]> git.ipfire.org Git - thirdparty/bind9.git/commitdiff
update OpenSSL PKCS#11 patch (rt19910)
authorFrancis Dupont <fdupont@isc.org>
Mon, 5 Oct 2009 13:20:06 +0000 (13:20 +0000)
committerFrancis Dupont <fdupont@isc.org>
Mon, 5 Oct 2009 13:20:06 +0000 (13:20 +0000)
bin/pkcs11/openssl-0.9.8k-patch

index 79f3aa80a72ee3ac93bc7d81dd327bafe94f9b00..f97396a6a95c2d177109ce55bb0db08b82cbb41f 100644 (file)
@@ -1,27 +1,30 @@
 Index: openssl/Configure
-diff -u openssl/Configure:1.1.3.1 openssl/Configure:1.6
+diff -u openssl/Configure:1.1.3.1 openssl/Configure:1.7
 --- openssl/Configure:1.1.3.1  Mon Feb 16 08:44:22 2009
-+++ openssl/Configure  Fri Sep  4 10:43:21 2009
++++ openssl/Configure  Mon Oct  5 13:16:50 2009
 @@ -12,7 +12,7 @@
  
  # see INSTALL for instructions.
  
 -my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [experimental-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [enable-montasm] [no-asm] [no-dso] [no-krb5] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity] os/compiler[:flags]\n";
-+my $usage="Usage: Configure --pk11-libname=PK11_LIB_LOCATION [no-<cipher> ...] [enable-<cipher> ...] [experimental-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [enable-montasm] [no-asm] [no-dso] [no-krb5] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity] os/compiler[:flags]\n";
++my $usage="Usage: Configure --pk11-libname=PK11_LIB_LOCATION --pk11-flavor=FLAVOR [no-<cipher> ...] [enable-<cipher> ...] [experimental-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [enable-montasm] [no-asm] [no-dso] [no-krb5] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity] os/compiler[:flags]\n";
  
  # Options:
  #
-@@ -21,6 +21,9 @@
+@@ -21,6 +21,12 @@
  # --prefix      prefix for the OpenSSL include, lib and bin directories
  #               (Default: the OPENSSLDIR directory)
  #
 +# --pk11-libname  PKCS#11 library name.
-+#               (Default: none)
++#               (No default)
++#
++# --pk11-flavor either crypto-accelerator or sign-only
++#               (No default)
 +#
  # --install_prefix  Additional prefix for package builders (empty by
  #               default).  This needn't be set in advance, you can
  #               just as well use "make INSTALL_PREFIX=/whatever install".
-@@ -329,7 +332,7 @@
+@@ -329,7 +335,7 @@
  "linux-ppc",  "gcc:-DB_ENDIAN -DTERMIO -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL::linux_ppc32.o::::::::::dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
  #### IA-32 targets...
  "linux-ia32-icc",     "icc:-DL_ENDIAN -DTERMIO -O2 -no_cpprt::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-KPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
@@ -30,17 +33,27 @@ diff -u openssl/Configure:1.1.3.1 openssl/Configure:1.6
  "linux-aout", "gcc:-DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -march=i486 -Wall::(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_out_asm}",
  ####
  "linux-generic64","gcc:-DTERMIO -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
-@@ -580,6 +583,9 @@
+@@ -337,7 +343,7 @@
+ "linux-ia64", "gcc:-DL_ENDIAN -DTERMIO -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK:${ia64_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
+ "linux-ia64-ecc","ecc:-DL_ENDIAN -DTERMIO -O2 -Wall -no_cpprt::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK:${ia64_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
+ "linux-ia64-icc","icc:-DL_ENDIAN -DTERMIO -O2 -Wall -no_cpprt::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK:${ia64_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
+-"linux-x86_64",       "gcc:-m64 -DL_ENDIAN -DTERMIO -O3 -Wall -DMD32_REG_T=int::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK BF_PTR2 DES_INT DES_UNROLL:${x86_64_asm}:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
++"linux-x86_64",       "gcc:-m64 -DL_ENDIAN -DTERMIO -O3 -Wall -DMD32_REG_T=int::-D_REENTRANT -pthread::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK BF_PTR2 DES_INT DES_UNROLL:${x86_64_asm}:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
+ #### SPARC Linux setups
+ # Ray Miller <ray.miller@computing-services.oxford.ac.uk> has patiently
+ # assisted with debugging of following two configs.
+@@ -580,6 +586,10 @@
  my $idx_ranlib = $idx++;
  my $idx_arflags = $idx++;
  
 +# PKCS#11 engine patch
 +my $pk11_libname="";
++my $pk11_flavor="";
 +
  my $prefix="";
  my $openssldir="";
  my $exe_ext="";
-@@ -812,6 +818,10 @@
+@@ -812,6 +822,14 @@
                                {
                                $flags.=$_." ";
                                }
@@ -48,10 +61,14 @@ diff -u openssl/Configure:1.1.3.1 openssl/Configure:1.6
 +                                {
 +                                $pk11_libname=$1;
 +                                }
++                      elsif (/^--pk11-flavor=(.*)$/)
++                              {
++                              $pk11_flavor=$1;
++                              }
                        elsif (/^--prefix=(.*)$/)
                                {
                                $prefix=$1;
-@@ -943,6 +953,13 @@
+@@ -943,6 +961,22 @@
        exit 0;
  }
  
@@ -61,11 +78,46 @@ diff -u openssl/Configure:1.1.3.1 openssl/Configure:1.6
 +        print STDERR "See README.pkcs11 for more information.\n";
 +        exit 1;
 +        }
++
++if (! $pk11_flavor
++    || !($pk11_flavor eq "crypto-accelerator" || $pk11_flavor eq "sign-only"))
++      {
++      print STDERR "You must set --pk11-flavor.\n";
++      print STDERR "Choices are crypto-accelerator and sign-only.\n";
++      print STDERR "See README.pkcs11 for more information.\n";
++      exit 1;
++      }
 +
  if ($target =~ m/^CygWin32(-.*)$/) {
        $target = "Cygwin".$1;
  }
-@@ -1103,6 +1120,8 @@
+@@ -1057,6 +1091,25 @@
+       print "\n";
+       }
++if ($pk11_flavor eq "crypto-accelerator")
++      {
++      $openssl_other_defines .= "#define OPENSSL_NO_HW_PKCS11SO\n";
++      $default_depflags .= " -DOPENSSL_NO_HW_PKCS11SO";
++      $depflags .= " -DOPENSSL_NO_HW_PKCS11SO";
++      $options .= " no-hw-pkcs11so";
++      print "    no-hw-pkcs11so  [pk11-flavor]";
++      print " OPENSSL_NO_HW_PKCS11SO\n";
++      }
++else
++      {
++      $openssl_other_defines .= "#define OPENSSL_NO_HW_PKCS11CA\n";
++      $default_depflags .= " -DOPENSSL_NO_HW_PKCS11CA";
++      $depflags .= " -DOPENSSL_NO_HW_PKCS11CA";
++      $options .= " no-hw-pkcs11ca";
++      print "    no-hw-pkcs11ca  [pk11-flavor]";
++      print " OPENSSL_NO_HW_PKCS11CA\n";
++}
++
+ my $IsMK1MF=scalar grep /^$target$/,@MK1MF_Builds;
+ $IsMK1MF=1 if ($target eq "mingw" && $^O ne "cygwin" && !is_msys());
+@@ -1103,6 +1156,8 @@
  if ($flags ne "")     { $cflags="$flags$cflags"; }
  else                  { $no_user_cflags=1;       }
  
@@ -74,7 +126,7 @@ diff -u openssl/Configure:1.1.3.1 openssl/Configure:1.6
  # Kerberos settings.  The flavor must be provided from outside, either through
  # the script "config" or manually.
  if (!$no_krb5)
-@@ -1456,6 +1475,7 @@
+@@ -1456,6 +1511,7 @@
        s/^VERSION=.*/VERSION=$version/;
        s/^MAJOR=.*/MAJOR=$major/;
        s/^MINOR=.*/MINOR=$minor/;
@@ -97,10 +149,27 @@ diff -u openssl/Makefile.org:1.1.3.1 openssl/Makefile.org:1.3
  OPENSSLDIR=/usr/local/ssl
  
 Index: openssl/README.pkcs11
-diff -u /dev/null openssl/README.pkcs11:1.5
---- /dev/null  Mon Oct  5 11:08:12 2009
-+++ openssl/README.pkcs11      Fri Sep  4 10:43:21 2009
-@@ -0,0 +1,230 @@
+diff -u /dev/null openssl/README.pkcs11:1.6
+--- /dev/null  Mon Oct  5 13:17:23 2009
++++ openssl/README.pkcs11      Mon Oct  5 13:16:50 2009
+@@ -0,0 +1,247 @@
++ISC modified
++============
++
++The PKCS#11 engine exists in two flavors, crypto-accelerator and
++sign-only. The first one is from the Solaris patch and uses the
++PKCS#11 device for all crypto operations it supports. The second
++is a stripped down version which provides only the useful
++function (i.e., signature with a RSA private key in the device
++protected key store and key loading).
++
++As a hint PKCS#11 boards should use the crypto-accelerator flavor,
++external PKCS#11 devices the sign-only. SCA 6000 is an example
++of the first, AEP Keyper of the second.
++
++Note it is mandatory to set a pk11-flavor (and only one) in
++config/Configure.
++
 +PKCS#11 engine support for OpenSSL 0.9.8j
 +=========================================
 +
@@ -403,27 +472,27 @@ diff -u openssl/crypto/opensslconf.h:1.1.3.1 openssl/crypto/opensslconf.h:1.5
  
  /* These default values were supplied by
 Index: openssl/crypto/engine/Makefile
-diff -u openssl/crypto/engine/Makefile:1.1.3.1 openssl/crypto/engine/Makefile:1.4
+diff -u openssl/crypto/engine/Makefile:1.1.3.1 openssl/crypto/engine/Makefile:1.5
 --- openssl/crypto/engine/Makefile:1.1.3.1     Wed Sep 17 17:10:59 2008
-+++ openssl/crypto/engine/Makefile     Fri Sep  4 10:43:22 2009
++++ openssl/crypto/engine/Makefile     Mon Oct  5 13:16:50 2009
 @@ -21,12 +21,14 @@
        eng_table.c eng_pkey.c eng_fat.c eng_all.c \
        tb_rsa.c tb_dsa.c tb_ecdsa.c tb_dh.c tb_ecdh.c tb_rand.c tb_store.c \
        tb_cipher.c tb_digest.c \
 -      eng_openssl.c eng_cnf.c eng_dyn.c eng_cryptodev.c eng_padlock.c
 +      eng_openssl.c eng_cnf.c eng_dyn.c eng_cryptodev.c eng_padlock.c \
-+      hw_pk11.c hw_pk11_pub.c
++      hw_pk11.c hw_pk11_pub.c hw_pk11so.c hw_pk11so_pub.c
  LIBOBJ= eng_err.o eng_lib.o eng_list.o eng_init.o eng_ctrl.o \
        eng_table.o eng_pkey.o eng_fat.o eng_all.o \
        tb_rsa.o tb_dsa.o tb_ecdsa.o tb_dh.o tb_ecdh.o tb_rand.o tb_store.o \
        tb_cipher.o tb_digest.o \
 -      eng_openssl.o eng_cnf.o eng_dyn.o eng_cryptodev.o eng_padlock.o
 +      eng_openssl.o eng_cnf.o eng_dyn.o eng_cryptodev.o eng_padlock.o \
-+      hw_pk11.o hw_pk11_pub.o
++      hw_pk11.o hw_pk11_pub.o hw_pk11so.o hw_pk11so_pub.o
  
  SRC= $(LIBSRC)
  
-@@ -286,6 +288,54 @@
+@@ -286,6 +288,102 @@
  eng_table.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
  eng_table.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h
  eng_table.o: eng_table.c
@@ -475,12 +544,60 @@ diff -u openssl/crypto/engine/Makefile:1.1.3.1 openssl/crypto/engine/Makefile:1.
 +hw_pk11_pub.o: ../../include/openssl/x509_vfy.h ../../include/openssl/pkcs7.h
 +hw_pk11_pub.o: ../../include/openssl/pem2.h ../cryptlib.h
 +hw_pk11_pub.o: ../../e_os.h hw_pk11_err.c hw_pk11_err.h hw_pk11_pub.c
++hw_pk11so.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
++hw_pk11so.o: ../../include/openssl/engine.h ../../include/openssl/ossl_typ.h
++hw_pk11so.o: ../../include/openssl/bn.h ../../include/openssl/rsa.h
++hw_pk11so.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
++hw_pk11so.o: ../../include/openssl/crypto.h ../../include/openssl/stack.h
++hw_pk11so.o: ../../include/openssl/safestack.h ../../include/openssl/opensslv.h
++hw_pk11so.o: ../../include/openssl/symhacks.h ../../include/openssl/dsa.h
++hw_pk11so.o: ../../include/openssl/dh.h ../../include/openssl/rand.h
++hw_pk11so.o: ../../include/openssl/ui.h ../../include/openssl/err.h
++hw_pk11so.o: ../../include/openssl/lhash.h ../../include/openssl/dso.h
++hw_pk11so.o: ../../include/openssl/pem.h ../../include/openssl/evp.h
++hw_pk11so.o: ../../include/openssl/md2.h ../../include/openssl/md4.h
++hw_pk11so.o: ../../include/openssl/md5.h ../../include/openssl/sha.h
++hw_pk11so.o: ../../include/openssl/ripemd.h ../../include/openssl/des.h
++hw_pk11so.o: ../../include/openssl/des_old.h ../../include/openssl/ui_compat.h
++hw_pk11so.o: ../../include/openssl/rc4.h ../../include/openssl/rc2.h
++hw_pk11so.o: ../../crypto/rc5/rc5.h ../../include/openssl/blowfish.h
++hw_pk11so.o: ../../include/openssl/cast.h ../../include/openssl/idea.h
++hw_pk11so.o: ../../crypto/mdc2/mdc2.h ../../include/openssl/aes.h
++hw_pk11so.o: ../../include/openssl/objects.h ../../include/openssl/obj_mac.h
++hw_pk11so.o: ../../include/openssl/x509.h ../../include/openssl/buffer.h
++hw_pk11so.o: ../../include/openssl/x509_vfy.h ../../include/openssl/pkcs7.h
++hw_pk11so.o: ../../include/openssl/pem2.h ../cryptlib.h
++hw_pk11so.o: ../../e_os.h hw_pk11_err.c hw_pk11_err.h hw_pk11so.c
++hw_pk11so_pub.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
++hw_pk11so_pub.o: ../../include/openssl/engine.h ../../include/openssl/ossl_typ.h
++hw_pk11so_pub.o: ../../include/openssl/bn.h ../../include/openssl/rsa.h
++hw_pk11so_pub.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
++hw_pk11so_pub.o: ../../include/openssl/crypto.h ../../include/openssl/stack.h
++hw_pk11so_pub.o: ../../include/openssl/safestack.h ../../include/openssl/opensslv.h
++hw_pk11so_pub.o: ../../include/openssl/symhacks.h ../../include/openssl/dsa.h
++hw_pk11so_pub.o: ../../include/openssl/dh.h ../../include/openssl/rand.h
++hw_pk11so_pub.o: ../../include/openssl/ui.h ../../include/openssl/err.h
++hw_pk11so_pub.o: ../../include/openssl/lhash.h ../../include/openssl/dso.h
++hw_pk11so_pub.o: ../../include/openssl/pem.h ../../include/openssl/evp.h
++hw_pk11so_pub.o: ../../include/openssl/md2.h ../../include/openssl/md4.h
++hw_pk11so_pub.o: ../../include/openssl/md5.h ../../include/openssl/sha.h
++hw_pk11so_pub.o: ../../include/openssl/ripemd.h ../../include/openssl/des.h
++hw_pk11so_pub.o: ../../include/openssl/des_old.h ../../include/openssl/ui_compat.h
++hw_pk11so_pub.o: ../../include/openssl/rc4.h ../../include/openssl/rc2.h
++hw_pk11so_pub.o: ../../crypto/rc5/rc5.h ../../include/openssl/blowfish.h
++hw_pk11so_pub.o: ../../include/openssl/cast.h ../../include/openssl/idea.h
++hw_pk11so_pub.o: ../../crypto/mdc2/mdc2.h ../../include/openssl/aes.h
++hw_pk11so_pub.o: ../../include/openssl/objects.h ../../include/openssl/obj_mac.h
++hw_pk11so_pub.o: ../../include/openssl/x509.h ../../include/openssl/buffer.h
++hw_pk11so_pub.o: ../../include/openssl/x509_vfy.h ../../include/openssl/pkcs7.h
++hw_pk11so_pub.o: ../../include/openssl/pem2.h ../cryptlib.h
++hw_pk11so_pub.o: ../../e_os.h hw_pk11_err.c hw_pk11_err.h hw_pk11so_pub.c
  tb_cipher.o: ../../e_os.h ../../include/openssl/asn1.h
  tb_cipher.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
  tb_cipher.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 Index: openssl/crypto/engine/cryptoki.h
 diff -u /dev/null openssl/crypto/engine/cryptoki.h:1.4
---- /dev/null  Mon Oct  5 11:08:14 2009
+--- /dev/null  Mon Oct  5 13:17:24 2009
 +++ openssl/crypto/engine/cryptoki.h   Thu Dec 18 00:14:12 2008
 @@ -0,0 +1,103 @@
 +/*
@@ -587,36 +704,62 @@ diff -u /dev/null openssl/crypto/engine/cryptoki.h:1.4
 +
 +#endif        /* _CRYPTOKI_H */
 Index: openssl/crypto/engine/eng_all.c
-diff -u openssl/crypto/engine/eng_all.c:1.1.3.1 openssl/crypto/engine/eng_all.c:1.2
+diff -u openssl/crypto/engine/eng_all.c:1.1.3.1 openssl/crypto/engine/eng_all.c:1.3
 --- openssl/crypto/engine/eng_all.c:1.1.3.1    Wed Jun  4 18:01:39 2008
-+++ openssl/crypto/engine/eng_all.c    Wed Oct 15 15:39:48 2008
-@@ -110,6 +110,9 @@
++++ openssl/crypto/engine/eng_all.c    Mon Oct  5 13:16:50 2009
+@@ -110,6 +110,14 @@
  #if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG)
        ENGINE_load_capi();
  #endif
 +#ifndef OPENSSL_NO_HW_PKCS11
-+      ENGINE_load_pk11();
++#ifndef OPENSSL_NO_HW_PKCS11CA
++      ENGINE_load_pk11ca();
++#endif
++#ifndef OPENSSL_NO_HW_PKCS11SO
++      ENGINE_load_pk11so();
++#endif
 +#endif
  #endif
        }
  
+Index: openssl/crypto/engine/eng_list.c
+diff -u openssl/crypto/engine/eng_list.c:1.1.3.1 openssl/crypto/engine/eng_list.c:1.2
+--- openssl/crypto/engine/eng_list.c:1.1.3.1   Sat Aug  6 10:34:35 2005
++++ openssl/crypto/engine/eng_list.c   Mon Oct  5 13:16:50 2009
+@@ -408,7 +408,11 @@
+                               !ENGINE_ctrl_cmd_string(iterator, "DIR_ADD",
+                                       load_dir, 0) ||
+                               !ENGINE_ctrl_cmd_string(iterator, "LOAD", NULL, 0))
++                      {
++                              if (iterator)
++                                      ENGINE_free(iterator);
+                               goto notfound;
++                      }
+               return iterator;
+               }
+ notfound:
 Index: openssl/crypto/engine/engine.h
-diff -u openssl/crypto/engine/engine.h:1.1.3.1 openssl/crypto/engine/engine.h:1.2
+diff -u openssl/crypto/engine/engine.h:1.1.3.1 openssl/crypto/engine/engine.h:1.3
 --- openssl/crypto/engine/engine.h:1.1.3.1     Wed Jun  4 18:01:40 2008
-+++ openssl/crypto/engine/engine.h     Wed Oct 15 15:39:48 2008
-@@ -337,6 +337,7 @@
++++ openssl/crypto/engine/engine.h     Mon Oct  5 13:16:50 2009
+@@ -337,6 +337,12 @@
  void ENGINE_load_ubsec(void);
  #endif
  void ENGINE_load_cryptodev(void);
-+void ENGINE_load_pk11(void);
++#ifndef OPENSSL_NO_HW_PKCS11CA
++void ENGINE_load_pk11ca(void);
++#endif
++#ifndef OPENSSL_NO_HW_PKCS11SO
++void ENGINE_load_pk11so(void);
++#endif
  void ENGINE_load_padlock(void);
  void ENGINE_load_builtin_engines(void);
  #ifndef OPENSSL_NO_CAPIENG
-Index: openssl/crypto/engine/hw_pk11-kp.c
-diff -u /dev/null openssl/crypto/engine/hw_pk11-kp.c:1.20
---- /dev/null  Mon Oct  5 11:08:14 2009
-+++ openssl/crypto/engine/hw_pk11-kp.c Tue Sep  1 06:02:18 2009
-@@ -0,0 +1,1611 @@
+Index: openssl/crypto/engine/hw_pk11.c
+diff -u /dev/null openssl/crypto/engine/hw_pk11.c:1.26
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11.c    Mon Oct  5 13:16:50 2009
+@@ -0,0 +1,3927 @@
 +/*
 + * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 + * Use is subject to license terms.
@@ -685,12 +828,6 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11-kp.c:1.20
 + *
 + */
 +
-+/* Modified to keep only RNG and RSA Sign */
-+
-+#ifdef OPENSSL_NO_RSA
-+#error RSA is disabled
-+#endif
-+
 +#include <stdio.h>
 +#include <stdlib.h>
 +#include <string.h>
@@ -705,10 +842,19 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11-kp.c:1.20
 +#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>
 +
 +#ifdef OPENSSL_SYS_WIN32
 +typedef int pid_t;
@@ -735,19 +881,29 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11-kp.c:1.20
 +
 +#ifndef OPENSSL_NO_HW
 +#ifndef OPENSSL_NO_HW_PK11
++#ifndef OPENSSL_NO_HW_PK11CA
 +
 +/* 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
-+
-+#ifndef OPENSSL_NO_DSA
-+#define OPENSSL_NO_DSA
-+#endif
-+#ifndef OPENSSL_NO_DH
-+#define OPENSSL_NO_DH
++/* #undef     DEBUG_SLOT_SELECTION */
++/*
++ * Solaris specific code. See comment at check_hw_mechanisms() for more
++ * information.
++ */
++#if defined (__SVR4) && defined (__sun)
++#undef        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
++
 +#ifdef OPENSSL_SYS_WIN32
 +#pragma pack(push, cryptoki, 1)
 +#include "cryptoki.h"
@@ -757,8 +913,28 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11-kp.c:1.20
 +#include "cryptoki.h"
 +#include "pkcs11.h"
 +#endif
++#include "hw_pk11ca.h"
 +#include "hw_pk11_err.c"
 +
++#ifdef        SOLARIS_AES_CTR
++/*
++ * NIDs for AES counter mode that will be defined during the engine
++ * initialization.
++ */
++static int NID_aes_128_ctr = NID_undef;
++static int NID_aes_192_ctr = NID_undef;
++static int NID_aes_256_ctr = NID_undef;
++#endif        /* SOLARIS_AES_CTR */
++
++#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.
++ */
++static int *hw_cnids;
++static 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];
 +
@@ -819,25 +995,117 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11-kp.c:1.20
 +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 session,
 +      CK_OBJECT_HANDLE oh);
 +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(sess_hdl, obj_hdl, retval, uselock, alg_type)   \
 +      {                                                               \
 +      if (uselock)                                                    \
@@ -859,3618 +1127,2765 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11-kp.c:1.20
 +              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_recover = 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;
 +
-+/*
-+ * 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
-+#define PK11_CMD_PIN                  (ENGINE_CMD_BASE+1)
-+#define PK11_CMD_SLOT                 (ENGINE_CMD_BASE+2)
-+static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
++typedef struct PK11_CIPHER_st
 +      {
-+              {
-+              PK11_CMD_SO_PATH,
-+              "SO_PATH",
-+              "Specifies the path to the 'pkcs#11' shared library",
-+              ENGINE_CMD_FLAG_STRING
-+              },
-+              {
-+              PK11_CMD_PIN,
-+              "PIN",
-+              "Specifies the pin code",
-+              ENGINE_CMD_FLAG_STRING
-+              },
-+              {
-+              PK11_CMD_SLOT,
-+              "SLOT",
-+              "Specifies the slot (default is auto select)",
-+              ENGINE_CMD_FLAG_NUMERIC,
-+              },
-+              {0, NULL, NULL, 0}
-+      };
-+
++      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 RAND_METHOD pk11_random =
++static PK11_CIPHER ciphers[] =
 +      {
-+      pk11_rand_seed,
-+      pk11_rand_bytes,
-+      pk11_rand_cleanup,
-+      pk11_rand_add,
-+      pk11_rand_bytes,
-+      pk11_rand_status
++      { 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;
 +
-+/* 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";
++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, },
++      };
 +
 +/*
-+ * These is the static string constant for the DSO file name and the function
-+ * symbol names to bind to.
++ * 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
 + */
-+static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
-+
-+static CK_SLOT_ID pubkey_SLOTID = 0;
-+static CK_SLOT_ID rand_SLOTID = 0;
-+static CK_SLOT_ID SLOTID = 0;
-+char *pk11_pin = NULL;
-+static CK_BBOOL pk11_library_initialized = FALSE;
-+static CK_BBOOL pk11_atfork_initialized = 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)
++typedef struct PK11_CIPHER_STATE_st
 +      {
-+#ifndef NOPTHREADS
-+      int type;
-+
-+      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);
-+
-+      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);
-+              }
++      PK11_SESSION    *sp;
++      } PK11_CIPHER_STATE;
 +
-+      return (1);
 +
-+malloc_err:
-+      pk11_free_all_locks();
-+      PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
-+      return (0);
-+#else
-+      return (1);
-+#endif
-+      }
++/*
++ * 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.
++ */
 +
-+static void pk11_free_all_locks(void)
++/* DES CBC EVP */
++static const EVP_CIPHER pk11_des_cbc =
 +      {
-+#ifndef NOPTHREADS
-+      int type;
-+
-+      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;
-+              }
++      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
++      };
 +
-+      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;
-+                      }
-+              }
-+#endif
-+      }
++/* 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
++      };
 +
 +/*
-+ * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
++ * 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 int bind_pk11(ENGINE *e)
++static const EVP_CIPHER pk11_des_ecb =
 +      {
-+      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))
-+              return (0);
-+
-+      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 */
-+              }
-+
-+      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);
-+
-+      /* Ensure the pk11 error handling is set up */
-+      ERR_load_pk11_strings();
-+
-+      return (1);
-+      }
++      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
++      };
 +
-+/* Dynamic engine support is disabled at a higher level for Solaris */
-+#ifdef        ENGINE_DYNAMIC_SUPPORT
-+static int bind_helper(ENGINE *e, const char *id)
++static const EVP_CIPHER pk11_3des_ecb =
 +      {
-+      if (id && (strcmp(id, engine_pk11_id) != 0))
-+              return (0);
-+
-+      if (!bind_pk11(e))
-+              return (0);
-+
-+      return (1);
-+      }
++      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
++      };
 +
-+IMPLEMENT_DYNAMIC_CHECK_FN()
-+IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
 +
-+#else
-+static ENGINE *engine_pk11(void)
++static const EVP_CIPHER pk11_aes_128_cbc =
 +      {
-+      ENGINE *ret = ENGINE_new();
-+
-+      if (!ret)
-+              return (NULL);
-+
-+      if (!bind_pk11(ret))
-+              {
-+              ENGINE_free(ret);
-+              return (NULL);
-+              }
-+
-+      return (ret);
-+      }
++      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
++      };
 +
-+void
-+ENGINE_load_pk11(void)
++static const EVP_CIPHER pk11_aes_192_cbc =
 +      {
-+      ENGINE *e_pk11 = NULL;
++      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
++      };
 +
-+      /*
-+       * 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 */
++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
++      };
 +
 +/*
-+ * These are the static string constants for the DSO file name and
-+ * the function symbol names to bind to.
++ * ECB modes don't use IV so that's why set_asn1_parameters and
++ * get_asn1_parameters are set to NULL.
 + */
-+static const char *PK11_LIBNAME = NULL;
-+
-+static const char *get_PK11_LIBNAME(void)
++static const EVP_CIPHER pk11_aes_128_ecb =
 +      {
-+      if (PK11_LIBNAME)
-+              return (PK11_LIBNAME);
-+
-+      return (def_PK11_LIBNAME);
-+      }
++      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 void free_PK11_LIBNAME(void)
++static const EVP_CIPHER pk11_aes_192_ecb =
 +      {
-+      if (PK11_LIBNAME)
-+              OPENSSL_free((void*)PK11_LIBNAME);
-+
-+      PK11_LIBNAME = NULL;
-+      }
++      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 long set_PK11_LIBNAME(const char *name)
++static const EVP_CIPHER pk11_aes_256_ecb =
 +      {
-+      free_PK11_LIBNAME();
++      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
++      };
 +
-+      return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
-+      }
++#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
++      };
 +
-+/* acquire all engine specific mutexes before fork */
-+static void pk11_fork_prepare(void)
++static EVP_CIPHER pk11_aes_192_ctr =
 +      {
-+#ifndef NOPTHREADS
-+      int i;
++      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
++      };
 +
-+      if (!pk11_library_initialized)
-+              return;
++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 */
 +
-+      LOCK_OBJSTORE(OP_RSA);
-+      for (i = 0; i < OP_MAX; i++)
-+              {
-+              (void) pthread_mutex_lock(session_cache[i].lock);
-+              }
-+#endif
-+      }
++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
++      };
 +
-+/* release all engine specific mutexes */
-+static void pk11_fork_parent(void)
++static const EVP_CIPHER pk11_rc4 =
 +      {
-+#ifndef NOPTHREADS
-+      int i;
++      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
++      };
 +
-+      if (!pk11_library_initialized)
-+              return;
++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),
++      };
 +
-+      for (i = OP_MAX - 1; i >= 0; i--)
-+              {
-+              (void) pthread_mutex_unlock(session_cache[i].lock);
-+              }
-+      UNLOCK_OBJSTORE(OP_RSA);
-+#endif
-+      }
++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),
++      };
 +
-+/*
-+ * same situation as in parent - we need to unlock all locks to make them
-+ * accessible to all threads.
-+ */
-+static void pk11_fork_child(void)
++static const EVP_MD pk11_sha224 =
 +      {
-+#ifndef NOPTHREADS
-+      int i;
++      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),
++      };
 +
-+      if (!pk11_library_initialized)
-+              return;
++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),
++      };
 +
-+      for (i = OP_MAX - 1; i >= 0; i--)
-+              {
-+              (void) pthread_mutex_unlock(session_cache[i].lock);
-+              }
-+      UNLOCK_OBJSTORE(OP_RSA);
-+#endif
-+      }
++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),
++      };
 +
-+/* Initialization function for the pk11 engine */
-+static int pk11_init(ENGINE *e)
-+{
-+      return (pk11_library_init(e));
-+}
++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.
-+ * 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.
++ * The definitions for control commands specific to this engine
 + */
-+/* ARGSUSED */
-+static int pk11_library_init(ENGINE *e)
++#define PK11_CMD_SO_PATH              ENGINE_CMD_BASE
++#define PK11_CMD_PIN                  (ENGINE_CMD_BASE+1)
++#define PK11_CMD_SLOT                 (ENGINE_CMD_BASE+2)
++static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
 +      {
-+      CK_C_GetFunctionList p;
-+      CK_RV rv = CKR_OK;
-+      CK_INFO info;
-+      int any_slot_found;
-+      int i;
-+#ifndef OPENSSL_SYS_WIN32
-+      struct sigaction sigint_act, sigterm_act, sighup_act;
-+#endif
-+
-+      /*
-+       * 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)
++              PK11_CMD_SO_PATH,
++              "SO_PATH",
++              "Specifies the path to the 'pkcs#11' shared library",
++              ENGINE_CMD_FLAG_STRING
++              },
 +              {
-+              PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
-+              goto err;
-+              }
-+
-+      /* get the C_GetFunctionList function from the loaded library */
-+      p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso,
-+              PK11_GET_FUNCTION_LIST);
-+      if (!p)
++              PK11_CMD_PIN,
++              "PIN",
++              "Specifies the pin code",
++              ENGINE_CMD_FLAG_STRING
++              },
 +              {
-+              PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
-+              goto err;
-+              }
++              PK11_CMD_SLOT,
++              "SLOT",
++              "Specifies the slot (default is auto select)",
++              ENGINE_CMD_FLAG_NUMERIC,
++              },
++              {0, NULL, NULL, 0}
++      };
 +
-+      /* 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;
-+              }
 +
-+#ifndef OPENSSL_SYS_WIN32
-+      /* Not all PKCS#11 library are signal safe! */
++static RAND_METHOD pk11_random =
++      {
++      pk11_rand_seed,
++      pk11_rand_bytes,
++      pk11_rand_cleanup,
++      pk11_rand_add,
++      pk11_rand_bytes,
++      pk11_rand_status
++      };
 +
-+      (void) memset(&sigint_act, 0, sizeof(sigint_act));
-+      (void) memset(&sigterm_act, 0, sizeof(sigterm_act));
-+      (void) memset(&sighup_act, 0, sizeof(sighup_act));
-+      (void) sigaction(SIGINT, NULL, &sigint_act);
-+      (void) sigaction(SIGTERM, NULL, &sigterm_act);
-+      (void) sigaction(SIGHUP, NULL, &sighup_act);
-+#endif
-+      rv = pFuncList->C_Initialize(NULL_PTR);
-+#ifndef OPENSSL_SYS_WIN32
-+      (void) sigaction(SIGINT, &sigint_act, NULL);
-+      (void) sigaction(SIGTERM, &sigterm_act, NULL);
-+      (void) sigaction(SIGHUP, &sighup_act, NULL);
-+#endif
-+      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;
-+              }
++/* Constants used when creating the ENGINE */
++#ifdef OPENSSL_NO_HW_PK11SO
++#error "can't load both crypto-accelerator and sign-only PKCS#11 engines"
++#endif
++static const char *engine_pk11_id = "pkcs11";
++static const char *engine_pk11_name =
++      "PKCS #11 engine support (crypto accelerator)";
 +
-+      if (pk11_choose_slots(&any_slot_found) == 0)
-+              goto err;
++CK_FUNCTION_LIST_PTR pFuncList = NULL;
++static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
 +
-+      /*
-+       * 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);
++/*
++ * These is the static string constant for the DSO file name and the function
++ * symbol names to bind to.
++ */
++static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
 +
-+      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;
-+                      }
-+              }
++static CK_BBOOL true = TRUE;
++static CK_BBOOL false = FALSE;
++static CK_SLOT_ID pubkey_SLOTID = 0;
++static CK_SLOT_ID rand_SLOTID = 0;
++static CK_SLOT_ID SLOTID = 0;
++char *pk11_pin = NULL;
++static CK_BBOOL pk11_library_initialized = FALSE;
++static CK_BBOOL pk11_atfork_initialized = FALSE;
++static int pk11_pid = 0;
 +
-+      pk11_library_initialized = 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;
++static DSO *pk11_dso = NULL;
 +
++/* allocate and initialize all locks used by the engine itself */
++static int pk11_init_all_locks(void)
++      {
 +#ifndef NOPTHREADS
-+      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 = TRUE;
-+              }
-+#endif
++      int type;
 +
-+      return (1);
++#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 */
 +
-+err:
-+      return (0);
-+      }
++#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 */
 +
-+/* Destructor (complements the "ENGINE_pk11()" constructor) */
-+/* ARGSUSED */
-+static int pk11_destroy(ENGINE *e)
-+      {
-+      free_PK11_LIBNAME();
-+      ERR_unload_pk11_strings();
-+      if (pk11_pin) {
-+              memset(pk11_pin, 0, strlen(pk11_pin));
-+              OPENSSL_free((void*)pk11_pin);
-+      }
-+      pk11_pin = NULL;
-+      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_pin) {
-+              memset(pk11_pin, 0, strlen(pk11_pin));
-+              OPENSSL_free((void*)pk11_pin);
-+      }
-+      pk11_pin = NULL;
-+
-+      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
++#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 */
 +
-+      if (!DSO_free(pk11_dso))
++      for (type = 0; type < OP_MAX; type++)
 +              {
-+              PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
-+              goto err;
++              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);
 +              }
-+      pk11_dso = NULL;
-+      pFuncList = NULL;
-+      pk11_library_initialized = 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:
++malloc_err:
++      pk11_free_all_locks();
++      PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
 +      return (0);
++#else
++      return (1);
++#endif
 +      }
 +
-+/* 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)(void))
++static void pk11_free_all_locks(void)
 +      {
-+      int initialized = ((pk11_dso == NULL) ? 0 : 1);
++#ifndef NOPTHREADS
++      int type;
 +
-+      switch (cmd)
++#ifndef OPENSSL_NO_RSA
++      if (find_lock[OP_RSA] != NULL)
 +              {
-+      case PK11_CMD_SO_PATH:
-+              if (p == NULL)
-+                      {
-+                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
-+                      return (0);
-+                      }
++              (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 */
 +
-+              if (initialized)
++      for (type = 0; type < OP_MAX; type++)
++              {
++              if (session_cache[type].lock != NULL)
 +                      {
-+                      PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
-+                      return (0);
++                      (void) pthread_mutex_destroy(session_cache[type].lock);
++                      OPENSSL_free(session_cache[type].lock);
++                      session_cache[type].lock = NULL;
 +                      }
-+
-+              return (set_PK11_LIBNAME((const char *)p));
-+      case PK11_CMD_PIN:
-+              if (pk11_pin) {
-+                      memset(pk11_pin, 0, strlen(pk11_pin));
-+                      OPENSSL_free((void*)pk11_pin);
 +              }
-+              pk11_pin = NULL;
++#endif
++      }
 +
-+              if (p == NULL)
-+                      {
-+                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
++/*
++ * 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);
-+                      }
 +
-+              pk11_pin = BUF_strdup(p);
-+              if (pk11_pin == NULL)
-+                      {
-+                      PK11err(PK11_F_GET_SESSION, PK11_R_MALLOC_FAILURE);
++      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);
-+                      }
-+              return (1);
-+      case PK11_CMD_SLOT:
-+              SLOTID = (CK_SLOT_ID)i;
-+#ifdef DEBUG_SLOT_SELECTION
-+              fprintf(stderr, "%s: slot set\n", PK11_DBG);
-+#endif
-+              return (1);
-+      default:
-+              break;
++#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);
 +
-+      PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
-+
-+      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;
++      if (pk11_have_recover != CK_TRUE)
++              pk11_rsa->rsa_pub_dec = rsa->rsa_pub_dec;
++#endif        /* OPENSSL_NO_RSA */
 +
++      /* Ensure the pk11 error handling is set up */
++      ERR_load_pk11_strings();
 +
-+/* Required function by the engine random interface. It does nothing here */
-+static void pk11_rand_cleanup(void)
-+      {
-+      return;
++      return (1);
 +      }
 +
-+/* ARGSUSED */
-+static void pk11_rand_add(const void *buf, int num, double add)
++/* Dynamic engine support is disabled at a higher level for Solaris */
++#ifdef        ENGINE_DYNAMIC_SUPPORT
++#error  "dynamic engine not supported"
++static int bind_helper(ENGINE *e, const char *id)
 +      {
-+      PK11_SESSION *sp;
++      if (id && (strcmp(id, engine_pk11_id) != 0))
++              return (0);
 +
-+      if ((sp = pk11_get_session(OP_RAND)) == NULL)
-+              return;
++      if (!bind_pk11(e))
++              return (0);
 +
-+      /*
-+       * 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;
++      return (1);
 +      }
 +
-+static void pk11_rand_seed(const void *buf, int num)
-+      {
-+      pk11_rand_add(buf, num, 0);
-+      }
++IMPLEMENT_DYNAMIC_CHECK_FN()
++IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
 +
-+static int pk11_rand_bytes(unsigned char *buf, int num)
++#else
++static ENGINE *engine_pk11(void)
 +      {
-+      CK_RV rv;
-+      PK11_SESSION *sp;
++      ENGINE *ret = ENGINE_new();
 +
-+      if ((sp = pk11_get_session(OP_RAND)) == NULL)
-+              return (0);
++      if (!ret)
++              return (NULL);
 +
-+      rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
-+      if (rv != CKR_OK)
++      if (!bind_pk11(ret))
 +              {
-+              PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
-+              pk11_return_session(sp, OP_RAND);
-+              return (0);
++              ENGINE_free(ret);
++              return (NULL);
 +              }
 +
-+      pk11_return_session(sp, OP_RAND);
-+      return (1);
++      return (ret);
 +      }
 +
-+/* Required function by the engine random interface. It does nothing here */
-+static int pk11_rand_status(void)
++void
++ENGINE_load_pk11(void)
 +      {
-+      return (1);
-+      }
++      ENGINE *e_pk11 = NULL;
 +
-+/* Free all BIGNUM structures from PK11_SESSION. */
-+static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
-+      {
-+      switch (optype)
++      /*
++       * 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)
 +              {
-+              case OP_RSA:
-+                      if (sp->opdata_rsa_n_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_rsa_n_num);
-+                              sp->opdata_rsa_n_num = NULL;
-+                              }
-+                      if (sp->opdata_rsa_e_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_rsa_e_num);
-+                              sp->opdata_rsa_e_num = NULL;
-+                              }
-+                      if (sp->opdata_rsa_d_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_rsa_d_num);
-+                              sp->opdata_rsa_d_num = NULL;
-+                              }
-+                      break;
-+              default:
-+                      break;
++              PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
++              return;
 +              }
-+      }
-+
-+/*
-+ * Get new PK11_SESSION structure ready for use. Every process must have
-+ * its own freelist of PK11_SESSION structures so handle fork() here
-+ * by destroying the old and creating new freelist.
-+ * The returned PK11_SESSION structure is disconnected from the freelist.
-+ */
-+PK11_SESSION *
-+pk11_get_session(PK11_OPTYPE optype)
-+      {
-+      PK11_SESSION *sp = NULL, *sp1, *freelist;
-+#ifndef NOPTHREADS
-+      pthread_mutex_t *freelist_lock = NULL;
-+#endif
-+      CK_RV rv;
 +
-+      switch (optype)
++      e_pk11 = engine_pk11();
++      if (!e_pk11)
 +              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+              case OP_RAND:
-+              case OP_DIGEST:
-+              case OP_CIPHER:
-+#ifndef NOPTHREADS
-+                      freelist_lock = session_cache[optype].lock;
-+#endif
-+                      break;
-+              default:
-+                      PK11err(PK11_F_GET_SESSION,
-+                              PK11_R_INVALID_OPERATION_TYPE);
-+                      return (NULL);
++              DSO_free(pk11_dso);
++              pk11_dso = NULL;
++              return;
 +              }
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_lock(freelist_lock);
-+#else
-+      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      freelist = session_cache[optype].head;
-+      sp = freelist;
 +
 +      /*
-+       * If the free list is empty, allocate new unitialized (filled
-+       * with zeroes) PK11_SESSION structure otherwise return first
-+       * structure from the freelist.
++       * 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 (sp == NULL)
-+              {
-+              if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
-+                      {
-+                      PK11err(PK11_F_GET_SESSION,
-+                              PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
-+              (void) memset(sp, 0, sizeof (PK11_SESSION));
-+              }
-+      else
++      if (!pk11_library_init(e_pk11))
 +              {
-+              freelist = sp->next;
++              DSO_free(pk11_dso);
++              pk11_dso = NULL;
++              ENGINE_free(e_pk11);
++              return;
 +              }
 +
-+      if (sp->pid != 0 && sp->pid != getpid())
-+              {
-+              /*
-+               * We are a new process and thus need to free any inherited
-+               * PK11_SESSION objects.
-+               */
-+              while ((sp1 = freelist) != NULL)
-+                      {
-+                      freelist = sp1->next;
-+                      /*
-+                       * NOTE: we do not want to call pk11_free_all_sessions()
-+                       * here because it would close underlying PKCS#11
-+                       * sessions and destroy all objects.
-+                       */
-+                      pk11_free_nums(sp1, optype);
-+                      OPENSSL_free(sp1);
-+                      }
-+
-+              /* we have to free the active list as well. */
-+              pk11_free_active_list(optype);
++      ENGINE_add(e_pk11);
 +
-+              /* Initialize the process */
-+              rv = pFuncList->C_Initialize(NULL_PTR);
-+              if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
-+                      {
-+                      PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
-+                          rv);
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      goto err;
-+                      }
++      ENGINE_free(e_pk11);
++      ERR_clear_error();
++      }
++#endif        /* ENGINE_DYNAMIC_SUPPORT */
 +
-+              /*
-+               * Choose slot here since the slot table is different on this
-+               * process. If we are here then we must have found at least one
-+               * usable slot before so we don't need to check any_slot_found.
-+               * See pk11_library_init()'s usage of this function for more
-+               * information.
-+               */
-+              if (pk11_choose_slots(NULL) == 0)
-+                      goto err;
++/*
++ * 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;
 +
-+              /* 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_GET_SESSION, PK11_R_OPENSESSION,
-+                          rv);
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      goto err;
-+                      }
++static const char *get_PK11_LIBNAME(void)
++      {
++      if (PK11_LIBNAME)
++              return (PK11_LIBNAME);
 +
-+              /* It is an inherited session and needs re-initialization. */
-+              if (pk11_setup_session(sp, optype) == 0)
-+                      {
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      }
-+              }
-+      if (sp->pid == 0)
-+              {
-+              /* It is a new session and needs initialization. */
-+              if (pk11_setup_session(sp, optype) == 0)
-+                      {
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      }
-+              }
++      return (def_PK11_LIBNAME);
++      }
 +
-+      /* set new head for the list of PK11_SESSION objects */
-+      session_cache[optype].head = freelist;
++static void free_PK11_LIBNAME(void)
++      {
++      if (PK11_LIBNAME)
++              OPENSSL_free((void*)PK11_LIBNAME);
 +
-+err:
-+      if (sp != NULL)
-+              sp->next = NULL;
++      PK11_LIBNAME = NULL;
++      }
 +
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_unlock(freelist_lock);
-+#else
-+      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
++static long set_PK11_LIBNAME(const char *name)
++      {
++      free_PK11_LIBNAME();
 +
-+      return (sp);
++      return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
 +      }
 +
-+
-+void
-+pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
++/* acquire all engine specific mutexes before fork */
++static void pk11_fork_prepare(void)
 +      {
 +#ifndef NOPTHREADS
-+      pthread_mutex_t *freelist_lock;
-+#endif
-+      PK11_SESSION *freelist;
++      int i;
 +
-+      if (sp == NULL || sp->pid != getpid())
++      if (!pk11_library_initialized)
 +              return;
 +
-+      switch (optype)
-+              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+              case OP_RAND:
-+              case OP_DIGEST:
-+              case OP_CIPHER:
-+#ifndef NOPTHREADS
-+                      freelist_lock = session_cache[optype].lock;
-+#endif
-+                      break;
-+              default:
-+                      PK11err(PK11_F_RETURN_SESSION,
-+                              PK11_R_INVALID_OPERATION_TYPE);
-+                      return;
++      LOCK_OBJSTORE(OP_RSA);
++      LOCK_OBJSTORE(OP_DSA);
++      LOCK_OBJSTORE(OP_DH);
++      for (i = 0; i < OP_MAX; i++)
++              {
++              (void) pthread_mutex_lock(session_cache[i].lock);
 +              }
-+
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_lock(freelist_lock);
-+#else
-+      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      freelist = session_cache[optype].head;
-+      sp->next = freelist;
-+      session_cache[optype].head = sp;
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_unlock(freelist_lock);
-+#else
-+      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
 +#endif
 +      }
 +
-+
-+/* Destroy all objects. This function is called when the engine is finished */
-+static int pk11_free_all_sessions()
++/* release all engine specific mutexes */
++static void pk11_fork_parent(void)
 +      {
-+      int ret = 1;
-+      int type;
++#ifndef NOPTHREADS
++      int i;
 +
-+      (void) pk11_destroy_rsa_key_objects(NULL);
++      if (!pk11_library_initialized)
++              return;
 +
-+      /*
-+       * We try to release as much as we can but any error means that we will
-+       * return 0 on exit.
-+       */
-+      for (type = 0; type < OP_MAX; type++)
++      for (i = OP_MAX - 1; i >= 0; i--)
 +              {
-+              if (pk11_free_session_list(type) == 0)
-+                      ret = 0;
++              (void) pthread_mutex_unlock(session_cache[i].lock);
 +              }
-+
-+      return (ret);
++      UNLOCK_OBJSTORE(OP_DH);
++      UNLOCK_OBJSTORE(OP_DSA);
++      UNLOCK_OBJSTORE(OP_RSA);
++#endif
 +      }
 +
 +/*
-+ * Destroy session structures from the linked list specified. Free as many
-+ * sessions as possible but any failure in C_CloseSession() means that we
-+ * return an error on return.
++ * same situation as in parent - we need to unlock all locks to make them
++ * accessible to all threads.
 + */
-+static int pk11_free_session_list(PK11_OPTYPE optype)
++static void pk11_fork_child(void)
 +      {
-+      CK_RV rv;
-+      PK11_SESSION *sp = NULL;
-+      PK11_SESSION *freelist = NULL;
-+      pid_t mypid = getpid();
 +#ifndef NOPTHREADS
-+      pthread_mutex_t *freelist_lock;
-+#endif
-+      int ret = 1;
++      int i;
 +
-+      switch (optype)
-+              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+              case OP_RAND:
-+              case OP_DIGEST:
-+              case OP_CIPHER:
-+#ifndef NOPTHREADS
-+                      freelist_lock = session_cache[optype].lock;
-+#endif
-+                      break;
-+              default:
-+                      PK11err(PK11_F_FREE_ALL_SESSIONS,
-+                              PK11_R_INVALID_OPERATION_TYPE);
-+                      return (0);
-+              }
++      if (!pk11_library_initialized)
++              return;
 +
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_lock(freelist_lock);
-+#else
-+      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      freelist = session_cache[optype].head;
-+      while ((sp = freelist) != NULL)
++      for (i = OP_MAX - 1; i >= 0; i--)
 +              {
-+              if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
-+                      {
-+                      rv = pFuncList->C_CloseSession(sp->session);
-+                      if (rv != CKR_OK)
-+                              {
-+                              PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
-+                                      PK11_R_CLOSESESSION, rv);
-+                              ret = 0;
-+                              }
-+                      }
-+              freelist = sp->next;
-+              pk11_free_nums(sp, optype);
-+              OPENSSL_free(sp);
++              (void) pthread_mutex_unlock(session_cache[i].lock);
 +              }
-+
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_unlock(freelist_lock);
-+#else
-+      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++      UNLOCK_OBJSTORE(OP_DH);
++      UNLOCK_OBJSTORE(OP_DSA);
++      UNLOCK_OBJSTORE(OP_RSA);
 +#endif
-+      return (ret);
 +      }
 +
++/* Initialization function for the pk11 engine */
++static int pk11_init(ENGINE *e)
++{
++      return (pk11_library_init(e));
++}
 +
-+static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
++/*
++ * 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_RV rv;
-+      CK_SLOT_ID myslot;
++      CK_C_GetFunctionList p;
++      CK_RV rv = CKR_OK;
++      CK_INFO info;
++      CK_ULONG ul_state_len;
++      int any_slot_found;
++      int i;
++#ifndef OPENSSL_SYS_WIN32
++      struct sigaction sigint_act, sigterm_act, sighup_act;
++#endif
 +
-+      switch (optype)
++      /*
++       * 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)
 +              {
-+              case OP_RSA:
-+                      myslot = pubkey_SLOTID;
-+                      break;
-+              case OP_RAND:
-+                      myslot = rand_SLOTID;
-+                      break;
-+              default:
-+                      PK11err(PK11_F_SETUP_SESSION,
-+                          PK11_R_INVALID_OPERATION_TYPE);
-+                      return (0);
++              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();
++                      }
 +              }
 +
-+      sp->session = CK_INVALID_HANDLE;
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+      rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
-+              NULL_PTR, NULL_PTR, &sp->session);
-+      if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
-+              {
-+              /*
-+               * We are probably a child process so force the
-+               * reinitialize of the session
-+               */
-+              pk11_library_initialized = FALSE;
-+              if (!pk11_library_init(NULL))
-+                      return (0);
-+              rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
-+                      NULL_PTR, NULL_PTR, &sp->session);
-+              }
-+      if (rv != CKR_OK)
++      if (pk11_dso == NULL)
 +              {
-+              PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
-+              return (0);
++              PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
++              goto err;
 +              }
 +
-+      sp->pid = getpid();
++#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 */
 +
-+      if (optype == OP_RSA)
++#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)
 +              {
-+              sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
-+              sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
-+              sp->opdata_rsa_pub = NULL;
-+              sp->opdata_rsa_n_num = NULL;
-+              sp->opdata_rsa_e_num = NULL;
-+              sp->opdata_rsa_priv = NULL;
-+              sp->opdata_rsa_d_num = NULL;
++              PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
++              goto err;
 +              }
 +
-+      return (1);
-+      }
++      /* 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;
++              }
 +
-+/* Destroy RSA public key from single session. */
-+int
-+pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
-+      {
-+      int ret = 0;
++#ifndef OPENSSL_SYS_WIN32
++      /* Not all PKCS#11 library are signal safe! */
 +
-+      if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
++      (void) memset(&sigint_act, 0, sizeof(sigint_act));
++      (void) memset(&sigterm_act, 0, sizeof(sigterm_act));
++      (void) memset(&sighup_act, 0, sizeof(sighup_act));
++      (void) sigaction(SIGINT, NULL, &sigint_act);
++      (void) sigaction(SIGTERM, NULL, &sigterm_act);
++      (void) sigaction(SIGHUP, NULL, &sighup_act);
++#endif
++      rv = pFuncList->C_Initialize(NULL_PTR);
++#ifndef OPENSSL_SYS_WIN32
++      (void) sigaction(SIGINT, &sigint_act, NULL);
++      (void) sigaction(SIGTERM, &sigterm_act, NULL);
++      (void) sigaction(SIGHUP, &sighup_act, NULL);
++#endif
++      if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
 +              {
-+              TRY_OBJ_DESTROY(sp->session, sp->opdata_rsa_pub_key,
-+                  ret, uselock, OP_RSA);
-+              sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
-+              sp->opdata_rsa_pub = NULL;
-+              if (sp->opdata_rsa_n_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_rsa_n_num);
-+                      sp->opdata_rsa_n_num = NULL;
-+                      }
-+              if (sp->opdata_rsa_e_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_rsa_e_num);
-+                      sp->opdata_rsa_e_num = NULL;
-+                      }
++              PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
++              goto err;
 +              }
 +
-+      return (ret);
-+      }
++      rv = pFuncList->C_GetInfo(&info);
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
++              goto err;
++              }
 +
-+/* Destroy RSA private key from single session. */
-+int
-+pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
-+      {
-+      int ret = 0;
++      if (pk11_choose_slots(&any_slot_found) == 0)
++              goto err;
 +
-+      if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
++      /*
++       * 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)
 +              {
-+              TRY_OBJ_DELETE(sp->session,
-+                             sp->opdata_rsa_priv_key,
-+                             ret, uselock, OP_RSA);
-+              sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
-+              sp->opdata_rsa_priv = NULL;
-+              if (sp->opdata_rsa_d_num != NULL)
++              /* 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)
 +                      {
-+                      BN_free(sp->opdata_rsa_d_num);
-+                      sp->opdata_rsa_d_num = NULL;
++                      PK11err_add_data(PK11_F_LIBRARY_INIT,
++                          PK11_R_OPENSESSION, rv);
++                      goto err;
 +                      }
 +              }
 +
-+      return (ret);
++      /*
++       * Disable digest if C_GetOperationState is not supported since
++       * this function is required by OpenSSL digest copy function
++       */
++      /* Keyper fails to return CKR_FUNCTION_NOT_SUPPORTED */
++      if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
++                      != CKR_OK) {
++#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;
 +      }
 +
-+/*
-+ * Destroy RSA key object wrapper. If session is NULL, try to destroy all
-+ * objects in the free list.
-+ */
-+int
-+pk11_destroy_rsa_key_objects(PK11_SESSION *session)
-+      {
-+      int ret = 1;
-+      PK11_SESSION *sp = NULL;
-+      PK11_SESSION *local_free_session;
-+      CK_BBOOL uselock = TRUE;
-+
-+      if (session != NULL)
-+              local_free_session = session;
-+      else
-+              {
-+#ifndef NOPTHREADS
-+              (void) pthread_mutex_lock(session_cache[OP_RSA].lock);
-+#else
-+              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+              local_free_session = session_cache[OP_RSA].head;
-+              uselock = FALSE;
-+              }
-+
++      pk11_library_initialized = TRUE;
++      pk11_pid = getpid();
 +      /*
-+       * go through the list of sessions and delete key objects
++       * if initialization of the locks fails pk11_init_all_locks()
++       * will do the cleanup.
 +       */
-+      while ((sp = local_free_session) != NULL)
-+              {
-+              local_free_session = sp->next;
++      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;
 +
-+              /*
-+               * Do not terminate list traversal if one of the
-+               * destroy operations fails.
-+               */
-+              if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
-+                      {
-+                      ret = 0;
-+                      continue;
-+                      }
-+              if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
++#ifndef NOPTHREADS
++      if (!pk11_atfork_initialized)
++              {
++              if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
++                  pk11_fork_child) != 0)
 +                      {
-+                      ret = 0;
-+                      continue;
++                      PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
++                      goto err;
 +                      }
++              pk11_atfork_initialized = TRUE;
 +              }
-+
-+#ifndef NOPTHREADS
-+      if (session == NULL)
-+              (void) pthread_mutex_unlock(session_cache[OP_RSA].lock);
-+#else
-+      if (session == NULL)
-+              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
 +#endif
 +
-+      return (ret);
++      return (1);
++
++err:
++      return (0);
 +      }
 +
-+static int pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh)
++/* Destructor (complements the "ENGINE_pk11()" constructor) */
++/* ARGSUSED */
++static int pk11_destroy(ENGINE *e)
 +      {
-+      CK_RV rv;
-+      rv = pFuncList->C_DestroyObject(session, oh);
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
-+                  rv);
-+              return (0);
-+              }
-+
++      free_PK11_LIBNAME();
++      ERR_unload_pk11_strings();
++      if (pk11_pin) {
++              memset(pk11_pin, 0, strlen(pk11_pin));
++              OPENSSL_free((void*)pk11_pin);
++      }
++      pk11_pin = NULL;
 +      return (1);
 +      }
 +
-+
 +/*
-+ * Public key mechanisms optionally supported
-+ *
-+ * CKM_RSA_X_509
-+ * CKM_RSA_PKCS
-+ *
-+ * The first slot that supports at least one of those mechanisms is chosen as a
-+ * public key slot.
-+ *
-+ * The output of this function is a set of global variables indicating which
-+ * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
-+ * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
-+ * variables carry information about which slot was chosen for (a) public key
-+ * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
++ * Termination function to clean up the session, the token, and the pk11
++ * library.
 + */
-+static int
-+pk11_choose_slots(int *any_slot_found)
++/* ARGSUSED */
++static int pk11_finish(ENGINE *e)
 +      {
-+      CK_SLOT_ID_PTR pSlotList = NULL_PTR;
-+      CK_ULONG ulSlotCount = 0;
-+      CK_MECHANISM_INFO mech_info;
-+      CK_TOKEN_INFO token_info;
-+      unsigned int i;
-+      CK_RV rv;
-+      CK_SLOT_ID best_slot_sofar = 0;
-+      CK_BBOOL found_candidate_slot = CK_FALSE;
-+      CK_SLOT_ID current_slot = 0;
-+
-+      /* let's initialize the output parameter */
-+      if (any_slot_found != NULL)
-+              *any_slot_found = 0;
++      int i;
 +
-+      /* Get slot list for memory allocation */
-+      rv = pFuncList->C_GetSlotList(0, NULL_PTR, &ulSlotCount);
++      if (pk11_pin) {
++              memset(pk11_pin, 0, strlen(pk11_pin));
++              OPENSSL_free((void*)pk11_pin);
++      }
++      pk11_pin = NULL;
 +
-+      if (rv != CKR_OK)
++      if (pk11_dso == NULL)
 +              {
-+              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
-+              return (0);
++              PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
++              goto err;
 +              }
 +
-+      /* it's not an error if we didn't find any providers */
-+      if (ulSlotCount == 0)
-+              {
-+#ifdef        DEBUG_SLOT_SELECTION
-+              fprintf(stderr, "%s: no crypto providers found\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              return (1);
-+              }
++      OPENSSL_assert(pFuncList != NULL);
 +
-+      pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
++      if (pk11_free_all_sessions() == 0)
++              goto err;
 +
-+      if (pSlotList == NULL)
-+              {
-+              PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
-+              return (0);
-+              }
++      /* free all active lists */
++      for (i = 0; i < OP_MAX; i++)
++              pk11_free_active_list(i);
 +
-+      /* Get the slot list for processing */
-+      rv = pFuncList->C_GetSlotList(0, pSlotList, &ulSlotCount);
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
-+              OPENSSL_free(pSlotList);
-+              return (0);
-+              }
++      pFuncList->C_CloseSession(global_session);
++      global_session = CK_INVALID_HANDLE;
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
-+      fprintf(stderr, "%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
++      /*
++       * Since we are part of a library (libcrypto.so), calling this function
++       * may have side-effects.
++       */
++#if 0
++      pFuncList->C_Finalize(NULL);
++#endif
 +
-+      fprintf(stderr, "%s: == checking rand slots ==\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+      for (i = 0; i < ulSlotCount; i++)
++      if (!DSO_free(pk11_dso))
 +              {
-+              current_slot = pSlotList[i];
-+
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              /* Check if slot has random support. */
-+              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
-+              if (rv != CKR_OK)
-+                      continue;
-+
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+
-+              if (token_info.flags & CKF_RNG)
-+                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: this token has CKF_RNG flag\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      pk11_have_random = CK_TRUE;
-+                      rand_SLOTID = current_slot;
-+                      break;
-+                      }
++              PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
++              goto err;
 +              }
++      pk11_dso = NULL;
++      pFuncList = NULL;
++      pk11_library_initialized = 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();
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: == checking pubkey slots ==\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+
-+      pubkey_SLOTID = pSlotList[0];
-+      for (i = 0; i < ulSlotCount; i++)
-+              {
-+              CK_BBOOL slot_has_rsa = CK_FALSE;
-+              current_slot = pSlotList[i];
-+
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
-+              if (rv != CKR_OK)
-+                      continue;
++      return (1);
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
-+#endif        /* DEBUG_SLOT_SELECTION */
++err:
++      return (0);
++      }
 +
-+              /*
-+               * Check if this slot is capable of signing with CKM_RSA_PKCS.
-+               */
-+              rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
-+                      &mech_info);
++/* 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)(void))
++      {
++      int initialized = ((pk11_dso == NULL) ? 0 : 1);
 +
-+              if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN)))
++      switch (cmd)
++              {
++      case PK11_CMD_SO_PATH:
++              if (p == NULL)
 +                      {
-+                      slot_has_rsa = CK_TRUE;
++                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
++                      return (0);
 +                      }
 +
-+              if (!found_candidate_slot && slot_has_rsa)
++              if (initialized)
 +                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+                      fprintf(stderr,
-+                          "%s: potential slot: %d\n", PK11_DBG, current_slot);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      best_slot_sofar = current_slot;
-+                      pk11_have_rsa = slot_has_rsa;
-+                      found_candidate_slot = CK_TRUE;
-+#ifdef        DEBUG_SLOT_SELECTION
-+                      fprintf(stderr,
-+                          "%s: setting found_candidate_slot to CK_TRUE\n",
-+                          PK11_DBG);
-+                      fprintf(stderr,
-+                          "%s: best so far slot: %d\n", PK11_DBG,
-+                          best_slot_sofar);
++                      PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
++                      return (0);
 +                      }
-+              else
++
++              return (set_PK11_LIBNAME((const char *)p));
++      case PK11_CMD_PIN:
++              if (pk11_pin) {
++                      memset(pk11_pin, 0, strlen(pk11_pin));
++                      OPENSSL_free((void*)pk11_pin);
++              }
++              pk11_pin = NULL;
++
++              if (p == NULL)
 +                      {
-+                      fprintf(stderr,
-+                          "%s: no rsa\n", PK11_DBG);
++                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
++                      return (0);
 +                      }
-+#else
-+                      } /* if */
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              } /* for */
 +
-+      if (found_candidate_slot)
-+              {
-+              pubkey_SLOTID = best_slot_sofar;
++              pk11_pin = BUF_strdup(p);
++              if (pk11_pin == NULL)
++                      {
++                      PK11err(PK11_F_GET_SESSION, PK11_R_MALLOC_FAILURE);
++                      return (0);
++                      }
++              return (1);
++      case PK11_CMD_SLOT:
++              SLOTID = (CK_SLOT_ID)i;
++#ifdef DEBUG_SLOT_SELECTION
++              fprintf(stderr, "%s: slot set\n", PK11_DBG);
++#endif
++              return (1);
++      default:
++              break;
 +              }
 +
-+      /*SLOTID = pSlotList[0];*/
++      PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr,
-+          "%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
-+      fprintf(stderr,
-+          "%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
-+      fprintf(stderr,
-+          "%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
-+      fprintf(stderr,
-+          "%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
-+#endif        /* DEBUG_SLOT_SELECTION */
++      return (0);
++      }
 +
-+      if (pSlotList != NULL)
-+              OPENSSL_free(pSlotList);
 +
-+      if (any_slot_found != NULL)
-+              *any_slot_found = 1;
-+      return (1);
++/* Required function by the engine random interface. It does nothing here */
++static void pk11_rand_cleanup(void)
++      {
++      return;
 +      }
 +
-+#endif        /* OPENSSL_NO_HW_PK11 */
-+#endif        /* OPENSSL_NO_HW */
-Index: openssl/crypto/engine/hw_pk11.c
-diff -u /dev/null openssl/crypto/engine/hw_pk11.c:1.25
---- /dev/null  Mon Oct  5 11:08:14 2009
-+++ openssl/crypto/engine/hw_pk11.c    Fri Sep  4 10:43:22 2009
-@@ -0,0 +1,3919 @@
-+/*
-+ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
-+ * Use is subject to license terms.
-+ */
-+
-+/* 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).
-+ *
-+ */
++/* ARGSUSED */
++static void pk11_rand_add(const void *buf, int num, double add)
++      {
++      PK11_SESSION *sp;
 +
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <string.h>
-+#include <sys/types.h>
++      if ((sp = pk11_get_session(OP_RAND)) == NULL)
++              return;
 +
-+#include <openssl/e_os2.h>
-+#include <openssl/crypto.h>
-+#include <cryptlib.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>
-+
-+#ifdef OPENSSL_SYS_WIN32
-+typedef int pid_t;
-+#define getpid() GetCurrentProcessId()
-+#define NOPTHREADS
-+#ifndef NULL_PTR
-+#define NULL_PTR NULL
-+#endif
-+#define CK_DEFINE_FUNCTION(returnType, name) \
-+      returnType __declspec(dllexport) name
-+#define CK_DECLARE_FUNCTION(returnType, name) \
-+      returnType __declspec(dllimport) name
-+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
-+      returnType __declspec(dllimport) (* name)
-+#else
-+#include <signal.h>
-+#include <unistd.h>
-+#include <dlfcn.h>
-+#endif
++      /*
++       * 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);
 +
-+#ifndef NOPTHREADS
-+#include <pthread.h>
-+#endif
++      return;
++      }
 +
-+#ifndef OPENSSL_NO_HW
-+#ifndef OPENSSL_NO_HW_PK11
++static void pk11_rand_seed(const void *buf, int num)
++      {
++      pk11_rand_add(buf, num, 0);
++      }
 +
-+/* 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)
-+#undef        SOLARIS_HW_SLOT_SELECTION
-+#endif
++static int pk11_rand_bytes(unsigned char *buf, int num)
++      {
++      CK_RV rv;
++      PK11_SESSION *sp;
 +
-+/*
-+ * 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
++      if ((sp = pk11_get_session(OP_RAND)) == NULL)
++              return (0);
 +
-+#ifdef OPENSSL_SYS_WIN32
-+#pragma pack(push, cryptoki, 1)
-+#include "cryptoki.h"
-+#include "pkcs11.h"
-+#pragma pack(pop, cryptoki)
-+#else
-+#include "cryptoki.h"
-+#include "pkcs11.h"
-+#endif
-+#include "hw_pk11_err.c"
++      rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
++              pk11_return_session(sp, OP_RAND);
++              return (0);
++              }
 +
-+#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 */
++      pk11_return_session(sp, OP_RAND);
++      return (1);
++      }
 +
-+#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 */
++/* Required function by the engine random interface. It does nothing here */
++static int pk11_rand_status(void)
++      {
++      return (1);
++      }
 +
-+/* PKCS#11 session caches and their locks for all operation types */
-+static PK11_CACHE session_cache[OP_MAX];
++/* Free all BIGNUM structures from PK11_SESSION. */
++static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
++      {
++      switch (optype)
++              {
++#ifndef       OPENSSL_NO_RSA
++              case OP_RSA:
++                      if (sp->opdata_rsa_n_num != NULL)
++                              {
++                              BN_free(sp->opdata_rsa_n_num);
++                              sp->opdata_rsa_n_num = NULL;
++                              }
++                      if (sp->opdata_rsa_e_num != NULL)
++                              {
++                              BN_free(sp->opdata_rsa_e_num);
++                              sp->opdata_rsa_e_num = NULL;
++                              }
++                      if (sp->opdata_rsa_d_num != NULL)
++                              {
++                              BN_free(sp->opdata_rsa_d_num);
++                              sp->opdata_rsa_d_num = NULL;
++                              }
++                      break;
++#endif
++#ifndef       OPENSSL_NO_DSA
++              case OP_DSA:
++                      if (sp->opdata_dsa_pub_num != NULL)
++                              {
++                              BN_free(sp->opdata_dsa_pub_num);
++                              sp->opdata_dsa_pub_num = NULL;
++                              }
++                      if (sp->opdata_dsa_priv_num != NULL)
++                              {
++                              BN_free(sp->opdata_dsa_priv_num);
++                              sp->opdata_dsa_priv_num = NULL;
++                              }
++                      break;
++#endif
++#ifndef       OPENSSL_NO_DH
++              case OP_DH:
++                      if (sp->opdata_dh_priv_num != NULL)
++                              {
++                              BN_free(sp->opdata_dh_priv_num);
++                              sp->opdata_dh_priv_num = NULL;
++                              }
++                      break;
++#endif
++              default:
++                      break;
++              }
++      }
 +
 +/*
-+ * 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.
++ * Get new PK11_SESSION structure ready for use. Every process must have
++ * its own freelist of PK11_SESSION structures so handle fork() here
++ * by destroying the old and creating new freelist.
++ * The returned PK11_SESSION structure is disconnected from the freelist.
 + */
++PK11_SESSION *
++pk11_get_session(PK11_OPTYPE optype)
++      {
++      PK11_SESSION *sp = NULL, *sp1, *freelist;
 +#ifndef NOPTHREADS
-+pthread_mutex_t *find_lock[OP_MAX] = { NULL };
++      pthread_mutex_t *freelist_lock = NULL;
 +#endif
++      CK_RV rv;
 +
-+/*
-+ * 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;
++      switch (optype)
++              {
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++              case OP_RAND:
++              case OP_DIGEST:
++              case OP_CIPHER:
++#ifndef NOPTHREADS
++                      freelist_lock = session_cache[optype].lock;
++#endif
++                      break;
++              default:
++                      PK11err(PK11_F_GET_SESSION,
++                              PK11_R_INVALID_OPERATION_TYPE);
++                      return (NULL);
++              }
++#ifndef NOPTHREADS
++      (void) pthread_mutex_lock(freelist_lock);
++#else
++      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      freelist = session_cache[optype].head;
++      sp = freelist;
 +
-+/* 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)(void));
-+static int pk11_destroy(ENGINE *e);
++      /*
++       * If the free list is empty, allocate new unitialized (filled
++       * with zeroes) PK11_SESSION structure otherwise return first
++       * structure from the freelist.
++       */
++      if (sp == NULL)
++              {
++              if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
++                      {
++                      PK11err(PK11_F_GET_SESSION,
++                              PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
++              (void) memset(sp, 0, sizeof (PK11_SESSION));
++              }
++      else
++              {
++              freelist = sp->next;
++              }
 +
-+/* 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 session,
-+      CK_OBJECT_HANDLE oh);
-+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);
++      if (sp->pid != 0 && sp->pid != getpid())
++              {
++              /*
++               * We are a new process and thus need to free any inherited
++               * PK11_SESSION objects.
++               */
++              while ((sp1 = freelist) != NULL)
++                      {
++                      freelist = sp1->next;
++                      /*
++                       * NOTE: we do not want to call pk11_free_all_sessions()
++                       * here because it would close underlying PKCS#11
++                       * sessions and destroy all objects.
++                       */
++                      pk11_free_nums(sp1, optype);
++                      OPENSSL_free(sp1);
++                      }
 +
-+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);
++              /* we have to free the active list as well. */
++              pk11_free_active_list(optype);
 +
-+static int pk11_init_all_locks(void);
-+static void pk11_free_all_locks(void);
++              /* Initialize the process */
++              rv = pFuncList->C_Initialize(NULL_PTR);
++              if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
++                      {
++                      PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
++                          rv);
++                      OPENSSL_free(sp);
++                      sp = NULL;
++                      goto err;
++                      }
 +
++              /*
++               * Choose slot here since the slot table is different on this
++               * process. If we are here then we must have found at least one
++               * usable slot before so we don't need to check any_slot_found.
++               * See pk11_library_init()'s usage of this function for more
++               * information.
++               */
 +#ifdef        SOLARIS_HW_SLOT_SELECTION
-+static int check_hw_mechanisms(void);
-+static int nid_in_table(int nid, int *nid_table);
++              if (check_hw_mechanisms() == 0)
++                      goto err;
 +#endif        /* SOLARIS_HW_SLOT_SELECTION */
++              if (pk11_choose_slots(NULL) == 0)
++                      goto err;
 +
-+/* 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
-+};
++              /* 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_GET_SESSION, PK11_R_OPENSESSION,
++                          rv);
++                      OPENSSL_free(sp);
++                      sp = NULL;
++                      goto err;
++                      }
 +
-+/* Index for the supported digests */
-+enum pk11_digest_id {
-+      PK11_MD5,
-+      PK11_SHA1,
-+      PK11_SHA224,
-+      PK11_SHA256,
-+      PK11_SHA384,
-+      PK11_SHA512,
-+      PK11_DIGEST_MAX
-+};
++              /* It is an inherited session and needs re-initialization. */
++              if (pk11_setup_session(sp, optype) == 0)
++                      {
++                      OPENSSL_free(sp);
++                      sp = NULL;
++                      }
++              }
++      if (sp->pid == 0)
++              {
++              /* It is a new session and needs initialization. */
++              if (pk11_setup_session(sp, optype) == 0)
++                      {
++                      OPENSSL_free(sp);
++                      sp = NULL;
++                      }
++              }
 +
-+#define       TRY_OBJ_DESTROY(sess_hdl, 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(sess_hdl, obj_hdl);        \
-+              }                                                       \
-+      if (uselock)                                                    \
-+              UNLOCK_OBJSTORE(alg_type);                              \
-+      }
++      /* set new head for the list of PK11_SESSION objects */
++      session_cache[optype].head = freelist;
 +
-+#define       TRY_OBJ_DELETE(sess_hdl, obj_hdl, retval, uselock, alg_type)    \
-+      {                                                               \
-+      if (uselock)                                                    \
-+              LOCK_OBJSTORE(alg_type);                                \
-+      (void) pk11_active_delete(obj_hdl, alg_type);                   \
-+      if (uselock)                                                    \
-+              UNLOCK_OBJSTORE(alg_type);                              \
++err:
++      if (sp != NULL)
++              sp->next = NULL;
++
++#ifndef NOPTHREADS
++      (void) pthread_mutex_unlock(freelist_lock);
++#else
++      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++
++      return (sp);
 +      }
 +
-+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_recover = 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
++void
++pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
 +      {
-+      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;
++#ifndef NOPTHREADS
++      pthread_mutex_t *freelist_lock;
++#endif
++      PK11_SESSION *freelist;
 +
-+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 */
-+      };
++      if (sp == NULL || sp->pid != getpid())
++              return;
 +
-+typedef struct PK11_DIGEST_st
-+      {
-+      enum pk11_digest_id     id;
-+      int                     nid;
-+      CK_MECHANISM_TYPE       mech_type;
-+      } PK11_DIGEST;
++      switch (optype)
++              {
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++              case OP_RAND:
++              case OP_DIGEST:
++              case OP_CIPHER:
++#ifndef NOPTHREADS
++                      freelist_lock = session_cache[optype].lock;
++#endif
++                      break;
++              default:
++                      PK11err(PK11_F_RETURN_SESSION,
++                              PK11_R_INVALID_OPERATION_TYPE);
++                      return;
++              }
 +
-+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, },
-+      };
++#ifndef NOPTHREADS
++      (void) pthread_mutex_lock(freelist_lock);
++#else
++      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      freelist = session_cache[optype].head;
++      sp->next = freelist;
++      session_cache[optype].head = sp;
++#ifndef NOPTHREADS
++      (void) pthread_mutex_unlock(freelist_lock);
++#else
++      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      }
 +
-+/*
-+ * 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;
 +
++/* Destroy all objects. This function is called when the engine is finished */
++static int pk11_free_all_sessions()
++      {
++      int ret = 1;
++      int type;
 +
-+/*
-+ * 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.
-+ */
++#ifndef OPENSSL_NO_RSA
++      (void) pk11_destroy_rsa_key_objects(NULL);
++#endif        /* OPENSSL_NO_RSA */
++#ifndef OPENSSL_NO_DSA
++      (void) pk11_destroy_dsa_key_objects(NULL);
++#endif        /* OPENSSL_NO_DSA */
++#ifndef OPENSSL_NO_DH
++      (void) pk11_destroy_dh_key_objects(NULL);
++#endif        /* OPENSSL_NO_DH */
++      (void) pk11_destroy_cipher_key_objects(NULL);
 +
-+/* 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
-+      };
++      /*
++       * We try to release as much as we can but any error means that we will
++       * return 0 on exit.
++       */
++      for (type = 0; type < OP_MAX; type++)
++              {
++              if (pk11_free_session_list(type) == 0)
++                      ret = 0;
++              }
 +
-+/* 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
-+      };
++      return (ret);
++      }
 +
 +/*
-+ * ECB modes don't use an Initial Vector so that's why set_asn1_parameters and
-+ * get_asn1_parameters fields are set to NULL.
++ * Destroy session structures from the linked list specified. Free as many
++ * sessions as possible but any failure in C_CloseSession() means that we
++ * return an error on return.
 + */
-+static const EVP_CIPHER pk11_des_ecb =
++static int pk11_free_session_list(PK11_OPTYPE optype)
 +      {
-+      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
-+      };
++      CK_RV rv;
++      PK11_SESSION *sp = NULL;
++      PK11_SESSION *freelist = NULL;
++      pid_t mypid = getpid();
++#ifndef NOPTHREADS
++      pthread_mutex_t *freelist_lock;
++#endif
++      int ret = 1;
 +
-+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
-+      };
++      switch (optype)
++              {
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++              case OP_RAND:
++              case OP_DIGEST:
++              case OP_CIPHER:
++#ifndef NOPTHREADS
++                      freelist_lock = session_cache[optype].lock;
++#endif
++                      break;
++              default:
++                      PK11err(PK11_F_FREE_ALL_SESSIONS,
++                              PK11_R_INVALID_OPERATION_TYPE);
++                      return (0);
++              }
 +
++#ifndef NOPTHREADS
++      (void) pthread_mutex_lock(freelist_lock);
++#else
++      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      freelist = session_cache[optype].head;
++      while ((sp = freelist) != NULL)
++              {
++              if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
++                      {
++                      rv = pFuncList->C_CloseSession(sp->session);
++                      if (rv != CKR_OK)
++                              {
++                              PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
++                                      PK11_R_CLOSESESSION, rv);
++                              ret = 0;
++                              }
++                      }
++              freelist = sp->next;
++              pk11_free_nums(sp, optype);
++              OPENSSL_free(sp);
++              }
 +
-+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
-+      };
++#ifndef NOPTHREADS
++      (void) pthread_mutex_unlock(freelist_lock);
++#else
++      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      return (ret);
++      }
 +
-+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 =
++static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
 +      {
-+      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
-+      };
++      CK_RV rv;
++      CK_SLOT_ID myslot;
 +
-+/*
-+ * 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
-+      };
++      switch (optype)
++              {
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++                      myslot = pubkey_SLOTID;
++                      break;
++              case OP_RAND:
++                      myslot = rand_SLOTID;
++                      break;
++              case OP_DIGEST:
++              case OP_CIPHER:
++                      myslot = SLOTID;
++                      break;
++              default:
++                      PK11err(PK11_F_SETUP_SESSION,
++                          PK11_R_INVALID_OPERATION_TYPE);
++                      return (0);
++              }
 +
-+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
-+      };
++      sp->session = CK_INVALID_HANDLE;
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
++#endif        /* DEBUG_SLOT_SELECTION */
++      rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
++              NULL_PTR, NULL_PTR, &sp->session);
++      if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
++              {
++              /*
++               * We are probably a child process so force the
++               * reinitialize of the session
++               */
++              pk11_library_initialized = FALSE;
++              if (!pk11_library_init(NULL))
++                      return (0);
++              rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
++                      NULL_PTR, NULL_PTR, &sp->session);
++              }
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
++              return (0);
++              }
 +
-+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
-+      };
++      sp->pid = getpid();
 +
-+#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
-+      };
++      switch (optype)
++              {
++#ifndef OPENSSL_NO_RSA
++              case OP_RSA:
++                      sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
++                      sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
++                      sp->opdata_rsa_pub = NULL;
++                      sp->opdata_rsa_n_num = NULL;
++                      sp->opdata_rsa_e_num = NULL;
++                      sp->opdata_rsa_priv = NULL;
++                      sp->opdata_rsa_d_num = NULL;
++                      break;
++#endif        /* OPENSSL_NO_RSA */
++#ifndef OPENSSL_NO_DSA
++              case OP_DSA:
++                      sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
++                      sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
++                      sp->opdata_dsa_pub = NULL;
++                      sp->opdata_dsa_pub_num = NULL;
++                      sp->opdata_dsa_priv = NULL;
++                      sp->opdata_dsa_priv_num = NULL;
++                      break;
++#endif        /* OPENSSL_NO_DSA */
++#ifndef OPENSSL_NO_DH
++              case OP_DH:
++                      sp->opdata_dh_key = CK_INVALID_HANDLE;
++                      sp->opdata_dh = NULL;
++                      sp->opdata_dh_priv_num = NULL;
++                      break;
++#endif        /* OPENSSL_NO_DH */
++              case OP_CIPHER:
++                      sp->opdata_cipher_key = CK_INVALID_HANDLE;
++                      sp->opdata_encrypt = -1;
++                      break;
++              default:
++                      break;
++              }
 +
-+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
-+      };
++      return (1);
++      }
 +
-+static EVP_CIPHER pk11_aes_256_ctr =
++#ifndef OPENSSL_NO_RSA
++/* Destroy RSA public key from single session. */
++int
++pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
 +      {
-+      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 */
++      int ret = 0;
 +
-+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
-+      };
++      if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
++              {
++              TRY_OBJ_DESTROY(sp->session, sp->opdata_rsa_pub_key,
++                  ret, uselock, OP_RSA);
++              sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
++              sp->opdata_rsa_pub = NULL;
++              if (sp->opdata_rsa_n_num != NULL)
++                      {
++                      BN_free(sp->opdata_rsa_n_num);
++                      sp->opdata_rsa_n_num = NULL;
++                      }
++              if (sp->opdata_rsa_e_num != NULL)
++                      {
++                      BN_free(sp->opdata_rsa_e_num);
++                      sp->opdata_rsa_e_num = 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
-+      };
++      return (ret);
++      }
 +
-+static const EVP_MD pk11_md5 =
++/* Destroy RSA private key from single session. */
++int
++pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
 +      {
-+      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),
-+      };
++      int ret = 0;
 +
-+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),
-+      };
++      if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
++              {
++              if ((sp->opdata_rsa_priv->flags & RSA_FLAG_EXT_PKEY) != 0)
++                      {
++                      TRY_OBJ_DELETE(sp->session,
++                                     sp->opdata_rsa_priv_key,
++                                     ret, uselock, OP_RSA);
++                      }
++              else
++                      {
++                      TRY_OBJ_DESTROY(sp->session,
++                                      sp->opdata_rsa_priv_key,
++                                      ret, uselock, OP_RSA);
++                      }
++              sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
++              sp->opdata_rsa_priv = NULL;
++              if (sp->opdata_rsa_d_num != NULL)
++                      {
++                      BN_free(sp->opdata_rsa_d_num);
++                      sp->opdata_rsa_d_num = NULL;
++                      }
++              }
 +
-+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),
-+      };
++      return (ret);
++      }
 +
 +/*
-+ * Initialization function. Sets up various PKCS#11 library components.
-+ * The definitions for control commands specific to this engine
++ * Destroy RSA key object wrapper. If session is NULL, try to destroy all
++ * objects in the free list.
 + */
-+#define PK11_CMD_SO_PATH              ENGINE_CMD_BASE
-+#define PK11_CMD_PIN                  (ENGINE_CMD_BASE+1)
-+#define PK11_CMD_SLOT                 (ENGINE_CMD_BASE+2)
-+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
-+              },
-+              {
-+              PK11_CMD_PIN,
-+              "PIN",
-+              "Specifies the pin code",
-+              ENGINE_CMD_FLAG_STRING
-+              },
-+              {
-+              PK11_CMD_SLOT,
-+              "SLOT",
-+              "Specifies the slot (default is auto select)",
-+              ENGINE_CMD_FLAG_NUMERIC,
-+              },
-+              {0, NULL, NULL, 0}
-+      };
-+
-+
-+static RAND_METHOD pk11_random =
++int
++pk11_destroy_rsa_key_objects(PK11_SESSION *session)
 +      {
-+      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";
++      int ret = 1;
++      PK11_SESSION *sp = NULL;
++      PK11_SESSION *local_free_session;
++      CK_BBOOL uselock = TRUE;
 +
-+/*
-+ * These is the static string constant for the DSO file name and the function
-+ * symbol names to bind to.
-+ */
-+static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
++      if (session != NULL)
++              local_free_session = session;
++      else
++              {
++#ifndef NOPTHREADS
++              (void) pthread_mutex_lock(session_cache[OP_RSA].lock);
++#else
++              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++              local_free_session = session_cache[OP_RSA].head;
++              uselock = FALSE;
++              }
 +
-+static CK_BBOOL true = TRUE;
-+static CK_BBOOL false = FALSE;
-+static CK_SLOT_ID pubkey_SLOTID = 0;
-+static CK_SLOT_ID rand_SLOTID = 0;
-+static CK_SLOT_ID SLOTID = 0;
-+char *pk11_pin = NULL;
-+static CK_BBOOL pk11_library_initialized = FALSE;
-+static CK_BBOOL pk11_atfork_initialized = FALSE;
-+static int pk11_pid = 0;
++      /*
++       * go through the list of sessions and delete key objects
++       */
++      while ((sp = local_free_session) != NULL)
++              {
++              local_free_session = sp->next;
 +
-+static DSO *pk11_dso = NULL;
++              /*
++               * Do not terminate list traversal if one of the
++               * destroy operations fails.
++               */
++              if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
++                      {
++                      ret = 0;
++                      continue;
++                      }
++              if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
++                      {
++                      ret = 0;
++                      continue;
++                      }
++              }
 +
-+/* allocate and initialize all locks used by the engine itself */
-+static int pk11_init_all_locks(void)
-+      {
 +#ifndef NOPTHREADS
-+      int type;
++      if (session == NULL)
++              (void) pthread_mutex_unlock(session_cache[OP_RSA].lock);
++#else
++      if (session == NULL)
++              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
 +
-+#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 */
++      return (ret);
++      }
++#endif        /* OPENSSL_NO_RSA */
 +
 +#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 */
++/* Destroy DSA public key from single session. */
++int
++pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
++      {
++      int ret = 0;
 +
-+      for (type = 0; type < OP_MAX; type++)
++      if (sp->opdata_dsa_pub_key != CK_INVALID_HANDLE)
 +              {
-+              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);
++              TRY_OBJ_DESTROY(sp->session, sp->opdata_dsa_pub_key,
++                  ret, uselock, OP_DSA);
++              sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
++              sp->opdata_dsa_pub = NULL;
++              if (sp->opdata_dsa_pub_num != NULL)
++                      {
++                      BN_free(sp->opdata_dsa_pub_num);
++                      sp->opdata_dsa_pub_num = NULL;
++                      }
 +              }
 +
-+      return (1);
-+
-+malloc_err:
-+      pk11_free_all_locks();
-+      PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
-+      return (0);
-+#else
-+      return (1);
-+#endif
++      return (ret);
 +      }
 +
-+static void pk11_free_all_locks(void)
++/* Destroy DSA private key from single session. */
++int
++pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
 +      {
-+#ifndef NOPTHREADS
-+      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 */
++      int ret = 0;
 +
-+      for (type = 0; type < OP_MAX; type++)
++      if (sp->opdata_dsa_priv_key != CK_INVALID_HANDLE)
 +              {
-+              if (session_cache[type].lock != NULL)
++              TRY_OBJ_DESTROY(sp->session, sp->opdata_dsa_priv_key,
++                  ret, uselock, OP_DSA);
++              sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
++              sp->opdata_dsa_priv = NULL;
++              if (sp->opdata_dsa_priv_num != NULL)
 +                      {
-+                      (void) pthread_mutex_destroy(session_cache[type].lock);
-+                      OPENSSL_free(session_cache[type].lock);
-+                      session_cache[type].lock = NULL;
++                      BN_free(sp->opdata_dsa_priv_num);
++                      sp->opdata_dsa_priv_num = NULL;
 +                      }
 +              }
-+#endif
++
++      return (ret);
 +      }
 +
 +/*
-+ * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
++ * Destroy DSA key object wrapper. If session is NULL, try to destroy all
++ * objects in the free list.
 + */
-+static int bind_pk11(ENGINE *e)
++int
++pk11_destroy_dsa_key_objects(PK11_SESSION *session)
 +      {
-+#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);
++      int ret = 1;
++      PK11_SESSION *sp = NULL;
++      PK11_SESSION *local_free_session;
++      CK_BBOOL uselock = TRUE;
 +
-+      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 (session != NULL)
++              local_free_session = session;
++      else
 +              {
-+              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 */
++#ifndef NOPTHREADS
++              (void) pthread_mutex_lock(session_cache[OP_DSA].lock);
++#else
++              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++              local_free_session = session_cache[OP_DSA].head;
++              uselock = FALSE;
 +              }
-+      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;
-+      if (pk11_have_recover != CK_TRUE)
-+              pk11_rsa->rsa_pub_dec = rsa->rsa_pub_dec;
-+#endif        /* OPENSSL_NO_RSA */
-+
-+      /* Ensure the pk11 error handling is set up */
-+      ERR_load_pk11_strings();
 +
-+      return (1);
-+      }
++      /*
++       * go through the list of sessions and delete key objects
++       */
++      while ((sp = local_free_session) != NULL)
++              {
++              local_free_session = sp->next;
 +
-+/* 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);
++              /*
++               * Do not terminate list traversal if one of the
++               * destroy operations fails.
++               */
++              if (pk11_destroy_dsa_object_pub(sp, uselock) == 0)
++                      {
++                      ret = 0;
++                      continue;
++                      }
++              if (pk11_destroy_dsa_object_priv(sp, uselock) == 0)
++                      {
++                      ret = 0;
++                      continue;
++                      }
++              }
 +
-+      if (!bind_pk11(e))
-+              return (0);
++#ifndef NOPTHREADS
++      if (session == NULL)
++              (void) pthread_mutex_unlock(session_cache[OP_DSA].lock);
++#else
++      if (session == NULL)
++              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
 +
-+      return (1);
++      return (ret);
 +      }
++#endif        /* OPENSSL_NO_DSA */
 +
-+IMPLEMENT_DYNAMIC_CHECK_FN()
-+IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
-+
-+#else
-+static ENGINE *engine_pk11(void)
++#ifndef OPENSSL_NO_DH
++/* Destroy DH key from single session. */
++int
++pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock)
 +      {
-+      ENGINE *ret = ENGINE_new();
-+
-+      if (!ret)
-+              return (NULL);
++      int ret = 0;
 +
-+      if (!bind_pk11(ret))
++      if (sp->opdata_dh_key != CK_INVALID_HANDLE)
 +              {
-+              ENGINE_free(ret);
-+              return (NULL);
++              TRY_OBJ_DESTROY(sp->session, sp->opdata_dh_key,
++                  ret, uselock, OP_DH);
++              sp->opdata_dh_key = CK_INVALID_HANDLE;
++              sp->opdata_dh = NULL;
++              if (sp->opdata_dh_priv_num != NULL)
++                      {
++                      BN_free(sp->opdata_dh_priv_num);
++                      sp->opdata_dh_priv_num = NULL;
++                      }
 +              }
 +
 +      return (ret);
 +      }
 +
-+void
-+ENGINE_load_pk11(void)
++/*
++ * Destroy DH key object wrapper.
++ *
++ * arg0: pointer to PKCS#11 engine session structure
++ *       if session is NULL, try to destroy all objects in the free list
++ */
++int
++pk11_destroy_dh_key_objects(PK11_SESSION *session)
 +      {
-+      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);
++      int ret = 1;
++      PK11_SESSION *sp = NULL;
++      PK11_SESSION *local_free_session;
++      CK_BBOOL uselock = TRUE;
 +
-+      if (pk11_dso == NULL)
++      if (session != NULL)
++              local_free_session = session;
++      else
 +              {
-+              PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
-+              return;
++#ifndef NOPTHREADS
++              (void) pthread_mutex_lock(session_cache[OP_DH].lock);
++#else
++              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++              local_free_session = session_cache[OP_DH].head;
++              uselock = FALSE;
 +              }
 +
-+      e_pk11 = engine_pk11();
-+      if (!e_pk11)
++      while ((sp = local_free_session) != NULL)
 +              {
-+              DSO_free(pk11_dso);
-+              pk11_dso = NULL;
-+              return;
-+              }
++              local_free_session = sp->next;
 +
-+      /*
-+       * 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;
++              /*
++               * Do not terminate list traversal if one of the
++               * destroy operations fails.
++               */
++              if (pk11_destroy_dh_object(sp, uselock) == 0)
++                      {
++                      ret = 0;
++                      continue;
++                      }
 +              }
 +
-+      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);
++#ifndef NOPTHREADS
++      if (session == NULL)
++              (void) pthread_mutex_unlock(session_cache[OP_DH].lock);
++#else
++      if (session == NULL)
++              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
 +
-+      return (def_PK11_LIBNAME);
++      return (ret);
 +      }
++#endif        /* OPENSSL_NO_DH */
 +
-+static void free_PK11_LIBNAME(void)
++static int pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh)
 +      {
-+      if (PK11_LIBNAME)
-+              OPENSSL_free((void*)PK11_LIBNAME);
++      CK_RV rv;
++      rv = pFuncList->C_DestroyObject(session, oh);
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
++                  rv);
++              return (0);
++              }
 +
-+      PK11_LIBNAME = NULL;
++      return (1);
 +      }
 +
-+static long set_PK11_LIBNAME(const char *name)
-+      {
-+      free_PK11_LIBNAME();
 +
-+      return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
-+      }
++/* Symmetric ciphers and digests support functions */
 +
-+/* acquire all engine specific mutexes before fork */
-+static void pk11_fork_prepare(void)
++static int
++cipher_nid_to_pk11(int nid)
 +      {
-+#ifndef NOPTHREADS
 +      int i;
 +
-+      if (!pk11_library_initialized)
-+              return;
-+
-+      LOCK_OBJSTORE(OP_RSA);
-+      LOCK_OBJSTORE(OP_DSA);
-+      LOCK_OBJSTORE(OP_DH);
-+      for (i = 0; i < OP_MAX; i++)
-+              {
-+              (void) pthread_mutex_lock(session_cache[i].lock);
-+              }
-+#endif
++      for (i = 0; i < PK11_CIPHER_MAX; i++)
++              if (ciphers[i].nid == nid)
++                      return (ciphers[i].id);
++      return (-1);
 +      }
 +
-+/* release all engine specific mutexes */
-+static void pk11_fork_parent(void)
++static int
++pk11_usable_ciphers(const int **nids)
 +      {
-+#ifndef NOPTHREADS
-+      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);
-+#endif
++      if (cipher_count > 0)
++              *nids = cipher_nids;
++      else
++              *nids = NULL;
++      return (cipher_count);
 +      }
 +
-+/*
-+ * same situation as in parent - we need to unlock all locks to make them
-+ * accessible to all threads.
-+ */
-+static void pk11_fork_child(void)
++static int
++pk11_usable_digests(const int **nids)
 +      {
-+#ifndef NOPTHREADS
-+      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);
-+#endif
++      if (digest_count > 0)
++              *nids = digest_nids;
++      else
++              *nids = NULL;
++      return (digest_count);
 +      }
 +
-+/* 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.
++ * Init context for encryption or decryption using a symmetric key.
 + */
-+/* ARGSUSED */
-+static int pk11_library_init(ENGINE *e)
++static int pk11_init_symmetric(EVP_CIPHER_CTX *ctx, PK11_CIPHER *pcipher,
++      PK11_SESSION *sp, CK_MECHANISM_PTR pmech)
 +      {
-+      CK_C_GetFunctionList p;
-+      CK_RV rv = CKR_OK;
-+      CK_INFO info;
-+      CK_ULONG ul_state_len;
-+      int any_slot_found;
-+      int i;
-+#ifndef OPENSSL_SYS_WIN32
-+      struct sigaction sigint_act, sigterm_act, sighup_act;
-+#endif
++      CK_RV rv;
++#ifdef        SOLARIS_AES_CTR
++      CK_AES_CTR_PARAMS ctr_params;
++#endif        /* SOLARIS_AES_CTR */
 +
 +      /*
-+       * 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.
++       * We expect pmech->mechanism to be already set and
++       * pParameter/ulParameterLen initialized to NULL/0 before
++       * pk11_init_symetric() is called.
 +       */
-+      if (pk11_library_initialized)
++      OPENSSL_assert(pmech->mechanism != 0);
++      OPENSSL_assert(pmech->pParameter == NULL);
++      OPENSSL_assert(pmech->ulParameterLen == 0);
++
++#ifdef        SOLARIS_AES_CTR
++      if (ctx->cipher->nid == NID_aes_128_ctr ||
++          ctx->cipher->nid == NID_aes_192_ctr ||
++          ctx->cipher->nid == NID_aes_256_ctr)
 +              {
-+              if (pk11_pid == getpid())
-+                      {
-+                      return (1);
-+                      }
-+              else
++              pmech->pParameter = (void *)(&ctr_params);
++              pmech->ulParameterLen = sizeof (ctr_params);
++              /*
++               * For now, we are limited to the fixed length of the counter,
++               * it covers the whole counter block. That's what RFC 4344
++               * needs. For more information on internal structure of the
++               * counter block, see RFC 3686. If needed in the future, we can
++               * add code so that the counter length can be set via
++               * ENGINE_ctrl() function.
++               */
++              ctr_params.ulCounterBits = AES_BLOCK_SIZE * 8;
++              OPENSSL_assert(pcipher->iv_len == AES_BLOCK_SIZE);
++              (void) memcpy(ctr_params.cb, ctx->iv, AES_BLOCK_SIZE);
++              }
++      else
++#endif        /* SOLARIS_AES_CTR */
++              {
++              if (pcipher->iv_len > 0)
 +                      {
-+                      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();
++                      pmech->pParameter = (void *)ctx->iv;
++                      pmech->ulParameterLen = pcipher->iv_len;
 +                      }
 +              }
 +
-+      if (pk11_dso == NULL)
++      /* if we get here, the encryption needs to be reinitialized */
++      if (ctx->encrypt)
++              rv = pFuncList->C_EncryptInit(sp->session, pmech,
++                      sp->opdata_cipher_key);
++      else
++              rv = pFuncList->C_DecryptInit(sp->session, pmech,
++                      sp->opdata_cipher_key);
++
++      if (rv != CKR_OK)
 +              {
-+              PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
-+              goto err;
++              PK11err_add_data(PK11_F_CIPHER_INIT, ctx->encrypt ?
++                  PK11_R_ENCRYPTINIT : PK11_R_DECRYPTINIT, rv);
++              pk11_return_session(sp, OP_CIPHER);
++              return (0);
 +              }
 +
-+#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 */
++      return (1);
++      }
 +
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
-+      if (check_hw_mechanisms() == 0)
-+              goto err;
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
++/* ARGSUSED */
++static int
++pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
++    const unsigned char *iv, int enc)
++      {
++      CK_MECHANISM mech;
++      int index;
++      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
++      PK11_SESSION *sp;
++      PK11_CIPHER *p_ciph_table_row;
 +
-+      /* 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;
-+              }
++      state->sp = NULL;
 +
-+      /* 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;
-+              }
++      index = cipher_nid_to_pk11(ctx->cipher->nid);
++      if (index < 0 || index >= PK11_CIPHER_MAX)
++              return (0);
 +
-+#ifndef OPENSSL_SYS_WIN32
-+      /* Not all PKCS#11 library are signal safe! */
++      p_ciph_table_row = &ciphers[index];
++      /*
++       * iv_len in the ctx->cipher structure is the maximum IV length for the
++       * current cipher and it must be less or equal to the IV length in our
++       * ciphers table. The key length must be in the allowed interval. From
++       * all cipher modes that the PKCS#11 engine supports only RC4 allows a
++       * key length to be in some range, all other NIDs have a precise key
++       * length. Every application can define its own EVP functions so this
++       * code serves as a sanity check.
++       *
++       * Note that the reason why the IV length in ctx->cipher might be
++       * greater than the actual length is that OpenSSL uses BLOCK_CIPHER_defs
++       * macro to define functions that return EVP structures for all DES
++       * modes. So, even ECB modes get 8 byte IV.
++       */
++      if (ctx->cipher->iv_len < p_ciph_table_row->iv_len ||
++          ctx->key_len < p_ciph_table_row->min_key_len ||
++          ctx->key_len > p_ciph_table_row->max_key_len) {
++              PK11err(PK11_F_CIPHER_INIT, PK11_R_KEY_OR_IV_LEN_PROBLEM);
++              return (0);
++      }
 +
-+      (void) memset(&sigint_act, 0, sizeof(sigint_act));
-+      (void) memset(&sigterm_act, 0, sizeof(sigterm_act));
-+      (void) memset(&sighup_act, 0, sizeof(sighup_act));
-+      (void) sigaction(SIGINT, NULL, &sigint_act);
-+      (void) sigaction(SIGTERM, NULL, &sigterm_act);
-+      (void) sigaction(SIGHUP, NULL, &sighup_act);
-+#endif
-+      rv = pFuncList->C_Initialize(NULL_PTR);
-+#ifndef OPENSSL_SYS_WIN32
-+      (void) sigaction(SIGINT, &sigint_act, NULL);
-+      (void) sigaction(SIGTERM, &sigterm_act, NULL);
-+      (void) sigaction(SIGHUP, &sighup_act, NULL);
-+#endif
-+      if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
-+              {
-+              PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
-+              goto err;
-+              }
++      if ((sp = pk11_get_session(OP_CIPHER)) == NULL)
++              return (0);
 +
-+      rv = pFuncList->C_GetInfo(&info);
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
-+              goto err;
-+              }
++      /* if applicable, the mechanism parameter is used for IV */
++      mech.mechanism = p_ciph_table_row->mech_type;
++      mech.pParameter = NULL;
++      mech.ulParameterLen = 0;
 +
-+      if (pk11_choose_slots(&any_slot_found) == 0)
-+              goto err;
++      /* The key object is destroyed here if it is not the current key. */
++      (void) check_new_cipher_key(sp, key, ctx->key_len);
 +
 +      /*
-+       * 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 the key is the same and the encryption is also the same, then
++       * just reuse it. However, we must not forget to reinitialize the
++       * context that was finalized in pk11_cipher_cleanup().
 +       */
-+      if (any_slot_found == 0)
-+              return (1);
-+
-+      if (global_session == CK_INVALID_HANDLE)
++      if (sp->opdata_cipher_key != CK_INVALID_HANDLE &&
++          sp->opdata_encrypt == ctx->encrypt)
 +              {
-+              /* 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;
-+                      }
-+              }
++              state->sp = sp;
++              if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
++                      return (0);
 +
-+      /*
-+       * Disable digest if C_GetOperationState is not supported since
-+       * this function is required by OpenSSL digest copy function
-+       */
-+      /* Keyper fails to return CKR_FUNCTION_NOT_SUPPORTED */
-+      if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
-+                      != CKR_OK) {
-+#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;
-+      }
++              return (1);
++              }
 +
-+      pk11_library_initialized = 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.
++       * Check if the key has been invalidated. If so, a new key object
++       * needs to be created.
 +       */
-+      for (i = 0; i < OP_MAX; i++)
-+              active_list[i] = NULL;
++      if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
++              {
++              sp->opdata_cipher_key = pk11_get_cipher_key(
++                      ctx, key, p_ciph_table_row->key_type, sp);
++              }
 +
-+#ifndef NOPTHREADS
-+      if (!pk11_atfork_initialized)
++      if (sp->opdata_encrypt != ctx->encrypt && sp->opdata_encrypt != -1)
 +              {
-+              if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
-+                  pk11_fork_child) != 0)
++              /*
++               * The previous encryption/decryption is different. Need to
++               * terminate the previous * active encryption/decryption here.
++               */
++              if (!pk11_cipher_final(sp))
 +                      {
-+                      PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
-+                      goto err;
++                      pk11_return_session(sp, OP_CIPHER);
++                      return (0);
 +                      }
-+              pk11_atfork_initialized = TRUE;
 +              }
-+#endif
 +
-+      return (1);
++      if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
++              {
++              pk11_return_session(sp, OP_CIPHER);
++              return (0);
++              }
 +
-+err:
-+      return (0);
-+      }
++      /* now initialize the context with a new key */
++      if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
++              return (0);
++
++      sp->opdata_encrypt = ctx->encrypt;
++      state->sp = sp;
 +
-+/* Destructor (complements the "ENGINE_pk11()" constructor) */
-+/* ARGSUSED */
-+static int pk11_destroy(ENGINE *e)
-+      {
-+      free_PK11_LIBNAME();
-+      ERR_unload_pk11_strings();
-+      if (pk11_pin) {
-+              memset(pk11_pin, 0, strlen(pk11_pin));
-+              OPENSSL_free((void*)pk11_pin);
-+      }
-+      pk11_pin = NULL;
 +      return (1);
 +      }
 +
 +/*
-+ * Termination function to clean up the session, the token, and the pk11
-+ * library.
++ * When reusing the same key in an encryption/decryption session for a
++ * decryption/encryption session, we need to close the active session
++ * and recreate a new one. Note that the key is in the global session so
++ * that it needs not be recreated.
++ *
++ * It is more appropriate to use C_En/DecryptFinish here. At the time of this
++ * development, these two functions in the PKCS#11 libraries used return
++ * unexpected errors when passing in 0 length output. It may be a good
++ * idea to try them again if performance is a problem here and fix
++ * C_En/DecryptFinial if there are bugs there causing the problem.
 + */
-+/* ARGSUSED */
-+static int pk11_finish(ENGINE *e)
++static int
++pk11_cipher_final(PK11_SESSION *sp)
 +      {
-+      int i;
-+
-+      if (pk11_pin) {
-+              memset(pk11_pin, 0, strlen(pk11_pin));
-+              OPENSSL_free((void*)pk11_pin);
-+      }
-+      pk11_pin = NULL;
++      CK_RV rv;
 +
-+      if (pk11_dso == NULL)
++      rv = pFuncList->C_CloseSession(sp->session);
++      if (rv != CKR_OK)
 +              {
-+              PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
-+              goto err;
++              PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_CLOSESESSION, rv);
++              return (0);
 +              }
 +
-+      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
-+
-+      if (!DSO_free(pk11_dso))
++      rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
++              NULL_PTR, NULL_PTR, &sp->session);
++      if (rv != CKR_OK)
 +              {
-+              PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
-+              goto err;
++              PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_OPENSESSION, rv);
++              return (0);
 +              }
-+      pk11_dso = NULL;
-+      pFuncList = NULL;
-+      pk11_library_initialized = 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)(void))
++/*
++ * An engine interface function. The calling function allocates sufficient
++ * memory for the output buffer "out" to hold the results.
++ */
++static int
++pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
++      const unsigned char *in, unsigned int inl)
 +      {
-+      int initialized = ((pk11_dso == NULL) ? 0 : 1);
++      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
++      PK11_SESSION *sp;
++      CK_RV rv;
++      unsigned long outl = inl;
 +
-+      switch (cmd)
-+              {
-+      case PK11_CMD_SO_PATH:
-+              if (p == NULL)
-+                      {
-+                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
-+                      return (0);
-+                      }
++      if (state == NULL || state->sp == NULL)
++              return (0);
 +
-+              if (initialized)
-+                      {
-+                      PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
-+                      return (0);
-+                      }
++      sp = (PK11_SESSION *) state->sp;
 +
-+              return (set_PK11_LIBNAME((const char *)p));
-+      case PK11_CMD_PIN:
-+              if (pk11_pin) {
-+                      memset(pk11_pin, 0, strlen(pk11_pin));
-+                      OPENSSL_free((void*)pk11_pin);
-+              }
-+              pk11_pin = NULL;
++      if (!inl)
++              return (1);
 +
-+              if (p == NULL)
++      /* RC4 is the only stream cipher we support */
++      if (ctx->cipher->nid != NID_rc4 && (inl % ctx->cipher->block_size) != 0)
++              return (0);
++
++      if (ctx->encrypt)
++              {
++              rv = pFuncList->C_EncryptUpdate(sp->session,
++                      (unsigned char *)in, inl, out, &outl);
++
++              if (rv != CKR_OK)
 +                      {
-+                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
++                      PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
++                          PK11_R_ENCRYPTUPDATE, rv);
 +                      return (0);
 +                      }
++              }
++      else
++              {
++              rv = pFuncList->C_DecryptUpdate(sp->session,
++                      (unsigned char *)in, inl, out, &outl);
 +
-+              pk11_pin = BUF_strdup(p);
-+              if (pk11_pin == NULL)
++              if (rv != CKR_OK)
 +                      {
-+                      PK11err(PK11_F_GET_SESSION, PK11_R_MALLOC_FAILURE);
++                      PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
++                          PK11_R_DECRYPTUPDATE, rv);
 +                      return (0);
 +                      }
-+              return (1);
-+      case PK11_CMD_SLOT:
-+              SLOTID = (CK_SLOT_ID)i;
-+#ifdef DEBUG_SLOT_SELECTION
-+              fprintf(stderr, "%s: slot set\n", PK11_DBG);
-+#endif
-+              return (1);
-+      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
++       * For DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
++       * the same size of input.
++       * The application has guaranteed to call the block ciphers with
++       * correctly aligned buffers.
 +       */
-+      pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
-+      pk11_return_session(sp, OP_RAND);
-+
-+      return;
-+      }
++      if (inl != outl)
++              return (0);
 +
-+static void pk11_rand_seed(const void *buf, int num)
-+      {
-+      pk11_rand_add(buf, num, 0);
++      return (1);
 +      }
 +
-+static int pk11_rand_bytes(unsigned char *buf, int num)
++/*
++ * Return the session to the pool. Calling C_EncryptFinal() and C_DecryptFinal()
++ * here is the right thing because in EVP_DecryptFinal_ex(), engine's
++ * do_cipher() is not even called, and in EVP_EncryptFinal_ex() it is called but
++ * the engine can't find out that it's the finalizing call. We wouldn't
++ * necessarily have to finalize the context here since reinitializing it with
++ * C_(Encrypt|Decrypt)Init() should be fine but for the sake of correctness,
++ * let's do it. Some implementations might leak memory if the previously used
++ * context is initialized without finalizing it first.
++ */
++static int
++pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
 +      {
 +      CK_RV rv;
-+      PK11_SESSION *sp;
-+
-+      if ((sp = pk11_get_session(OP_RAND)) == NULL)
-+              return (0);
++      CK_ULONG len = EVP_MAX_BLOCK_LENGTH;
++      CK_BYTE buf[EVP_MAX_BLOCK_LENGTH];
++      PK11_CIPHER_STATE *state = ctx->cipher_data;
 +
-+      rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
-+      if (rv != CKR_OK)
++      if (state != NULL && state->sp != NULL)
 +              {
-+              PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
-+              pk11_return_session(sp, OP_RAND);
-+              return (0);
++              /*
++               * We are not interested in the data here, we just need to get
++               * rid of the context.
++               */
++              if (ctx->encrypt)
++                      rv = pFuncList->C_EncryptFinal(
++                          state->sp->session, buf, &len);
++              else
++                      rv = pFuncList->C_DecryptFinal(
++                          state->sp->session, buf, &len);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_CIPHER_CLEANUP, ctx->encrypt ?
++                          PK11_R_ENCRYPTFINAL : PK11_R_DECRYPTFINAL, rv);
++                      pk11_return_session(state->sp, OP_CIPHER);
++                      return (0);
++                      }
++
++              pk11_return_session(state->sp, OP_CIPHER);
++              state->sp = NULL;
 +              }
 +
-+      pk11_return_session(sp, OP_RAND);
 +      return (1);
 +      }
 +
-+/* Required function by the engine random interface. It does nothing here */
-+static int pk11_rand_status(void)
++/*
++ * Registered by the ENGINE when used to find out how to deal with
++ * a particular NID in the ENGINE. This says what we'll do at the
++ * top level - note, that list is restricted by what we answer with
++ */
++/* ARGSUSED */
++static int
++pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
++      const int **nids, int nid)
 +      {
-+      return (1);
-+      }
++      if (!cipher)
++              return (pk11_usable_ciphers(nids));
 +
-+/* Free all BIGNUM structures from PK11_SESSION. */
-+static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
-+      {
-+      switch (optype)
++      switch (nid)
 +              {
-+#ifndef       OPENSSL_NO_RSA
-+              case OP_RSA:
-+                      if (sp->opdata_rsa_n_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_rsa_n_num);
-+                              sp->opdata_rsa_n_num = NULL;
-+                              }
-+                      if (sp->opdata_rsa_e_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_rsa_e_num);
-+                              sp->opdata_rsa_e_num = NULL;
-+                              }
-+                      if (sp->opdata_rsa_d_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_rsa_d_num);
-+                              sp->opdata_rsa_d_num = NULL;
-+                              }
-+                      break;
-+#endif
-+#ifndef       OPENSSL_NO_DSA
-+              case OP_DSA:
-+                      if (sp->opdata_dsa_pub_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_dsa_pub_num);
-+                              sp->opdata_dsa_pub_num = NULL;
-+                              }
-+                      if (sp->opdata_dsa_priv_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_dsa_priv_num);
-+                              sp->opdata_dsa_priv_num = NULL;
-+                              }
++              case NID_des_ede3_cbc:
++                      *cipher = &pk11_3des_cbc;
 +                      break;
-+#endif
-+#ifndef       OPENSSL_NO_DH
-+              case OP_DH:
-+                      if (sp->opdata_dh_priv_num != NULL)
-+                              {
-+                              BN_free(sp->opdata_dh_priv_num);
-+                              sp->opdata_dh_priv_num = NULL;
-+                              }
++              case NID_des_cbc:
++                      *cipher = &pk11_des_cbc;
 +                      break;
-+#endif
-+              default:
++              case NID_des_ede3_ecb:
++                      *cipher = &pk11_3des_ecb;
 +                      break;
-+              }
-+      }
-+
-+/*
-+ * Get new PK11_SESSION structure ready for use. Every process must have
-+ * its own freelist of PK11_SESSION structures so handle fork() here
-+ * by destroying the old and creating new freelist.
-+ * The returned PK11_SESSION structure is disconnected from the freelist.
-+ */
-+PK11_SESSION *
-+pk11_get_session(PK11_OPTYPE optype)
-+      {
-+      PK11_SESSION *sp = NULL, *sp1, *freelist;
-+#ifndef NOPTHREADS
-+      pthread_mutex_t *freelist_lock = NULL;
-+#endif
-+      CK_RV rv;
-+
-+      switch (optype)
-+              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+              case OP_RAND:
-+              case OP_DIGEST:
-+              case OP_CIPHER:
-+#ifndef NOPTHREADS
-+                      freelist_lock = session_cache[optype].lock;
-+#endif
++              case NID_des_ecb:
++                      *cipher = &pk11_des_ecb;
++                      break;
++              case NID_aes_128_cbc:
++                      *cipher = &pk11_aes_128_cbc;
++                      break;
++              case NID_aes_192_cbc:
++                      *cipher = &pk11_aes_192_cbc;
++                      break;
++              case NID_aes_256_cbc:
++                      *cipher = &pk11_aes_256_cbc;
++                      break;
++              case NID_aes_128_ecb:
++                      *cipher = &pk11_aes_128_ecb;
++                      break;
++              case NID_aes_192_ecb:
++                      *cipher = &pk11_aes_192_ecb;
++                      break;
++              case NID_aes_256_ecb:
++                      *cipher = &pk11_aes_256_ecb;
++                      break;
++              case NID_bf_cbc:
++                      *cipher = &pk11_bf_cbc;
++                      break;
++              case NID_rc4:
++                      *cipher = &pk11_rc4;
 +                      break;
 +              default:
-+                      PK11err(PK11_F_GET_SESSION,
-+                              PK11_R_INVALID_OPERATION_TYPE);
-+                      return (NULL);
++#ifdef        SOLARIS_AES_CTR
++                      /*
++                       * These can't be in separated cases because the NIDs
++                       * here are not constants.
++                       */
++                      if (nid == NID_aes_128_ctr)
++                              *cipher = &pk11_aes_128_ctr;
++                      else if (nid == NID_aes_192_ctr)
++                              *cipher = &pk11_aes_192_ctr;
++                      else if (nid == NID_aes_256_ctr)
++                              *cipher = &pk11_aes_256_ctr;
++                      else
++#endif        /* SOLARIS_AES_CTR */
++                      *cipher = NULL;
++                      break;
 +              }
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_lock(freelist_lock);
-+#else
-+      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      freelist = session_cache[optype].head;
-+      sp = freelist;
++      return (*cipher != NULL);
++      }
 +
-+      /*
-+       * If the free list is empty, allocate new unitialized (filled
-+       * with zeroes) PK11_SESSION structure otherwise return first
-+       * structure from the freelist.
-+       */
-+      if (sp == NULL)
-+              {
-+              if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
-+                      {
-+                      PK11err(PK11_F_GET_SESSION,
-+                              PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
-+              (void) memset(sp, 0, sizeof (PK11_SESSION));
-+              }
-+      else
-+              {
-+              freelist = sp->next;
-+              }
++/* ARGSUSED */
++static int
++pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
++      const int **nids, int nid)
++      {
++      if (!digest)
++              return (pk11_usable_digests(nids));
 +
-+      if (sp->pid != 0 && sp->pid != getpid())
++      switch (nid)
 +              {
-+              /*
-+               * We are a new process and thus need to free any inherited
-+               * PK11_SESSION objects.
-+               */
-+              while ((sp1 = freelist) != NULL)
-+                      {
-+                      freelist = sp1->next;
-+                      /*
-+                       * NOTE: we do not want to call pk11_free_all_sessions()
-+                       * here because it would close underlying PKCS#11
-+                       * sessions and destroy all objects.
-+                       */
-+                      pk11_free_nums(sp1, optype);
-+                      OPENSSL_free(sp1);
-+                      }
++              case NID_md5:
++                      *digest = &pk11_md5;
++                      break;
++              case NID_sha1:
++                      *digest = &pk11_sha1;
++                      break;
++              case NID_sha224:
++                      *digest = &pk11_sha224;
++                      break;
++              case NID_sha256:
++                      *digest = &pk11_sha256;
++                      break;
++              case NID_sha384:
++                      *digest = &pk11_sha384;
++                      break;
++              case NID_sha512:
++                      *digest = &pk11_sha512;
++                      break;
++              default:
++                      *digest = NULL;
++                      break;
++              }
++      return (*digest != NULL);
++      }
 +
-+              /* we have to free the active list as well. */
-+              pk11_free_active_list(optype);
 +
-+              /* Initialize the process */
-+              rv = pFuncList->C_Initialize(NULL_PTR);
-+              if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
-+                      {
-+                      PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
-+                          rv);
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      goto err;
-+                      }
++/* Create a secret key object in a PKCS#11 session */
++static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
++      const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp)
++      {
++      CK_RV rv;
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      CK_OBJECT_CLASS obj_key = CKO_SECRET_KEY;
++      CK_ULONG ul_key_attr_count = 6;
 +
-+              /*
-+               * Choose slot here since the slot table is different on this
-+               * process. If we are here then we must have found at least one
-+               * usable slot before so we don't need to check any_slot_found.
-+               * See pk11_library_init()'s usage of this function for more
-+               * information.
-+               */
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
-+              if (check_hw_mechanisms() == 0)
-+                      goto err;
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
-+              if (pk11_choose_slots(NULL) == 0)
-+                      goto err;
++      CK_ATTRIBUTE  a_key_template[] =
++              {
++              {CKA_CLASS, (void*) NULL, sizeof (CK_OBJECT_CLASS)},
++              {CKA_KEY_TYPE, (void*) NULL, sizeof (CK_KEY_TYPE)},
++              {CKA_TOKEN, &false, sizeof (false)},
++              {CKA_ENCRYPT, &true, sizeof (true)},
++              {CKA_DECRYPT, &true, sizeof (true)},
++              {CKA_VALUE, (void*) NULL, 0},
++              };
 +
-+              /* 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_GET_SESSION, PK11_R_OPENSESSION,
-+                          rv);
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      goto err;
-+                      }
++      /*
++       * Create secret key object in global_session. All other sessions
++       * can use the key handles. Here is why:
++       * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
++       * It may then call DecryptInit and DecryptUpdate using the same key.
++       * To use the same key object, we need to call EncryptFinal with
++       * a 0 length message. Currently, this does not work for 3DES
++       * mechanism. To get around this problem, we close the session and
++       * then create a new session to use the same key object. When a session
++       * is closed, all the object handles will be invalid. Thus, create key
++       * objects in a global session, an individual session may be closed to
++       * terminate the active operation.
++       */
++      CK_SESSION_HANDLE session = global_session;
++      a_key_template[0].pValue = &obj_key;
++      a_key_template[1].pValue = &key_type;
++      a_key_template[5].pValue = (void *) key;
++      a_key_template[5].ulValueLen = (unsigned long) ctx->key_len;
 +
-+              /* It is an inherited session and needs re-initialization. */
-+              if (pk11_setup_session(sp, optype) == 0)
-+                      {
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      }
-+              }
-+      if (sp->pid == 0)
++      rv = pFuncList->C_CreateObject(session,
++              a_key_template, ul_key_attr_count, &h_key);
++      if (rv != CKR_OK)
 +              {
-+              /* It is a new session and needs initialization. */
-+              if (pk11_setup_session(sp, optype) == 0)
-+                      {
-+                      OPENSSL_free(sp);
-+                      sp = NULL;
-+                      }
++              PK11err_add_data(PK11_F_GET_CIPHER_KEY, PK11_R_CREATEOBJECT,
++                  rv);
++              goto err;
 +              }
 +
-+      /* set new head for the list of PK11_SESSION objects */
-+      session_cache[optype].head = freelist;
-+
++      /*
++       * Save the key information used in this session.
++       * The max can be saved is PK11_KEY_LEN_MAX.
++       */
++      sp->opdata_key_len = ctx->key_len > PK11_KEY_LEN_MAX ?
++              PK11_KEY_LEN_MAX : ctx->key_len;
++      (void) memcpy(sp->opdata_key, key, sp->opdata_key_len);
 +err:
-+      if (sp != NULL)
-+              sp->next = NULL;
-+
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_unlock(freelist_lock);
-+#else
-+      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
 +
-+      return (sp);
++      return (h_key);
 +      }
 +
++static int
++md_nid_to_pk11(int nid)
++      {
++      int i;
 +
-+void
-+pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
++      for (i = 0; i < PK11_DIGEST_MAX; i++)
++              if (digests[i].nid == nid)
++                      return (digests[i].id);
++      return (-1);
++      }
++
++static int
++pk11_digest_init(EVP_MD_CTX *ctx)
 +      {
-+#ifndef NOPTHREADS
-+      pthread_mutex_t *freelist_lock;
-+#endif
-+      PK11_SESSION *freelist;
++      CK_RV rv;
++      CK_MECHANISM mech;
++      int index;
++      PK11_SESSION *sp;
++      PK11_DIGEST *pdp;
++      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
 +
-+      if (sp == NULL || sp->pid != getpid())
-+              return;
++      state->sp = NULL;
 +
-+      switch (optype)
-+              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+              case OP_RAND:
-+              case OP_DIGEST:
-+              case OP_CIPHER:
-+#ifndef NOPTHREADS
-+                      freelist_lock = session_cache[optype].lock;
-+#endif
-+                      break;
-+              default:
-+                      PK11err(PK11_F_RETURN_SESSION,
-+                              PK11_R_INVALID_OPERATION_TYPE);
-+                      return;
-+              }
-+
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_lock(freelist_lock);
-+#else
-+      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      freelist = session_cache[optype].head;
-+      sp->next = freelist;
-+      session_cache[optype].head = sp;
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_unlock(freelist_lock);
-+#else
-+      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      }
++      index = md_nid_to_pk11(ctx->digest->type);
++      if (index < 0 || index >= PK11_DIGEST_MAX)
++              return (0);
 +
++      pdp = &digests[index];
++      if ((sp = pk11_get_session(OP_DIGEST)) == NULL)
++              return (0);
 +
-+/* Destroy all objects. This function is called when the engine is finished */
-+static int pk11_free_all_sessions()
-+      {
-+      int ret = 1;
-+      int type;
++      /* at present, no parameter is needed for supported digests */
++      mech.mechanism = pdp->mech_type;
++      mech.pParameter = NULL;
++      mech.ulParameterLen = 0;
 +
-+#ifndef OPENSSL_NO_RSA
-+      (void) pk11_destroy_rsa_key_objects(NULL);
-+#endif        /* OPENSSL_NO_RSA */
-+#ifndef OPENSSL_NO_DSA
-+      (void) pk11_destroy_dsa_key_objects(NULL);
-+#endif        /* OPENSSL_NO_DSA */
-+#ifndef OPENSSL_NO_DH
-+      (void) pk11_destroy_dh_key_objects(NULL);
-+#endif        /* OPENSSL_NO_DH */
-+      (void) pk11_destroy_cipher_key_objects(NULL);
++      rv = pFuncList->C_DigestInit(sp->session, &mech);
 +
-+      /*
-+       * We try to release as much as we can but any error means that we will
-+       * return 0 on exit.
-+       */
-+      for (type = 0; type < OP_MAX; type++)
++      if (rv != CKR_OK)
 +              {
-+              if (pk11_free_session_list(type) == 0)
-+                      ret = 0;
++              PK11err_add_data(PK11_F_DIGEST_INIT, PK11_R_DIGESTINIT, rv);
++              pk11_return_session(sp, OP_DIGEST);
++              return (0);
 +              }
 +
-+      return (ret);
++      state->sp = sp;
++
++      return (1);
 +      }
 +
-+/*
-+ * Destroy session structures from the linked list specified. Free as many
-+ * sessions as possible but any failure in C_CloseSession() means that we
-+ * return an error on return.
-+ */
-+static int pk11_free_session_list(PK11_OPTYPE optype)
++static int
++pk11_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count)
 +      {
 +      CK_RV rv;
-+      PK11_SESSION *sp = NULL;
-+      PK11_SESSION *freelist = NULL;
-+      pid_t mypid = getpid();
-+#ifndef NOPTHREADS
-+      pthread_mutex_t *freelist_lock;
-+#endif
-+      int ret = 1;
++      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
 +
-+      switch (optype)
-+              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+              case OP_RAND:
-+              case OP_DIGEST:
-+              case OP_CIPHER:
-+#ifndef NOPTHREADS
-+                      freelist_lock = session_cache[optype].lock;
-+#endif
-+                      break;
-+              default:
-+                      PK11err(PK11_F_FREE_ALL_SESSIONS,
-+                              PK11_R_INVALID_OPERATION_TYPE);
-+                      return (0);
-+              }
++      /* 0 length message will cause a failure in C_DigestFinal */
++      if (count == 0)
++              return (1);
 +
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_lock(freelist_lock);
-+#else
-+      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      freelist = session_cache[optype].head;
-+      while ((sp = freelist) != NULL)
++      if (state == NULL || state->sp == NULL)
++              return (0);
++
++      rv = pFuncList->C_DigestUpdate(state->sp->session, (CK_BYTE *) data,
++              count);
++
++      if (rv != CKR_OK)
 +              {
-+              if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
-+                      {
-+                      rv = pFuncList->C_CloseSession(sp->session);
-+                      if (rv != CKR_OK)
-+                              {
-+                              PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
-+                                      PK11_R_CLOSESESSION, rv);
-+                              ret = 0;
-+                              }
-+                      }
-+              freelist = sp->next;
-+              pk11_free_nums(sp, optype);
-+              OPENSSL_free(sp);
++              PK11err_add_data(PK11_F_DIGEST_UPDATE, PK11_R_DIGESTUPDATE, rv);
++              pk11_return_session(state->sp, OP_DIGEST);
++              state->sp = NULL;
++              return (0);
 +              }
 +
-+#ifndef NOPTHREADS
-+      (void) pthread_mutex_unlock(freelist_lock);
-+#else
-+      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+      return (ret);
++      return (1);
 +      }
 +
-+
-+static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
++static int
++pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
 +      {
 +      CK_RV rv;
-+      CK_SLOT_ID myslot;
++      unsigned long len;
++      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
++      len = ctx->digest->md_size;
 +
-+      switch (optype)
-+              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+                      myslot = pubkey_SLOTID;
-+                      break;
-+              case OP_RAND:
-+                      myslot = rand_SLOTID;
-+                      break;
-+              case OP_DIGEST:
-+              case OP_CIPHER:
-+                      myslot = SLOTID;
-+                      break;
-+              default:
-+                      PK11err(PK11_F_SETUP_SESSION,
-+                          PK11_R_INVALID_OPERATION_TYPE);
-+                      return (0);
-+              }
++      if (state == NULL || state->sp == NULL)
++              return (0);
++
++      rv = pFuncList->C_DigestFinal(state->sp->session, md, &len);
 +
-+      sp->session = CK_INVALID_HANDLE;
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+      rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
-+              NULL_PTR, NULL_PTR, &sp->session);
-+      if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
-+              {
-+              /*
-+               * We are probably a child process so force the
-+               * reinitialize of the session
-+               */
-+              pk11_library_initialized = FALSE;
-+              if (!pk11_library_init(NULL))
-+                      return (0);
-+              rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
-+                      NULL_PTR, NULL_PTR, &sp->session);
-+              }
 +      if (rv != CKR_OK)
 +              {
-+              PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
++              PK11err_add_data(PK11_F_DIGEST_FINAL, PK11_R_DIGESTFINAL, rv);
++              pk11_return_session(state->sp, OP_DIGEST);
++              state->sp = NULL;
 +              return (0);
 +              }
 +
-+      sp->pid = getpid();
++      if (ctx->digest->md_size != len)
++              return (0);
 +
-+      switch (optype)
-+              {
-+#ifndef OPENSSL_NO_RSA
-+              case OP_RSA:
-+                      sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
-+                      sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
-+                      sp->opdata_rsa_pub = NULL;
-+                      sp->opdata_rsa_n_num = NULL;
-+                      sp->opdata_rsa_e_num = NULL;
-+                      sp->opdata_rsa_priv = NULL;
-+                      sp->opdata_rsa_d_num = NULL;
-+                      break;
-+#endif        /* OPENSSL_NO_RSA */
-+#ifndef OPENSSL_NO_DSA
-+              case OP_DSA:
-+                      sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
-+                      sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
-+                      sp->opdata_dsa_pub = NULL;
-+                      sp->opdata_dsa_pub_num = NULL;
-+                      sp->opdata_dsa_priv = NULL;
-+                      sp->opdata_dsa_priv_num = NULL;
-+                      break;
-+#endif        /* OPENSSL_NO_DSA */
-+#ifndef OPENSSL_NO_DH
-+              case OP_DH:
-+                      sp->opdata_dh_key = CK_INVALID_HANDLE;
-+                      sp->opdata_dh = NULL;
-+                      sp->opdata_dh_priv_num = NULL;
-+                      break;
-+#endif        /* OPENSSL_NO_DH */
-+              case OP_CIPHER:
-+                      sp->opdata_cipher_key = CK_INVALID_HANDLE;
-+                      sp->opdata_encrypt = -1;
-+                      break;
-+              default:
-+                      break;
-+              }
++      /*
++       * Final is called and digest is returned, so return the session
++       * to the pool
++       */
++      pk11_return_session(state->sp, OP_DIGEST);
++      state->sp = NULL;
 +
 +      return (1);
 +      }
 +
-+#ifndef OPENSSL_NO_RSA
-+/* Destroy RSA public key from single session. */
-+int
-+pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
++static int
++pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
 +      {
++      CK_RV rv;
 +      int ret = 0;
++      PK11_CIPHER_STATE *state, *state_to;
++      CK_BYTE_PTR pstate = NULL;
++      CK_ULONG ul_state_len;
 +
-+      if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
-+              {
-+              TRY_OBJ_DESTROY(sp->session, sp->opdata_rsa_pub_key,
-+                  ret, uselock, OP_RSA);
-+              sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
-+              sp->opdata_rsa_pub = NULL;
-+              if (sp->opdata_rsa_n_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_rsa_n_num);
-+                      sp->opdata_rsa_n_num = NULL;
-+                      }
-+              if (sp->opdata_rsa_e_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_rsa_e_num);
-+                      sp->opdata_rsa_e_num = NULL;
-+                      }
-+              }
++      /* The copy-from state */
++      state = (PK11_CIPHER_STATE *) from->md_data;
++      if (state == NULL || state->sp == NULL)
++              goto err;
 +
-+      return (ret);
-+      }
++      /* Initialize the copy-to state */
++      if (!pk11_digest_init(to))
++              goto err;
++      state_to = (PK11_CIPHER_STATE *) to->md_data;
 +
-+/* Destroy RSA private key from single session. */
-+int
-+pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
-+      {
-+      int ret = 0;
++      /* Get the size of the operation state of the copy-from session */
++      rv = pFuncList->C_GetOperationState(state->sp->session, NULL,
++              &ul_state_len);
 +
-+      if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
++      if (rv != CKR_OK)
 +              {
-+              if ((sp->opdata_rsa_priv->flags & RSA_FLAG_EXT_PKEY) != 0)
-+                      {
-+                      TRY_OBJ_DELETE(sp->session,
-+                                     sp->opdata_rsa_priv_key,
-+                                     ret, uselock, OP_RSA);
-+                      }
-+              else
-+                      {
-+                      TRY_OBJ_DESTROY(sp->session,
-+                                      sp->opdata_rsa_priv_key,
-+                                      ret, uselock, OP_RSA);
-+                      }
-+              sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
-+              sp->opdata_rsa_priv = NULL;
-+              if (sp->opdata_rsa_d_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_rsa_d_num);
-+                      sp->opdata_rsa_d_num = NULL;
-+                      }
++              PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
++                  rv);
++              goto err;
++              }
++      if (ul_state_len == 0)
++              {
++              goto err;
 +              }
 +
-+      return (ret);
-+      }
++      pstate = OPENSSL_malloc(ul_state_len);
++      if (pstate == NULL)
++              {
++              PK11err(PK11_F_DIGEST_COPY, PK11_R_MALLOC_FAILURE);
++              goto err;
++              }
 +
-+/*
-+ * Destroy RSA key object wrapper. If session is NULL, try to destroy all
-+ * objects in the free list.
-+ */
-+int
-+pk11_destroy_rsa_key_objects(PK11_SESSION *session)
-+      {
-+      int ret = 1;
-+      PK11_SESSION *sp = NULL;
-+      PK11_SESSION *local_free_session;
-+      CK_BBOOL uselock = TRUE;
++      /* Get the operation state of the copy-from session */
++      rv = pFuncList->C_GetOperationState(state->sp->session, pstate,
++              &ul_state_len);
 +
-+      if (session != NULL)
-+              local_free_session = session;
-+      else
++      if (rv != CKR_OK)
 +              {
-+#ifndef NOPTHREADS
-+              (void) pthread_mutex_lock(session_cache[OP_RSA].lock);
-+#else
-+              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+              local_free_session = session_cache[OP_RSA].head;
-+              uselock = FALSE;
++              PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
++                  rv);
++              goto err;
 +              }
 +
-+      /*
-+       * go through the list of sessions and delete key objects
-+       */
-+      while ((sp = local_free_session) != NULL)
-+              {
-+              local_free_session = sp->next;
++      /* Set the operation state of the copy-to session */
++      rv = pFuncList->C_SetOperationState(state_to->sp->session, pstate,
++              ul_state_len, 0, 0);
 +
-+              /*
-+               * Do not terminate list traversal if one of the
-+               * destroy operations fails.
-+               */
-+              if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
-+                      {
-+                      ret = 0;
-+                      continue;
-+                      }
-+              if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
-+                      {
-+                      ret = 0;
-+                      continue;
-+                      }
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_DIGEST_COPY,
++                  PK11_R_SET_OPERATION_STATE, rv);
++              goto err;
 +              }
 +
-+#ifndef NOPTHREADS
-+      if (session == NULL)
-+              (void) pthread_mutex_unlock(session_cache[OP_RSA].lock);
-+#else
-+      if (session == NULL)
-+              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
++      ret = 1;
++err:
++      if (pstate != NULL)
++              OPENSSL_free(pstate);
 +
 +      return (ret);
 +      }
-+#endif        /* OPENSSL_NO_RSA */
 +
-+#ifndef OPENSSL_NO_DSA
-+/* Destroy DSA public key from single session. */
-+int
-+pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
++/* Return any pending session state to the pool */
++static int
++pk11_digest_cleanup(EVP_MD_CTX *ctx)
 +      {
-+      int ret = 0;
++      PK11_CIPHER_STATE *state = ctx->md_data;
++      unsigned char buf[EVP_MAX_MD_SIZE];
 +
-+      if (sp->opdata_dsa_pub_key != CK_INVALID_HANDLE)
++      if (state != NULL && state->sp != NULL)
 +              {
-+              TRY_OBJ_DESTROY(sp->session, sp->opdata_dsa_pub_key,
-+                  ret, uselock, OP_DSA);
-+              sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
-+              sp->opdata_dsa_pub = NULL;
-+              if (sp->opdata_dsa_pub_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_dsa_pub_num);
-+                      sp->opdata_dsa_pub_num = NULL;
-+                      }
++              /*
++               * If state->sp is not NULL then pk11_digest_final() has not
++               * been called yet. We must call it now to free any memory
++               * that might have been allocated in the token when
++               * pk11_digest_init() was called. pk11_digest_final()
++               * will return the session to the cache.
++               */
++              if (!pk11_digest_final(ctx, buf))
++                      return (0);
 +              }
 +
-+      return (ret);
++      return (1);
 +      }
 +
-+/* Destroy DSA private key from single session. */
-+int
-+pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
++/*
++ * Check if the new key is the same as the key object in the session. If the key
++ * is the same, no need to create a new key object. Otherwise, the old key
++ * object needs to be destroyed and a new one will be created. Return 1 for
++ * cache hit, 0 for cache miss. Note that we must check the key length first
++ * otherwise we could end up reusing a different, longer key with the same
++ * prefix.
++ */
++static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
++      int key_len)
 +      {
-+      int ret = 0;
-+
-+      if (sp->opdata_dsa_priv_key != CK_INVALID_HANDLE)
++      if (sp->opdata_key_len != key_len ||
++          memcmp(sp->opdata_key, key, key_len) != 0)
 +              {
-+              TRY_OBJ_DESTROY(sp->session, sp->opdata_dsa_priv_key,
-+                  ret, uselock, OP_DSA);
-+              sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
-+              sp->opdata_dsa_priv = NULL;
-+              if (sp->opdata_dsa_priv_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_dsa_priv_num);
-+                      sp->opdata_dsa_priv_num = NULL;
-+                      }
++              (void) pk11_destroy_cipher_key_objects(sp);
++              return (0);
 +              }
-+
-+      return (ret);
++      return (1);
 +      }
 +
-+/*
-+ * Destroy DSA key object wrapper. If session is NULL, try to destroy all
-+ * objects in the free list.
-+ */
-+int
-+pk11_destroy_dsa_key_objects(PK11_SESSION *session)
++/* Destroy one or more secret key objects. */
++static int pk11_destroy_cipher_key_objects(PK11_SESSION *session)
 +      {
-+      int ret = 1;
++      int ret = 0;
 +      PK11_SESSION *sp = NULL;
 +      PK11_SESSION *local_free_session;
-+      CK_BBOOL uselock = TRUE;
 +
 +      if (session != NULL)
 +              local_free_session = session;
 +      else
 +              {
 +#ifndef NOPTHREADS
-+              (void) pthread_mutex_lock(session_cache[OP_DSA].lock);
++              (void) pthread_mutex_lock(session_cache[OP_CIPHER].lock);
 +#else
 +              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
 +#endif
-+              local_free_session = session_cache[OP_DSA].head;
-+              uselock = FALSE;
++              local_free_session = session_cache[OP_CIPHER].head;
 +              }
 +
-+      /*
-+       * go through the list of sessions and delete key objects
-+       */
 +      while ((sp = local_free_session) != NULL)
 +              {
 +              local_free_session = sp->next;
 +
-+              /*
-+               * Do not terminate list traversal if one of the
-+               * destroy operations fails.
-+               */
-+              if (pk11_destroy_dsa_object_pub(sp, uselock) == 0)
-+                      {
-+                      ret = 0;
-+                      continue;
-+                      }
-+              if (pk11_destroy_dsa_object_priv(sp, uselock) == 0)
++              if (sp->opdata_cipher_key != CK_INVALID_HANDLE)
 +                      {
-+                      ret = 0;
-+                      continue;
++                      /*
++                       * The secret key object is created in the
++                       * global_session. See pk11_get_cipher_key
++                       */
++                      if (pk11_destroy_object(global_session,
++                              sp->opdata_cipher_key) == 0)
++                              goto err;
++                      sp->opdata_cipher_key = CK_INVALID_HANDLE;
 +                      }
 +              }
++      ret = 1;
++err:
 +
 +#ifndef NOPTHREADS
 +      if (session == NULL)
-+              (void) pthread_mutex_unlock(session_cache[OP_DSA].lock);
++              (void) pthread_mutex_unlock(session_cache[OP_CIPHER].lock);
 +#else
 +      if (session == NULL)
 +              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
@@ -4478,6318 +3893,7125 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11.c:1.25
 +
 +      return (ret);
 +      }
-+#endif        /* OPENSSL_NO_DSA */
 +
-+#ifndef OPENSSL_NO_DH
-+/* Destroy DH key from single session. */
-+int
-+pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock)
-+      {
-+      int ret = 0;
-+
-+      if (sp->opdata_dh_key != CK_INVALID_HANDLE)
-+              {
-+              TRY_OBJ_DESTROY(sp->session, sp->opdata_dh_key,
-+                  ret, uselock, OP_DH);
-+              sp->opdata_dh_key = CK_INVALID_HANDLE;
-+              sp->opdata_dh = NULL;
-+              if (sp->opdata_dh_priv_num != NULL)
-+                      {
-+                      BN_free(sp->opdata_dh_priv_num);
-+                      sp->opdata_dh_priv_num = NULL;
-+                      }
-+              }
-+
-+      return (ret);
-+      }
 +
 +/*
-+ * Destroy DH key object wrapper.
++ * Public key mechanisms optionally supported
 + *
-+ * arg0: pointer to PKCS#11 engine session structure
-+ *       if session is NULL, try to destroy all objects in the free list
++ * CKM_RSA_X_509
++ * CKM_RSA_PKCS
++ * CKM_DSA
++ *
++ * The first slot that supports at least one of those mechanisms is chosen as a
++ * public key slot.
++ *
++ * Symmetric ciphers optionally supported
++ *
++ * CKM_DES3_CBC
++ * CKM_DES_CBC
++ * CKM_AES_CBC
++ * CKM_DES3_ECB
++ * CKM_DES_ECB
++ * CKM_AES_ECB
++ * CKM_AES_CTR
++ * CKM_RC4
++ * CKM_BLOWFISH_CBC
++ *
++ * Digests optionally supported
++ *
++ * CKM_MD5
++ * CKM_SHA_1
++ * CKM_SHA224
++ * CKM_SHA256
++ * CKM_SHA384
++ * CKM_SHA512
++ *
++ * The output of this function is a set of global variables indicating which
++ * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
++ * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
++ * variables carry information about which slot was chosen for (a) public key
++ * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
 + */
-+int
-+pk11_destroy_dh_key_objects(PK11_SESSION *session)
++static int
++pk11_choose_slots(int *any_slot_found)
 +      {
-+      int ret = 1;
-+      PK11_SESSION *sp = NULL;
-+      PK11_SESSION *local_free_session;
-+      CK_BBOOL uselock = TRUE;
++      CK_SLOT_ID_PTR pSlotList = NULL_PTR;
++      CK_ULONG ulSlotCount = 0;
++      CK_MECHANISM_INFO mech_info;
++      CK_TOKEN_INFO token_info;
++      unsigned int i;
++      CK_RV rv;
++      CK_SLOT_ID best_slot_sofar = 0;
++      CK_BBOOL found_candidate_slot = CK_FALSE;
++      int slot_n_cipher = 0;
++      int slot_n_digest = 0;
++      CK_SLOT_ID current_slot = 0;
++      int current_slot_n_cipher = 0;
++      int current_slot_n_digest = 0;
 +
-+      if (session != NULL)
-+              local_free_session = session;
-+      else
++      int local_cipher_nids[PK11_CIPHER_MAX];
++      int local_digest_nids[PK11_DIGEST_MAX];
++
++      /* let's initialize the output parameter */
++      if (any_slot_found != NULL)
++              *any_slot_found = 0;
++
++      /* Get slot list for memory allocation */
++      rv = pFuncList->C_GetSlotList(0, NULL_PTR, &ulSlotCount);
++
++      if (rv != CKR_OK)
 +              {
-+#ifndef NOPTHREADS
-+              (void) pthread_mutex_lock(session_cache[OP_DH].lock);
-+#else
-+              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+              local_free_session = session_cache[OP_DH].head;
-+              uselock = FALSE;
++              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
++              return (0);
 +              }
 +
-+      while ((sp = local_free_session) != NULL)
++      /* it's not an error if we didn't find any providers */
++      if (ulSlotCount == 0)
 +              {
-+              local_free_session = sp->next;
-+
-+              /*
-+               * Do not terminate list traversal if one of the
-+               * destroy operations fails.
-+               */
-+              if (pk11_destroy_dh_object(sp, uselock) == 0)
-+                      {
-+                      ret = 0;
-+                      continue;
-+                      }
++#ifdef        DEBUG_SLOT_SELECTION
++              fprintf(stderr, "%s: no crypto providers found\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
++              return (1);
 +              }
 +
-+#ifndef NOPTHREADS
-+      if (session == NULL)
-+              (void) pthread_mutex_unlock(session_cache[OP_DH].lock);
-+#else
-+      if (session == NULL)
-+              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
++      pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
 +
-+      return (ret);
-+      }
-+#endif        /* OPENSSL_NO_DH */
++      if (pSlotList == NULL)
++              {
++              PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
++              return (0);
++              }
 +
-+static int pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh)
-+      {
-+      CK_RV rv;
-+      rv = pFuncList->C_DestroyObject(session, oh);
++      /* Get the slot list for processing */
++      rv = pFuncList->C_GetSlotList(0, pSlotList, &ulSlotCount);
 +      if (rv != CKR_OK)
 +              {
-+              PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
-+                  rv);
++              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
++              OPENSSL_free(pSlotList);
 +              return (0);
 +              }
 +
-+      return (1);
-+      }
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
++      fprintf(stderr, "%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
 +
++      fprintf(stderr, "%s: == checking rand slots ==\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
++      for (i = 0; i < ulSlotCount; i++)
++              {
++              current_slot = pSlotList[i];
 +
-+/* Symmetric ciphers and digests support functions */
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
++#endif        /* DEBUG_SLOT_SELECTION */
++              /* Check if slot has random support. */
++              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
++              if (rv != CKR_OK)
++                      continue;
 +
-+static int
-+cipher_nid_to_pk11(int nid)
-+      {
-+      int i;
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      for (i = 0; i < PK11_CIPHER_MAX; i++)
-+              if (ciphers[i].nid == nid)
-+                      return (ciphers[i].id);
-+      return (-1);
-+      }
++              if (token_info.flags & CKF_RNG)
++                      {
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: this token has CKF_RNG flag\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
++                      pk11_have_random = CK_TRUE;
++                      rand_SLOTID = current_slot;
++                      break;
++                      }
++              }
 +
-+static int
-+pk11_usable_ciphers(const int **nids)
-+      {
-+      if (cipher_count > 0)
-+              *nids = cipher_nids;
-+      else
-+              *nids = NULL;
-+      return (cipher_count);
-+      }
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: == checking pubkey slots ==\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+static int
-+pk11_usable_digests(const int **nids)
-+      {
-+      if (digest_count > 0)
-+              *nids = digest_nids;
-+      else
-+              *nids = NULL;
-+      return (digest_count);
-+      }
++      pubkey_SLOTID = pSlotList[0];
++      for (i = 0; i < ulSlotCount; i++)
++              {
++              CK_BBOOL slot_has_rsa = CK_FALSE;
++              CK_BBOOL slot_has_recover = CK_FALSE;
++              CK_BBOOL slot_has_dsa = CK_FALSE;
++              CK_BBOOL slot_has_dh = CK_FALSE;
++              current_slot = pSlotList[i];
 +
-+/*
-+ * Init context for encryption or decryption using a symmetric key.
-+ */
-+static int pk11_init_symmetric(EVP_CIPHER_CTX *ctx, PK11_CIPHER *pcipher,
-+      PK11_SESSION *sp, CK_MECHANISM_PTR pmech)
-+      {
-+      CK_RV rv;
-+#ifdef        SOLARIS_AES_CTR
-+      CK_AES_CTR_PARAMS ctr_params;
-+#endif        /* SOLARIS_AES_CTR */
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
++#endif        /* DEBUG_SLOT_SELECTION */
++              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
++              if (rv != CKR_OK)
++                      continue;
 +
-+      /*
-+       * We expect pmech->mechanism to be already set and
-+       * pParameter/ulParameterLen initialized to NULL/0 before
-+       * pk11_init_symetric() is called.
-+       */
-+      OPENSSL_assert(pmech->mechanism != 0);
-+      OPENSSL_assert(pmech->pParameter == NULL);
-+      OPENSSL_assert(pmech->ulParameterLen == 0);
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+#ifdef        SOLARIS_AES_CTR
-+      if (ctx->cipher->nid == NID_aes_128_ctr ||
-+          ctx->cipher->nid == NID_aes_192_ctr ||
-+          ctx->cipher->nid == NID_aes_256_ctr)
-+              {
-+              pmech->pParameter = (void *)(&ctr_params);
-+              pmech->ulParameterLen = sizeof (ctr_params);
++#ifndef OPENSSL_NO_RSA
 +              /*
-+               * For now, we are limited to the fixed length of the counter,
-+               * it covers the whole counter block. That's what RFC 4344
-+               * needs. For more information on internal structure of the
-+               * counter block, see RFC 3686. If needed in the future, we can
-+               * add code so that the counter length can be set via
-+               * ENGINE_ctrl() function.
++               * Check if this slot is capable of signing and
++               * verifying with CKM_RSA_PKCS.
 +               */
-+              ctr_params.ulCounterBits = AES_BLOCK_SIZE * 8;
-+              OPENSSL_assert(pcipher->iv_len == AES_BLOCK_SIZE);
-+              (void) memcpy(ctr_params.cb, ctx->iv, AES_BLOCK_SIZE);
-+              }
-+      else
-+#endif        /* SOLARIS_AES_CTR */
-+              {
-+              if (pcipher->iv_len > 0)
++              rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
++                      &mech_info);
++
++              if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
++                              (mech_info.flags & CKF_VERIFY)))
 +                      {
-+                      pmech->pParameter = (void *)ctx->iv;
-+                      pmech->ulParameterLen = pcipher->iv_len;
++                      /*
++                       * Check if this slot is capable of encryption,
++                       * decryption, sign, and verify with CKM_RSA_X_509.
++                       */
++                      rv = pFuncList->C_GetMechanismInfo(current_slot,
++                          CKM_RSA_X_509, &mech_info);
++
++                      if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
++                          (mech_info.flags & CKF_VERIFY) &&
++                          (mech_info.flags & CKF_ENCRYPT) &&
++                          (mech_info.flags & CKF_DECRYPT)))
++                              {
++                              slot_has_rsa = CK_TRUE;
++                              if (mech_info.flags & CKF_VERIFY_RECOVER)
++                                      {
++                                      slot_has_recover = CK_TRUE;
++                                      }
++                              }
 +                      }
-+              }
++#endif        /* OPENSSL_NO_RSA */
 +
-+      /* if we get here, the encryption needs to be reinitialized */
-+      if (ctx->encrypt)
-+              rv = pFuncList->C_EncryptInit(sp->session, pmech,
-+                      sp->opdata_cipher_key);
-+      else
-+              rv = pFuncList->C_DecryptInit(sp->session, pmech,
-+                      sp->opdata_cipher_key);
++#ifndef OPENSSL_NO_DSA
++              /*
++               * Check if this slot is capable of signing and
++               * verifying with CKM_DSA.
++               */
++              rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_DSA,
++                      &mech_info);
++              if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
++                  (mech_info.flags & CKF_VERIFY)))
++                      {
++                      slot_has_dsa = CK_TRUE;
++                      }
 +
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_CIPHER_INIT, ctx->encrypt ?
-+                  PK11_R_ENCRYPTINIT : PK11_R_DECRYPTINIT, rv);
-+              pk11_return_session(sp, OP_CIPHER);
-+              return (0);
-+              }
++#endif        /* OPENSSL_NO_DSA */
 +
-+      return (1);
-+      }
++#ifndef OPENSSL_NO_DH
++              /*
++               * Check if this slot is capable of DH key generataion and
++               * derivation.
++               */
++              rv = pFuncList->C_GetMechanismInfo(current_slot,
++                  CKM_DH_PKCS_KEY_PAIR_GEN, &mech_info);
 +
-+/* ARGSUSED */
-+static int
-+pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
-+    const unsigned char *iv, int enc)
-+      {
-+      CK_MECHANISM mech;
-+      int index;
-+      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
-+      PK11_SESSION *sp;
-+      PK11_CIPHER *p_ciph_table_row;
++              if (rv == CKR_OK && (mech_info.flags & CKF_GENERATE_KEY_PAIR))
++                      {
++                      rv = pFuncList->C_GetMechanismInfo(current_slot,
++                              CKM_DH_PKCS_DERIVE, &mech_info);
++                      if (rv == CKR_OK && (mech_info.flags & CKF_DERIVE))
++                              {
++                              slot_has_dh = CK_TRUE;
++                              }
++                      }
++#endif        /* OPENSSL_NO_DH */
 +
-+      state->sp = NULL;
++              if (!found_candidate_slot &&
++                  (slot_has_rsa || slot_has_dsa || slot_has_dh))
++                      {
++#ifdef        DEBUG_SLOT_SELECTION
++                      fprintf(stderr,
++                          "%s: potential slot: %d\n", PK11_DBG, current_slot);
++#endif        /* DEBUG_SLOT_SELECTION */
++                      best_slot_sofar = current_slot;
++                      pk11_have_rsa = slot_has_rsa;
++                      pk11_have_recover = slot_has_recover;
++                      pk11_have_dsa = slot_has_dsa;
++                      pk11_have_dh = slot_has_dh;
++                      found_candidate_slot = CK_TRUE;
++#ifdef        DEBUG_SLOT_SELECTION
++                      fprintf(stderr,
++                          "%s: setting found_candidate_slot to CK_TRUE\n",
++                          PK11_DBG);
++                      fprintf(stderr,
++                          "%s: best so far slot: %d\n", PK11_DBG,
++                          best_slot_sofar);
++                      }
++              else
++                      {
++                      fprintf(stderr,
++                          "%s: no rsa/dsa/dh\n", PK11_DBG);
++                      }
++#else
++                      } /* if */
++#endif        /* DEBUG_SLOT_SELECTION */
++              } /* for */
 +
-+      index = cipher_nid_to_pk11(ctx->cipher->nid);
-+      if (index < 0 || index >= PK11_CIPHER_MAX)
-+              return (0);
++      if (found_candidate_slot)
++              {
++              pubkey_SLOTID = best_slot_sofar;
++              }
 +
-+      p_ciph_table_row = &ciphers[index];
-+      /*
-+       * iv_len in the ctx->cipher structure is the maximum IV length for the
-+       * current cipher and it must be less or equal to the IV length in our
-+       * ciphers table. The key length must be in the allowed interval. From
-+       * all cipher modes that the PKCS#11 engine supports only RC4 allows a
-+       * key length to be in some range, all other NIDs have a precise key
-+       * length. Every application can define its own EVP functions so this
-+       * code serves as a sanity check.
-+       *
-+       * Note that the reason why the IV length in ctx->cipher might be
-+       * greater than the actual length is that OpenSSL uses BLOCK_CIPHER_defs
-+       * macro to define functions that return EVP structures for all DES
-+       * modes. So, even ECB modes get 8 byte IV.
-+       */
-+      if (ctx->cipher->iv_len < p_ciph_table_row->iv_len ||
-+          ctx->key_len < p_ciph_table_row->min_key_len ||
-+          ctx->key_len > p_ciph_table_row->max_key_len) {
-+              PK11err(PK11_F_CIPHER_INIT, PK11_R_KEY_OR_IV_LEN_PROBLEM);
-+              return (0);
-+      }
++      found_candidate_slot = CK_FALSE;
++      best_slot_sofar = 0;
 +
-+      if ((sp = pk11_get_session(OP_CIPHER)) == NULL)
-+              return (0);
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: == checking cipher/digest ==\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      /* if applicable, the mechanism parameter is used for IV */
-+      mech.mechanism = p_ciph_table_row->mech_type;
-+      mech.pParameter = NULL;
-+      mech.ulParameterLen = 0;
++      SLOTID = pSlotList[0];
++      for (i = 0; i < ulSlotCount; i++)
++              {
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      /* The key object is destroyed here if it is not the current key. */
-+      (void) check_new_cipher_key(sp, key, ctx->key_len);
++              current_slot = pSlotList[i];
++              current_slot_n_cipher = 0;
++              current_slot_n_digest = 0;
++              (void) memset(local_cipher_nids, 0, sizeof (local_cipher_nids));
++              (void) memset(local_digest_nids, 0, sizeof (local_digest_nids));
 +
-+      /*
-+       * If the key is the same and the encryption is also the same, then
-+       * just reuse it. However, we must not forget to reinitialize the
-+       * context that was finalized in pk11_cipher_cleanup().
-+       */
-+      if (sp->opdata_cipher_key != CK_INVALID_HANDLE &&
-+          sp->opdata_encrypt == ctx->encrypt)
-+              {
-+              state->sp = sp;
-+              if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
-+                      return (0);
++              pk11_find_symmetric_ciphers(pFuncList, current_slot,
++                  &current_slot_n_cipher, local_cipher_nids);
 +
-+              return (1);
-+              }
++              pk11_find_digests(pFuncList, current_slot,
++                  &current_slot_n_digest, local_digest_nids);
 +
-+      /*
-+       * Check if the key has been invalidated. If so, a new key object
-+       * needs to be created.
-+       */
-+      if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
-+              {
-+              sp->opdata_cipher_key = pk11_get_cipher_key(
-+                      ctx, key, p_ciph_table_row->key_type, sp);
-+              }
++#ifdef        DEBUG_SLOT_SELECTION
++              fprintf(stderr, "%s: current_slot_n_cipher %d\n", PK11_DBG,
++                      current_slot_n_cipher);
++              fprintf(stderr, "%s: current_slot_n_digest %d\n", PK11_DBG,
++                      current_slot_n_digest);
++              fprintf(stderr, "%s: best so far cipher/digest slot: %d\n",
++                      PK11_DBG, best_slot_sofar);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      if (sp->opdata_encrypt != ctx->encrypt && sp->opdata_encrypt != -1)
-+              {
 +              /*
-+               * The previous encryption/decryption is different. Need to
-+               * terminate the previous * active encryption/decryption here.
++               * If the current slot supports more ciphers/digests than
++               * the previous best one we change the current best to this one,
++               * otherwise leave it where it is.
 +               */
-+              if (!pk11_cipher_final(sp))
++              if ((current_slot_n_cipher + current_slot_n_digest) >
++                  (slot_n_cipher + slot_n_digest))
 +                      {
-+                      pk11_return_session(sp, OP_CIPHER);
-+                      return (0);
++#ifdef        DEBUG_SLOT_SELECTION
++                      fprintf(stderr,
++                              "%s: changing best so far slot to %d\n",
++                              PK11_DBG, current_slot);
++#endif        /* DEBUG_SLOT_SELECTION */
++                      best_slot_sofar = SLOTID = current_slot;
++                      cipher_count = slot_n_cipher = current_slot_n_cipher;
++                      digest_count = slot_n_digest = current_slot_n_digest;
++                      (void) memcpy(cipher_nids, local_cipher_nids,
++                          sizeof (local_cipher_nids));
++                      (void) memcpy(digest_nids, local_digest_nids, 
++                          sizeof (local_digest_nids));
 +                      }
 +              }
 +
-+      if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
-+              {
-+              pk11_return_session(sp, OP_CIPHER);
-+              return (0);
-+              }
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr,
++          "%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
++      fprintf(stderr,
++          "%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
++      fprintf(stderr,
++          "%s: chosen cipher/digest slot: %d\n", PK11_DBG, SLOTID);
++      fprintf(stderr,
++          "%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
++      fprintf(stderr,
++          "%s: pk11_have_recover %d\n", PK11_DBG, pk11_have_recover);
++      fprintf(stderr,
++          "%s: pk11_have_dsa %d\n", PK11_DBG, pk11_have_dsa);
++      fprintf(stderr,
++          "%s: pk11_have_dh %d\n", PK11_DBG, pk11_have_dh);
++      fprintf(stderr,
++          "%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
++      fprintf(stderr,
++          "%s: cipher_count %d\n", PK11_DBG, cipher_count);
++      fprintf(stderr,
++          "%s: digest_count %d\n", PK11_DBG, digest_count);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      /* now initialize the context with a new key */
-+      if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
-+              return (0);
++      if (pSlotList != NULL)
++              OPENSSL_free(pSlotList);
 +
-+      sp->opdata_encrypt = ctx->encrypt;
-+      state->sp = sp;
++#ifdef        SOLARIS_HW_SLOT_SELECTION
++      OPENSSL_free(hw_cnids);
++      OPENSSL_free(hw_dnids);
++#endif        /* SOLARIS_HW_SLOT_SELECTION */
 +
++      if (any_slot_found != NULL)
++              *any_slot_found = 1;
 +      return (1);
 +      }
 +
-+/*
-+ * When reusing the same key in an encryption/decryption session for a
-+ * decryption/encryption session, we need to close the active session
-+ * and recreate a new one. Note that the key is in the global session so
-+ * that it needs not be recreated.
-+ *
-+ * It is more appropriate to use C_En/DecryptFinish here. At the time of this
-+ * development, these two functions in the PKCS#11 libraries used return
-+ * unexpected errors when passing in 0 length output. It may be a good
-+ * idea to try them again if performance is a problem here and fix
-+ * C_En/DecryptFinial if there are bugs there causing the problem.
-+ */
-+static int
-+pk11_cipher_final(PK11_SESSION *sp)
++static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR pflist,
++    int slot_id, CK_MECHANISM_TYPE mech, int *current_slot_n_cipher,
++    int *local_cipher_nids, int id)
 +      {
++      CK_MECHANISM_INFO mech_info;
 +      CK_RV rv;
 +
-+      rv = pFuncList->C_CloseSession(sp->session);
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: checking mech: %x", PK11_DBG, mech);
++#endif        /* DEBUG_SLOT_SELECTION */
++      rv = pflist->C_GetMechanismInfo(slot_id, mech, &mech_info);
++
 +      if (rv != CKR_OK)
 +              {
-+              PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_CLOSESESSION, rv);
-+              return (0);
++#ifdef        DEBUG_SLOT_SELECTION
++              fprintf(stderr, " not found\n");
++#endif        /* DEBUG_SLOT_SELECTION */
++              return;
 +              }
 +
-+      rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
-+              NULL_PTR, NULL_PTR, &sp->session);
-+      if (rv != CKR_OK)
++      if ((mech_info.flags & CKF_ENCRYPT) &&
++          (mech_info.flags & CKF_DECRYPT))
 +              {
-+              PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_OPENSESSION, rv);
-+              return (0);
++#ifdef        SOLARIS_HW_SLOT_SELECTION
++              if (nid_in_table(ciphers[id].nid, hw_cnids))
++#endif        /* SOLARIS_HW_SLOT_SELECTION */
++                      {
++#ifdef        DEBUG_SLOT_SELECTION
++              fprintf(stderr, " usable\n");
++#endif        /* DEBUG_SLOT_SELECTION */
++                      local_cipher_nids[(*current_slot_n_cipher)++] =
++                          ciphers[id].nid;
++                      }
++#ifdef        SOLARIS_HW_SLOT_SELECTION
++#ifdef        DEBUG_SLOT_SELECTION
++              else
++                      {
++              fprintf(stderr, " rejected, software implementation only\n");
++                      }
++#endif        /* DEBUG_SLOT_SELECTION */
++#endif        /* SOLARIS_HW_SLOT_SELECTION */
++              }
++#ifdef        DEBUG_SLOT_SELECTION
++      else
++              {
++              fprintf(stderr, " unusable\n");
 +              }
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      return (1);
++      return;
 +      }
 +
-+/*
-+ * An engine interface function. The calling function allocates sufficient
-+ * memory for the output buffer "out" to hold the results.
-+ */
-+static int
-+pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
-+      const unsigned char *in, unsigned int inl)
++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)
 +      {
-+      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
-+      PK11_SESSION *sp;
++      CK_MECHANISM_INFO mech_info;
 +      CK_RV rv;
-+      unsigned long outl = inl;
-+
-+      if (state == NULL || state->sp == NULL)
-+              return (0);
-+
-+      sp = (PK11_SESSION *) state->sp;
-+
-+      if (!inl)
-+              return (1);
 +
-+      /* RC4 is the only stream cipher we support */
-+      if (ctx->cipher->nid != NID_rc4 && (inl % ctx->cipher->block_size) != 0)
-+              return (0);
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: checking mech: %x", PK11_DBG, mech);
++#endif        /* DEBUG_SLOT_SELECTION */
++      rv = pflist->C_GetMechanismInfo(slot_id, mech, &mech_info);
 +
-+      if (ctx->encrypt)
++      if (rv != CKR_OK)
 +              {
-+              rv = pFuncList->C_EncryptUpdate(sp->session,
-+                      (unsigned char *)in, inl, out, &outl);
++#ifdef        DEBUG_SLOT_SELECTION
++              fprintf(stderr, " not found\n");
++#endif        /* DEBUG_SLOT_SELECTION */
++              return;
++              }
 +
-+              if (rv != CKR_OK)
++      if (mech_info.flags & CKF_DIGEST)
++              {
++#ifdef        SOLARIS_HW_SLOT_SELECTION
++              if (nid_in_table(digests[id].nid, hw_dnids))
++#endif        /* SOLARIS_HW_SLOT_SELECTION */
 +                      {
-+                      PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
-+                          PK11_R_ENCRYPTUPDATE, rv);
-+                      return (0);
++#ifdef        DEBUG_SLOT_SELECTION
++              fprintf(stderr, " usable\n");
++#endif        /* DEBUG_SLOT_SELECTION */
++                      local_digest_nids[(*current_slot_n_digest)++] =
++                          digests[id].nid;
++                      }
++#ifdef        SOLARIS_HW_SLOT_SELECTION
++#ifdef        DEBUG_SLOT_SELECTION
++              else
++                      {
++              fprintf(stderr, " rejected, software implementation only\n");
 +                      }
++#endif        /* DEBUG_SLOT_SELECTION */
++#endif        /* SOLARIS_HW_SLOT_SELECTION */
 +              }
++#ifdef        DEBUG_SLOT_SELECTION
 +      else
 +              {
-+              rv = pFuncList->C_DecryptUpdate(sp->session,
-+                      (unsigned char *)in, inl, out, &outl);
-+
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
-+                          PK11_R_DECRYPTUPDATE, rv);
-+                      return (0);
-+                      }
++              fprintf(stderr, " unusable\n");
 +              }
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      /*
-+       * For DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
-+       * the same size of input.
-+       * The application has guaranteed to call the block ciphers with
-+       * correctly aligned buffers.
-+       */
-+      if (inl != outl)
-+              return (0);
-+
-+      return (1);
++      return;
 +      }
 +
-+/*
-+ * Return the session to the pool. Calling C_EncryptFinal() and C_DecryptFinal()
-+ * here is the right thing because in EVP_DecryptFinal_ex(), engine's
-+ * do_cipher() is not even called, and in EVP_EncryptFinal_ex() it is called but
-+ * the engine can't find out that it's the finalizing call. We wouldn't
-+ * necessarily have to finalize the context here since reinitializing it with
-+ * C_(Encrypt|Decrypt)Init() should be fine but for the sake of correctness,
-+ * let's do it. Some implementations might leak memory if the previously used
-+ * context is initialized without finalizing it first.
-+ */
-+static int
-+pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
++#ifdef        SOLARIS_AES_CTR
++/* create a new NID when we have no OID for that mechanism */
++static int pk11_add_NID(char *sn, char *ln)
 +      {
-+      CK_RV rv;
-+      CK_ULONG len = EVP_MAX_BLOCK_LENGTH;
-+      CK_BYTE buf[EVP_MAX_BLOCK_LENGTH];
-+      PK11_CIPHER_STATE *state = ctx->cipher_data;
++      ASN1_OBJECT *o;
++      int nid;
 +
-+      if (state != NULL && state->sp != NULL)
++      if ((o = ASN1_OBJECT_create(OBJ_new_nid(1), (unsigned char *)"",
++          1, sn, ln)) == NULL)
 +              {
-+              /*
-+               * We are not interested in the data here, we just need to get
-+               * rid of the context.
-+               */
-+              if (ctx->encrypt)
-+                      rv = pFuncList->C_EncryptFinal(
-+                          state->sp->session, buf, &len);
-+              else
-+                      rv = pFuncList->C_DecryptFinal(
-+                          state->sp->session, buf, &len);
-+
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_CIPHER_CLEANUP, ctx->encrypt ?
-+                          PK11_R_ENCRYPTFINAL : PK11_R_DECRYPTFINAL, rv);
-+                      pk11_return_session(state->sp, OP_CIPHER);
-+                      return (0);
-+                      }
-+
-+              pk11_return_session(state->sp, OP_CIPHER);
-+              state->sp = NULL;
++              return (0);
 +              }
 +
-+      return (1);
++      /* will return NID_undef on error */
++      nid = OBJ_add_object(o);
++      ASN1_OBJECT_free(o);
++
++      return (nid);
 +      }
 +
 +/*
-+ * Registered by the ENGINE when used to find out how to deal with
-+ * a particular NID in the ENGINE. This says what we'll do at the
-+ * top level - note, that list is restricted by what we answer with
++ * Create new NIDs for AES counter mode. OpenSSL doesn't support them now so we
++ * have to help ourselves here.
 + */
-+/* ARGSUSED */
-+static int
-+pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
-+      const int **nids, int nid)
++static int pk11_add_aes_ctr_NIDs(void)
 +      {
-+      if (!cipher)
-+              return (pk11_usable_ciphers(nids));
++      /* are we already set? */
++      if (NID_aes_256_ctr != NID_undef)
++              return (1);
 +
-+      switch (nid)
++      /*
++       * There are no official names for AES counter modes yet so we just
++       * follow the format of those that exist.
++       */
++      if ((NID_aes_128_ctr = pk11_add_NID("AES-128-CTR", "aes-128-ctr")) ==
++          NID_undef)
++              goto err;
++      ciphers[PK11_AES_128_CTR].nid = pk11_aes_128_ctr.nid = NID_aes_128_ctr;
++      if ((NID_aes_192_ctr = pk11_add_NID("AES-192-CTR", "aes-192-ctr")) ==
++          NID_undef)
++              goto err;
++      ciphers[PK11_AES_192_CTR].nid = pk11_aes_192_ctr.nid = NID_aes_192_ctr;
++      if ((NID_aes_256_ctr = pk11_add_NID("AES-256-CTR", "aes-256-ctr")) ==
++          NID_undef)
++              goto err;
++      ciphers[PK11_AES_256_CTR].nid = pk11_aes_256_ctr.nid = NID_aes_256_ctr;
++      return (1);
++
++err:
++      PK11err(PK11_F_ADD_AES_CTR_NIDS, PK11_R_ADD_NID_FAILED);
++      return (0);
++      }
++#endif        /* SOLARIS_AES_CTR */
++
++/* Find what symmetric ciphers this slot supports. */
++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)
++      {
++      int i;
++
++      for (i = 0; i < PK11_CIPHER_MAX; ++i)
 +              {
-+              case NID_des_ede3_cbc:
-+                      *cipher = &pk11_3des_cbc;
-+                      break;
-+              case NID_des_cbc:
-+                      *cipher = &pk11_des_cbc;
-+                      break;
-+              case NID_des_ede3_ecb:
-+                      *cipher = &pk11_3des_ecb;
-+                      break;
-+              case NID_des_ecb:
-+                      *cipher = &pk11_des_ecb;
-+                      break;
-+              case NID_aes_128_cbc:
-+                      *cipher = &pk11_aes_128_cbc;
-+                      break;
-+              case NID_aes_192_cbc:
-+                      *cipher = &pk11_aes_192_cbc;
-+                      break;
-+              case NID_aes_256_cbc:
-+                      *cipher = &pk11_aes_256_cbc;
-+                      break;
-+              case NID_aes_128_ecb:
-+                      *cipher = &pk11_aes_128_ecb;
-+                      break;
-+              case NID_aes_192_ecb:
-+                      *cipher = &pk11_aes_192_ecb;
-+                      break;
-+              case NID_aes_256_ecb:
-+                      *cipher = &pk11_aes_256_ecb;
-+                      break;
-+              case NID_bf_cbc:
-+                      *cipher = &pk11_bf_cbc;
-+                      break;
-+              case NID_rc4:
-+                      *cipher = &pk11_rc4;
-+                      break;
-+              default:
-+#ifdef        SOLARIS_AES_CTR
-+                      /*
-+                       * These can't be in separated cases because the NIDs
-+                       * here are not constants.
-+                       */
-+                      if (nid == NID_aes_128_ctr)
-+                              *cipher = &pk11_aes_128_ctr;
-+                      else if (nid == NID_aes_192_ctr)
-+                              *cipher = &pk11_aes_192_ctr;
-+                      else if (nid == NID_aes_256_ctr)
-+                              *cipher = &pk11_aes_256_ctr;
-+                      else
-+#endif        /* SOLARIS_AES_CTR */
-+                      *cipher = NULL;
-+                      break;
++              pk11_get_symmetric_cipher(pflist, current_slot,
++                  ciphers[i].mech_type, current_slot_n_cipher,
++                  local_cipher_nids, ciphers[i].id);
 +              }
-+      return (*cipher != NULL);
 +      }
 +
-+/* ARGSUSED */
-+static int
-+pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
-+      const int **nids, int nid)
++/* Find what digest algorithms this slot supports. */
++static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
++    CK_SLOT_ID current_slot, int *current_slot_n_digest, int *local_digest_nids)
 +      {
-+      if (!digest)
-+              return (pk11_usable_digests(nids));
++      int i;
 +
-+      switch (nid)
++      for (i = 0; i < PK11_DIGEST_MAX; ++i)
 +              {
-+              case NID_md5:
-+                      *digest = &pk11_md5;
-+                      break;
-+              case NID_sha1:
-+                      *digest = &pk11_sha1;
-+                      break;
-+              case NID_sha224:
-+                      *digest = &pk11_sha224;
-+                      break;
-+              case NID_sha256:
-+                      *digest = &pk11_sha256;
-+                      break;
-+              case NID_sha384:
-+                      *digest = &pk11_sha384;
-+                      break;
-+              case NID_sha512:
-+                      *digest = &pk11_sha512;
-+                      break;
-+              default:
-+                      *digest = NULL;
-+                      break;
++              pk11_get_digest(pflist, current_slot, digests[i].mech_type,
++                  current_slot_n_digest, local_digest_nids, digests[i].id);
 +              }
-+      return (*digest != NULL);
 +      }
 +
++#ifdef        SOLARIS_HW_SLOT_SELECTION
++/*
++ * It would be great if we could use pkcs11_kernel directly since this library
++ * offers hardware slots only. That's the easiest way to achieve the situation
++ * where we use the hardware accelerators when present and OpenSSL native code
++ * otherwise. That presumes the fact that OpenSSL native code is faster than the
++ * code in the soft token. It's a logical assumption - Crypto Framework has some
++ * inherent overhead so going there for the software implementation of a
++ * mechanism should be logically slower in contrast to the OpenSSL native code,
++ * presuming that both implementations are of similar speed. For example, the
++ * soft token for AES is roughly three times slower than OpenSSL for 64 byte
++ * blocks and still 20% slower for 8KB blocks. So, if we want to ship products
++ * that use the PKCS#11 engine by default, we must somehow avoid that regression
++ * on machines without hardware acceleration. That's why switching to the
++ * pkcs11_kernel library seems like a very good idea.
++ *
++ * The problem is that OpenSSL built with SunStudio is roughly 2x slower for
++ * asymmetric operations (RSA/DSA/DH) than the soft token built with the same
++ * compiler. That means that if we switched to pkcs11_kernel from the libpkcs11
++ * library, we would have had a performance regression on machines without
++ * hardware acceleration for asymmetric operations for all applications that use
++ * the PKCS#11 engine. There is one such application - Apache web server since
++ * it's shipped configured to use the PKCS#11 engine by default. Having said
++ * that, we can't switch to the pkcs11_kernel library now and have to come with
++ * a solution that, on non-accelerated machines, uses the OpenSSL native code
++ * for all symmetric ciphers and digests while it uses the soft token for
++ * asymmetric operations.
++ *
++ * This is the idea: dlopen() pkcs11_kernel directly and find out what
++ * mechanisms are there. We don't care about duplications (more slots can
++ * support the same mechanism), we just want to know what mechanisms can be
++ * possibly supported in hardware on that particular machine. As said before,
++ * pkcs11_kernel will show you hardware providers only.
++ *
++ * Then, we rely on the fact that since we use libpkcs11 library we will find
++ * the metaslot. When we go through the metaslot's mechanisms for symmetric
++ * ciphers and digests, we check that any found mechanism is in the table
++ * created using the pkcs11_kernel library. So, as a result we have two arrays
++ * of mechanisms that were advertised as supported in hardware which was the
++ * goal of that whole excercise. Thus, we can use libpkcs11 but avoid soft token
++ * code for symmetric ciphers and digests. See pk11_choose_slots() for more
++ * information.
++ *
++ * This is Solaris specific code, if SOLARIS_HW_SLOT_SELECTION is not defined
++ * the code won't be used.
++ */
++#if defined(__sparcv9) || defined(__x86_64) || defined(__amd64)
++static const char pkcs11_kernel[] = "/usr/lib/security/64/pkcs11_kernel.so.1";
++#else
++static const char pkcs11_kernel[] = "/usr/lib/security/pkcs11_kernel.so.1";
++#endif
 +
-+/* Create a secret key object in a PKCS#11 session */
-+static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
-+      const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp)
++/*
++ * Check hardware capabilities of the machines. The output are two lists,
++ * hw_cnids and hw_dnids, that contain hardware mechanisms found in all hardware
++ * providers together. They are not sorted and may contain duplicate mechanisms.
++ */
++static int check_hw_mechanisms(void)
 +      {
++      int i;
 +      CK_RV rv;
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
-+      CK_OBJECT_CLASS obj_key = CKO_SECRET_KEY;
-+      CK_ULONG ul_key_attr_count = 6;
++      void *handle;
++      CK_C_GetFunctionList p;
++      CK_TOKEN_INFO token_info;
++      CK_ULONG ulSlotCount = 0;
++      int n_cipher = 0, n_digest = 0;
++      CK_FUNCTION_LIST_PTR pflist = NULL;
++      CK_SLOT_ID_PTR pSlotList = NULL_PTR;
++      int *tmp_hw_cnids = NULL, *tmp_hw_dnids = NULL;
++      int hw_ctable_size, hw_dtable_size;
 +
-+      CK_ATTRIBUTE  a_key_template[] =
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: SOLARIS_HW_SLOT_SELECTION code running\n",
++          PK11_DBG);
++#endif
++      if ((handle = dlopen(pkcs11_kernel, RTLD_LAZY)) == NULL)
 +              {
-+              {CKA_CLASS, (void*) NULL, sizeof (CK_OBJECT_CLASS)},
-+              {CKA_KEY_TYPE, (void*) NULL, sizeof (CK_KEY_TYPE)},
-+              {CKA_TOKEN, &false, sizeof (false)},
-+              {CKA_ENCRYPT, &true, sizeof (true)},
-+              {CKA_DECRYPT, &true, sizeof (true)},
-+              {CKA_VALUE, (void*) NULL, 0},
-+              };
-+
-+      /*
-+       * Create secret key object in global_session. All other sessions
-+       * can use the key handles. Here is why:
-+       * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
-+       * It may then call DecryptInit and DecryptUpdate using the same key.
-+       * To use the same key object, we need to call EncryptFinal with
-+       * a 0 length message. Currently, this does not work for 3DES
-+       * mechanism. To get around this problem, we close the session and
-+       * then create a new session to use the same key object. When a session
-+       * is closed, all the object handles will be invalid. Thus, create key
-+       * objects in a global session, an individual session may be closed to
-+       * terminate the active operation.
-+       */
-+      CK_SESSION_HANDLE session = global_session;
-+      a_key_template[0].pValue = &obj_key;
-+      a_key_template[1].pValue = &key_type;
-+      a_key_template[5].pValue = (void *) key;
-+      a_key_template[5].ulValueLen = (unsigned long) ctx->key_len;
++              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
++              goto err;
++              }
 +
-+      rv = pFuncList->C_CreateObject(session,
-+              a_key_template, ul_key_attr_count, &h_key);
-+      if (rv != CKR_OK)
++      if ((p = (CK_C_GetFunctionList)dlsym(handle,
++          PK11_GET_FUNCTION_LIST)) == NULL)
 +              {
-+              PK11err_add_data(PK11_F_GET_CIPHER_KEY, PK11_R_CREATEOBJECT,
-+                  rv);
++              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
 +              goto err;
 +              }
 +
-+      /*
-+       * Save the key information used in this session.
-+       * The max can be saved is PK11_KEY_LEN_MAX.
-+       */
-+      sp->opdata_key_len = ctx->key_len > PK11_KEY_LEN_MAX ?
-+              PK11_KEY_LEN_MAX : ctx->key_len;
-+      (void) memcpy(sp->opdata_key, key, sp->opdata_key_len);
-+err:
-+
-+      return (h_key);
-+      }
-+
-+static int
-+md_nid_to_pk11(int nid)
-+      {
-+      int i;
++      /* get the full function list from the loaded library */
++      if (p(&pflist) != CKR_OK)
++              {
++              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
++              goto err;
++              }
 +
-+      for (i = 0; i < PK11_DIGEST_MAX; i++)
-+              if (digests[i].nid == nid)
-+                      return (digests[i].id);
-+      return (-1);
-+      }
++      rv = pflist->C_Initialize(NULL_PTR);
++      if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
++              {
++              PK11err_add_data(PK11_F_CHECK_HW_MECHANISMS,
++                  PK11_R_INITIALIZE, rv);
++              goto err;
++              }
 +
-+static int
-+pk11_digest_init(EVP_MD_CTX *ctx)
-+      {
-+      CK_RV rv;
-+      CK_MECHANISM mech;
-+      int index;
-+      PK11_SESSION *sp;
-+      PK11_DIGEST *pdp;
-+      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
++      if (pflist->C_GetSlotList(0, NULL_PTR, &ulSlotCount) != CKR_OK)
++              {
++              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
++              goto err;
++              }
 +
-+      state->sp = NULL;
-+
-+      index = md_nid_to_pk11(ctx->digest->type);
-+      if (index < 0 || index >= PK11_DIGEST_MAX)
-+              return (0);
-+
-+      pdp = &digests[index];
-+      if ((sp = pk11_get_session(OP_DIGEST)) == NULL)
-+              return (0);
-+
-+      /* at present, no parameter is needed for supported digests */
-+      mech.mechanism = pdp->mech_type;
-+      mech.pParameter = NULL;
-+      mech.ulParameterLen = 0;
-+
-+      rv = pFuncList->C_DigestInit(sp->session, &mech);
-+
-+      if (rv != CKR_OK)
++      /* no slots, set the hw mechanism tables as empty */
++      if (ulSlotCount == 0)
 +              {
-+              PK11err_add_data(PK11_F_DIGEST_INIT, PK11_R_DIGESTINIT, rv);
-+              pk11_return_session(sp, OP_DIGEST);
-+              return (0);
-+              }
-+
-+      state->sp = sp;
-+
-+      return (1);
-+      }
-+
-+static int
-+pk11_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count)
-+      {
-+      CK_RV rv;
-+      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
-+
-+      /* 0 length message will cause a failure in C_DigestFinal */
-+      if (count == 0)
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: no hardware mechanisms found\n", PK11_DBG);
++#endif
++              hw_cnids = OPENSSL_malloc(sizeof (int));
++              hw_dnids = OPENSSL_malloc(sizeof (int));
++              if (hw_cnids == NULL || hw_dnids == NULL)
++                      {
++                      PK11err(PK11_F_CHECK_HW_MECHANISMS,
++                          PK11_R_MALLOC_FAILURE);
++                      return (0);
++                      }
++              /* this means empty tables */
++              hw_cnids[0] = NID_undef;
++              hw_dnids[0] = NID_undef;
 +              return (1);
-+
-+      if (state == NULL || state->sp == NULL)
-+              return (0);
-+
-+      rv = pFuncList->C_DigestUpdate(state->sp->session, (CK_BYTE *) data,
-+              count);
-+
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DIGEST_UPDATE, PK11_R_DIGESTUPDATE, rv);
-+              pk11_return_session(state->sp, OP_DIGEST);
-+              state->sp = NULL;
-+              return (0);
-+              }
-+
-+      return (1);
-+      }
-+
-+static int
-+pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
-+      {
-+      CK_RV rv;
-+      unsigned long len;
-+      PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
-+      len = ctx->digest->md_size;
-+
-+      if (state == NULL || state->sp == NULL)
-+              return (0);
-+
-+      rv = pFuncList->C_DigestFinal(state->sp->session, md, &len);
-+
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DIGEST_FINAL, PK11_R_DIGESTFINAL, rv);
-+              pk11_return_session(state->sp, OP_DIGEST);
-+              state->sp = NULL;
-+              return (0);
 +              }
 +
-+      if (ctx->digest->md_size != len)
-+              return (0);
-+
-+      /*
-+       * Final is called and digest is returned, so return the session
-+       * to the pool
-+       */
-+      pk11_return_session(state->sp, OP_DIGEST);
-+      state->sp = NULL;
-+
-+      return (1);
-+      }
-+
-+static int
-+pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
-+      {
-+      CK_RV rv;
-+      int ret = 0;
-+      PK11_CIPHER_STATE *state, *state_to;
-+      CK_BYTE_PTR pstate = NULL;
-+      CK_ULONG ul_state_len;
-+
-+      /* The copy-from state */
-+      state = (PK11_CIPHER_STATE *) from->md_data;
-+      if (state == NULL || state->sp == NULL)
-+              goto err;
-+
-+      /* Initialize the copy-to state */
-+      if (!pk11_digest_init(to))
-+              goto err;
-+      state_to = (PK11_CIPHER_STATE *) to->md_data;
-+
-+      /* Get the size of the operation state of the copy-from session */
-+      rv = pFuncList->C_GetOperationState(state->sp->session, NULL,
-+              &ul_state_len);
-+
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
-+                  rv);
-+              goto err;
-+              }
-+      if (ul_state_len == 0)
++      pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
++      if (pSlotList == NULL)
 +              {
++              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
 +              goto err;
 +              }
 +
-+      pstate = OPENSSL_malloc(ul_state_len);
-+      if (pstate == NULL)
++      /* Get the slot list for processing */
++      if (pflist->C_GetSlotList(0, pSlotList, &ulSlotCount) != CKR_OK)
 +              {
-+              PK11err(PK11_F_DIGEST_COPY, PK11_R_MALLOC_FAILURE);
++              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
 +              goto err;
 +              }
 +
-+      /* Get the operation state of the copy-from session */
-+      rv = pFuncList->C_GetOperationState(state->sp->session, pstate,
-+              &ul_state_len);
-+
-+      if (rv != CKR_OK)
++      /*
++       * We don't care about duplicit mechanisms in multiple slots and also
++       * reserve one slot for the terminal NID_undef which we use to stop the
++       * search.
++       */
++      hw_ctable_size = ulSlotCount * PK11_CIPHER_MAX + 1;
++      hw_dtable_size = ulSlotCount * PK11_DIGEST_MAX + 1;
++      tmp_hw_cnids = OPENSSL_malloc(hw_ctable_size * sizeof (int));
++      tmp_hw_dnids = OPENSSL_malloc(hw_dtable_size * sizeof (int));
++      if (tmp_hw_cnids == NULL || tmp_hw_dnids == NULL)
 +              {
-+              PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
-+                  rv);
++              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
 +              goto err;
 +              }
 +
-+      /* Set the operation state of the copy-to session */
-+      rv = pFuncList->C_SetOperationState(state_to->sp->session, pstate,
-+              ul_state_len, 0, 0);
-+
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DIGEST_COPY,
-+                  PK11_R_SET_OPERATION_STATE, rv);
-+              goto err;
-+              }
++      /*
++       * Do not use memset since we should not rely on the fact that NID_undef
++       * is zero now.
++       */
++      for (i = 0; i < hw_ctable_size; ++i)
++              tmp_hw_cnids[i] = NID_undef;
++      for (i = 0; i < hw_dtable_size; ++i)
++              tmp_hw_dnids[i] = NID_undef;
 +
-+      ret = 1;
-+err:
-+      if (pstate != NULL)
-+              OPENSSL_free(pstate);
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: provider: %s\n", PK11_DBG, pkcs11_kernel);
++      fprintf(stderr, "%s: found %d hardware slots\n", PK11_DBG, ulSlotCount);
++      fprintf(stderr, "%s: now looking for mechs supported in hw\n",
++          PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      return (ret);
-+      }
++      for (i = 0; i < ulSlotCount; i++)
++              {
++              if (pflist->C_GetTokenInfo(pSlotList[i], &token_info) != CKR_OK)
++                      continue;
 +
-+/* Return any pending session state to the pool */
-+static int
-+pk11_digest_cleanup(EVP_MD_CTX *ctx)
-+      {
-+      PK11_CIPHER_STATE *state = ctx->md_data;
-+      unsigned char buf[EVP_MAX_MD_SIZE];
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      if (state != NULL && state->sp != NULL)
-+              {
 +              /*
-+               * If state->sp is not NULL then pk11_digest_final() has not
-+               * been called yet. We must call it now to free any memory
-+               * that might have been allocated in the token when
-+               * pk11_digest_init() was called. pk11_digest_final()
-+               * will return the session to the cache.
++               * We are filling the hw mech tables here. Global tables are
++               * still NULL so all mechanisms are put into tmp tables.
 +               */
-+              if (!pk11_digest_final(ctx, buf))
-+                      return (0);
++              pk11_find_symmetric_ciphers(pflist, pSlotList[i],
++                  &n_cipher, tmp_hw_cnids);
++              pk11_find_digests(pflist, pSlotList[i],
++                  &n_digest, tmp_hw_dnids);
 +              }
 +
++      /*
++       * Since we are part of a library (libcrypto.so), calling this function
++       * may have side-effects. Also, C_Finalize() is triggered by
++       * dlclose(3C).
++       */
++#if 0
++      pflist->C_Finalize(NULL);
++#endif
++      OPENSSL_free(pSlotList);
++      (void) dlclose(handle);
++      hw_cnids = tmp_hw_cnids;
++      hw_dnids = tmp_hw_dnids;
++
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: hw mechs check complete\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
 +      return (1);
++
++err:
++      if (pSlotList != NULL)
++              OPENSSL_free(pSlotList);
++      if (tmp_hw_cnids != NULL)
++              OPENSSL_free(tmp_hw_cnids);
++      if (tmp_hw_dnids != NULL)
++              OPENSSL_free(tmp_hw_dnids);
++
++      return (0);
 +      }
 +
 +/*
-+ * Check if the new key is the same as the key object in the session. If the key
-+ * is the same, no need to create a new key object. Otherwise, the old key
-+ * object needs to be destroyed and a new one will be created. Return 1 for
-+ * cache hit, 0 for cache miss. Note that we must check the key length first
-+ * otherwise we could end up reusing a different, longer key with the same
-+ * prefix.
++ * Check presence of a NID in the table of NIDs. The table may be NULL (i.e.,
++ * non-existent).
 + */
-+static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
-+      int key_len)
++static int nid_in_table(int nid, int *nid_table)
 +      {
-+      if (sp->opdata_key_len != key_len ||
-+          memcmp(sp->opdata_key, key, key_len) != 0)
-+              {
-+              (void) pk11_destroy_cipher_key_objects(sp);
-+              return (0);
-+              }
-+      return (1);
-+      }
-+
-+/* Destroy one or more secret key objects. */
-+static int pk11_destroy_cipher_key_objects(PK11_SESSION *session)
-+      {
-+      int ret = 0;
-+      PK11_SESSION *sp = NULL;
-+      PK11_SESSION *local_free_session;
++      int i = 0;
 +
-+      if (session != NULL)
-+              local_free_session = session;
-+      else
-+              {
-+#ifndef NOPTHREADS
-+              (void) pthread_mutex_lock(session_cache[OP_CIPHER].lock);
-+#else
-+              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
-+              local_free_session = session_cache[OP_CIPHER].head;
-+              }
++      /*
++       * a special case. NULL means that we are initializing a new
++       * table.
++       */
++      if (nid_table == NULL)
++              return (1);
 +
-+      while ((sp = local_free_session) != NULL)
++      /*
++       * the table is never full, there is always at least one
++       * NID_undef.
++       */
++      while (nid_table[i] != NID_undef)
 +              {
-+              local_free_session = sp->next;
-+
-+              if (sp->opdata_cipher_key != CK_INVALID_HANDLE)
++              if (nid_table[i++] == nid)
 +                      {
-+                      /*
-+                       * The secret key object is created in the
-+                       * global_session. See pk11_get_cipher_key
-+                       */
-+                      if (pk11_destroy_object(global_session,
-+                              sp->opdata_cipher_key) == 0)
-+                              goto err;
-+                      sp->opdata_cipher_key = CK_INVALID_HANDLE;
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, " (NID %d in hw table, idx %d)", nid, i);
++#endif        /* DEBUG_SLOT_SELECTION */
++                      return (1);
 +                      }
 +              }
-+      ret = 1;
-+err:
-+
-+#ifndef NOPTHREADS
-+      if (session == NULL)
-+              (void) pthread_mutex_unlock(session_cache[OP_CIPHER].lock);
-+#else
-+      if (session == NULL)
-+              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
-+#endif
 +
-+      return (ret);
++      return (0);
 +      }
++#endif        /* SOLARIS_HW_SLOT_SELECTION */
 +
++#endif        /* OPENSSL_NO_HW_PK11CA */
++#endif        /* OPENSSL_NO_HW_PK11 */
++#endif        /* OPENSSL_NO_HW */
+Index: openssl/crypto/engine/hw_pk11_err.c
+diff -u /dev/null openssl/crypto/engine/hw_pk11_err.c:1.4
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11_err.c        Wed Dec 17 16:14:26 2008
+@@ -0,0 +1,259 @@
++/*
++ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
++ * Use is subject to license terms.
++ */
 +
++/* crypto/engine/hw_pk11_err.c */
 +/*
-+ * Public key mechanisms optionally supported
++ * This product includes software developed by the OpenSSL Project for
++ * use in the OpenSSL Toolkit (http://www.openssl.org/).
 + *
-+ * CKM_RSA_X_509
-+ * CKM_RSA_PKCS
-+ * CKM_DSA
++ * This project also referenced hw_pkcs11-0.9.7b.patch written by
++ * Afchine Madjlessi.
++ */
++/*
++ * ====================================================================
++ * Copyright (c) 2000-2001 The OpenSSL Project.  All rights reserved.
 + *
-+ * The first slot that supports at least one of those mechanisms is chosen as a
-+ * public key slot.
++ * Redistribution and use in source and binary forms, with or without
++ * modification, are permitted provided that the following conditions
++ * are met:
 + *
-+ * Symmetric ciphers optionally supported
++ * 1. Redistributions of source code must retain the above copyright
++ *    notice, this list of conditions and the following disclaimer.
 + *
-+ * CKM_DES3_CBC
-+ * CKM_DES_CBC
-+ * CKM_AES_CBC
-+ * CKM_DES3_ECB
-+ * CKM_DES_ECB
-+ * CKM_AES_ECB
-+ * CKM_AES_CTR
-+ * CKM_RC4
-+ * CKM_BLOWFISH_CBC
++ * 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.
 + *
-+ * Digests optionally supported
++ * 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/)"
 + *
-+ * CKM_MD5
-+ * CKM_SHA_1
-+ * CKM_SHA224
-+ * CKM_SHA256
-+ * CKM_SHA384
-+ * CKM_SHA512
++ * 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).
 + *
-+ * The output of this function is a set of global variables indicating which
-+ * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
-+ * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
-+ * variables carry information about which slot was chosen for (a) public key
-+ * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
 + */
-+static int
-+pk11_choose_slots(int *any_slot_found)
-+      {
-+      CK_SLOT_ID_PTR pSlotList = NULL_PTR;
-+      CK_ULONG ulSlotCount = 0;
-+      CK_MECHANISM_INFO mech_info;
-+      CK_TOKEN_INFO token_info;
-+      unsigned int i;
-+      CK_RV rv;
-+      CK_SLOT_ID best_slot_sofar = 0;
-+      CK_BBOOL found_candidate_slot = CK_FALSE;
-+      int slot_n_cipher = 0;
-+      int slot_n_digest = 0;
-+      CK_SLOT_ID current_slot = 0;
-+      int current_slot_n_cipher = 0;
-+      int current_slot_n_digest = 0;
-+
-+      int local_cipher_nids[PK11_CIPHER_MAX];
-+      int local_digest_nids[PK11_DIGEST_MAX];
 +
-+      /* let's initialize the output parameter */
-+      if (any_slot_found != NULL)
-+              *any_slot_found = 0;
-+
-+      /* Get slot list for memory allocation */
-+      rv = pFuncList->C_GetSlotList(0, NULL_PTR, &ulSlotCount);
++#include <stdio.h>
++#include <openssl/err.h>
++#include "hw_pk11_err.h"
 +
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
-+              return (0);
-+              }
++/* BEGIN ERROR CODES */
++#ifndef OPENSSL_NO_ERR
++static ERR_STRING_DATA pk11_str_functs[]=
++{
++{ ERR_PACK(0, PK11_F_INIT, 0),                        "PK11_INIT"},
++{ ERR_PACK(0, PK11_F_FINISH, 0),              "PK11_FINISH"},
++{ ERR_PACK(0, PK11_F_DESTROY, 0),             "PK11_DESTROY"},
++{ ERR_PACK(0, PK11_F_CTRL, 0),                        "PK11_CTRL"},
++{ ERR_PACK(0, PK11_F_RSA_INIT, 0),            "PK11_RSA_INIT"},
++{ ERR_PACK(0, PK11_F_RSA_FINISH, 0),          "PK11_RSA_FINISH"},
++{ ERR_PACK(0, PK11_F_GET_PUB_RSA_KEY, 0),     "PK11_GET_PUB_RSA_KEY"},
++{ ERR_PACK(0, PK11_F_GET_PRIV_RSA_KEY, 0),    "PK11_GET_PRIV_RSA_KEY"},
++{ ERR_PACK(0, PK11_F_RSA_GEN_KEY, 0),         "PK11_RSA_GEN_KEY"},
++{ ERR_PACK(0, PK11_F_RSA_PUB_ENC, 0),         "PK11_RSA_PUB_ENC"},
++{ ERR_PACK(0, PK11_F_RSA_PRIV_ENC, 0),                "PK11_RSA_PRIV_ENC"},
++{ ERR_PACK(0, PK11_F_RSA_PUB_DEC, 0),         "PK11_RSA_PUB_DEC"},
++{ ERR_PACK(0, PK11_F_RSA_PRIV_DEC, 0),                "PK11_RSA_PRIV_DEC"},
++{ ERR_PACK(0, PK11_F_RSA_SIGN, 0),            "PK11_RSA_SIGN"},
++{ ERR_PACK(0, PK11_F_RSA_VERIFY, 0),          "PK11_RSA_VERIFY"},
++{ ERR_PACK(0, PK11_F_RAND_ADD, 0),            "PK11_RAND_ADD"},
++{ ERR_PACK(0, PK11_F_RAND_BYTES, 0),          "PK11_RAND_BYTES"},
++{ ERR_PACK(0, PK11_F_GET_SESSION, 0),         "PK11_GET_SESSION"},
++{ ERR_PACK(0, PK11_F_FREE_SESSION, 0),                "PK11_FREE_SESSION"},
++{ ERR_PACK(0, PK11_F_LOAD_PUBKEY, 0),         "PK11_LOAD_PUBKEY"},
++{ ERR_PACK(0, PK11_F_LOAD_PRIVKEY, 0),                "PK11_LOAD_PRIV_KEY"},
++{ ERR_PACK(0, PK11_F_RSA_PUB_ENC_LOW, 0),     "PK11_RSA_PUB_ENC_LOW"},
++{ ERR_PACK(0, PK11_F_RSA_PRIV_ENC_LOW, 0),    "PK11_RSA_PRIV_ENC_LOW"},
++{ ERR_PACK(0, PK11_F_RSA_PUB_DEC_LOW, 0),     "PK11_RSA_PUB_DEC_LOW"},
++{ ERR_PACK(0, PK11_F_RSA_PRIV_DEC_LOW, 0),    "PK11_RSA_PRIV_DEC_LOW"},
++{ ERR_PACK(0, PK11_F_DSA_SIGN, 0),            "PK11_DSA_SIGN"},
++{ ERR_PACK(0, PK11_F_DSA_VERIFY, 0),          "PK11_DSA_VERIFY"},
++{ ERR_PACK(0, PK11_F_DSA_INIT, 0),            "PK11_DSA_INIT"},
++{ ERR_PACK(0, PK11_F_DSA_FINISH, 0),          "PK11_DSA_FINISH"},
++{ ERR_PACK(0, PK11_F_GET_PUB_DSA_KEY, 0),     "PK11_GET_PUB_DSA_KEY"},
++{ ERR_PACK(0, PK11_F_GET_PRIV_DSA_KEY, 0),    "PK11_GET_PRIV_DSA_KEY"},
++{ ERR_PACK(0, PK11_F_DH_INIT, 0),             "PK11_DH_INIT"},
++{ ERR_PACK(0, PK11_F_DH_FINISH, 0),           "PK11_DH_FINISH"},
++{ ERR_PACK(0, PK11_F_MOD_EXP_DH, 0),          "PK11_MOD_EXP_DH"},
++{ ERR_PACK(0, PK11_F_GET_DH_KEY, 0),          "PK11_GET_DH_KEY"},
++{ ERR_PACK(0, PK11_F_FREE_ALL_SESSIONS, 0),   "PK11_FREE_ALL_SESSIONS"},
++{ ERR_PACK(0, PK11_F_SETUP_SESSION, 0),               "PK11_SETUP_SESSION"},
++{ ERR_PACK(0, PK11_F_DESTROY_OBJECT, 0),      "PK11_DESTROY_OBJECT"},
++{ ERR_PACK(0, PK11_F_CIPHER_INIT, 0),         "PK11_CIPHER_INIT"},
++{ ERR_PACK(0, PK11_F_CIPHER_DO_CIPHER, 0),    "PK11_CIPHER_DO_CIPHER"},
++{ ERR_PACK(0, PK11_F_GET_CIPHER_KEY, 0),      "PK11_GET_CIPHER_KEY"},
++{ ERR_PACK(0, PK11_F_DIGEST_INIT, 0),         "PK11_DIGEST_INIT"},
++{ ERR_PACK(0, PK11_F_DIGEST_UPDATE, 0),               "PK11_DIGEST_UPDATE"},
++{ ERR_PACK(0, PK11_F_DIGEST_FINAL, 0),                "PK11_DIGEST_FINAL"},
++{ ERR_PACK(0, PK11_F_CHOOSE_SLOT, 0),         "PK11_CHOOSE_SLOT"},
++{ ERR_PACK(0, PK11_F_CIPHER_FINAL, 0),                "PK11_CIPHER_FINAL"},
++{ ERR_PACK(0, PK11_F_LIBRARY_INIT, 0),                "PK11_LIBRARY_INIT"},
++{ ERR_PACK(0, PK11_F_LOAD, 0),                        "ENGINE_LOAD_PK11"},
++{ ERR_PACK(0, PK11_F_DH_GEN_KEY, 0),          "PK11_DH_GEN_KEY"},
++{ ERR_PACK(0, PK11_F_DH_COMP_KEY, 0),         "PK11_DH_COMP_KEY"},
++{ ERR_PACK(0, PK11_F_DIGEST_COPY, 0),         "PK11_DIGEST_COPY"},
++{ ERR_PACK(0, PK11_F_CIPHER_CLEANUP, 0),      "PK11_CIPHER_CLEANUP"},
++{ ERR_PACK(0, PK11_F_ACTIVE_ADD, 0),          "PK11_ACTIVE_ADD"},
++{ ERR_PACK(0, PK11_F_ACTIVE_DELETE, 0),               "PK11_ACTIVE_DELETE"},
++{ ERR_PACK(0, PK11_F_CHECK_HW_MECHANISMS, 0), "PK11_CHECK_HW_MECHANISMS"},
++{ ERR_PACK(0, PK11_F_INIT_SYMMETRIC, 0),      "PK11_INIT_SYMMETRIC"},
++{ ERR_PACK(0, PK11_F_ADD_AES_CTR_NIDS, 0),    "PK11_ADD_AES_CTR_NIDS"},
++{ 0, NULL}
++};
 +
-+      /* it's not an error if we didn't find any providers */
-+      if (ulSlotCount == 0)
-+              {
-+#ifdef        DEBUG_SLOT_SELECTION
-+              fprintf(stderr, "%s: no crypto providers found\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              return (1);
-+              }
++static ERR_STRING_DATA pk11_str_reasons[]=
++{
++{ PK11_R_ALREADY_LOADED,              "PKCS#11 DSO already loaded"},
++{ PK11_R_DSO_FAILURE,                 "unable to load PKCS#11 DSO"},
++{ PK11_R_NOT_LOADED,                  "PKCS#11 DSO not loaded"},
++{ PK11_R_PASSED_NULL_PARAMETER,               "null parameter passed"},
++{ PK11_R_COMMAND_NOT_IMPLEMENTED,     "command not implemented"},
++{ PK11_R_INITIALIZE,                  "C_Initialize failed"},
++{ PK11_R_FINALIZE,                    "C_Finalize failed"},
++{ PK11_R_GETINFO,                     "C_GetInfo faile"},
++{ PK11_R_GETSLOTLIST,                 "C_GetSlotList failed"},
++{ PK11_R_NO_MODULUS_OR_NO_EXPONENT,   "no modulus or no exponent"},
++{ PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID,       "attr sensitive or invalid"},
++{ PK11_R_GETATTRIBUTVALUE,            "C_GetAttributeValue failed"},
++{ PK11_R_NO_MODULUS,                  "no modulus"},
++{ PK11_R_NO_EXPONENT,                 "no exponent"},
++{ PK11_R_FINDOBJECTSINIT,             "C_FindObjectsInit failed"},
++{ PK11_R_FINDOBJECTS,                 "C_FindObjects failed"},
++{ PK11_R_FINDOBJECTSFINAL,            "C_FindObjectsFinal failed"},
++{ PK11_R_CREATEOBJECT,                        "C_CreateObject failed"},
++{ PK11_R_DESTROYOBJECT,                       "C_DestroyObject failed"},
++{ PK11_R_OPENSESSION,                 "C_OpenSession failed"},
++{ PK11_R_CLOSESESSION,                        "C_CloseSession failed"},
++{ PK11_R_ENCRYPTINIT,                 "C_EncryptInit failed"},
++{ PK11_R_ENCRYPT,                     "C_Encrypt failed"},
++{ PK11_R_SIGNINIT,                    "C_SignInit failed"},
++{ PK11_R_SIGN,                                "C_Sign failed"},
++{ PK11_R_DECRYPTINIT,                 "C_DecryptInit failed"},
++{ PK11_R_DECRYPT,                     "C_Decrypt failed"},
++{ PK11_R_VERIFYINIT,                  "C_VerifyRecover failed"},
++{ PK11_R_VERIFY,                      "C_Verify failed"},
++{ PK11_R_VERIFYRECOVERINIT,           "C_VerifyRecoverInit failed"},
++{ PK11_R_VERIFYRECOVER,                       "C_VerifyRecover failed"},
++{ PK11_R_GEN_KEY,                     "C_GenerateKeyPair failed"},
++{ PK11_R_SEEDRANDOM,                  "C_SeedRandom failed"},
++{ PK11_R_GENERATERANDOM,              "C_GenerateRandom failed"},
++{ PK11_R_INVALID_MESSAGE_LENGTH,      "invalid message length"},
++{ PK11_R_UNKNOWN_ALGORITHM_TYPE,      "unknown algorithm type"},
++{ PK11_R_UNKNOWN_ASN1_OBJECT_ID,      "unknown asn1 onject id"},
++{ PK11_R_UNKNOWN_PADDING_TYPE,                "unknown padding type"},
++{ PK11_R_PADDING_CHECK_FAILED,                "padding check failed"},
++{ PK11_R_DIGEST_TOO_BIG,              "digest too big"},
++{ PK11_R_MALLOC_FAILURE,              "malloc failure"},
++{ PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED,        "ctl command not implemented"},
++{ PK11_R_DATA_GREATER_THAN_MOD_LEN,   "data is bigger than mod"},
++{ PK11_R_DATA_TOO_LARGE_FOR_MODULUS,  "data is too larger for mod"},
++{ PK11_R_MISSING_KEY_COMPONENT,               "a dsa component is missing"},
++{ PK11_R_INVALID_SIGNATURE_LENGTH,    "invalid signature length"},
++{ PK11_R_INVALID_DSA_SIGNATURE_R,     "missing r in dsa verify"},
++{ PK11_R_INVALID_DSA_SIGNATURE_S,     "missing s in dsa verify"},
++{ PK11_R_INCONSISTENT_KEY,            "inconsistent key type"},
++{ PK11_R_ENCRYPTUPDATE,                       "C_EncryptUpdate failed"},
++{ PK11_R_DECRYPTUPDATE,                       "C_DecryptUpdate failed"},
++{ PK11_R_DIGESTINIT,                  "C_DigestInit failed"},
++{ PK11_R_DIGESTUPDATE,                        "C_DigestUpdate failed"},
++{ PK11_R_DIGESTFINAL,                 "C_DigestFinal failed"},
++{ PK11_R_ENCRYPTFINAL,                        "C_EncryptFinal failed"},
++{ PK11_R_DECRYPTFINAL,                        "C_DecryptFinal failed"},
++{ PK11_R_NO_PRNG_SUPPORT,             "Slot does not support PRNG"},
++{ PK11_R_GETTOKENINFO,                        "C_GetTokenInfo failed"},
++{ PK11_R_DERIVEKEY,                   "C_DeriveKey failed"},
++{ PK11_R_GET_OPERATION_STATE,         "C_GetOperationState failed"},
++{ PK11_R_SET_OPERATION_STATE,         "C_SetOperationState failed"},
++{ PK11_R_INVALID_PIN,                 "invalid PIN"},
++{ PK11_R_TOO_MANY_OBJECTS,            "too many objects"},
++{ PK11_R_OBJECT_NOT_FOUND,            "object not found"},
++{ PK11_R_INVALID_HANDLE,              "invalid PKCS#11 object handle"},
++{ PK11_R_KEY_OR_IV_LEN_PROBLEM,               "IV or key length incorrect"},
++{ PK11_R_INVALID_OPERATION_TYPE,      "invalid operation type"},
++{ PK11_R_ADD_NID_FAILED,              "failed to add NID" },
++{ 0,  NULL}
++};
++#endif        /* OPENSSL_NO_ERR */
 +
-+      pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
++static int pk11_lib_error_code = 0;
++static int pk11_error_init = 1;
 +
-+      if (pSlotList == NULL)
++static void
++ERR_load_pk11_strings(void)
++      {
++      if (pk11_lib_error_code == 0)
++              pk11_lib_error_code = ERR_get_next_error_library();
++
++      if (pk11_error_init)
 +              {
-+              PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
-+              return (0);
++              pk11_error_init = 0;
++#ifndef OPENSSL_NO_ERR
++              ERR_load_strings(pk11_lib_error_code, pk11_str_functs);
++              ERR_load_strings(pk11_lib_error_code, pk11_str_reasons);
++#endif
 +              }
++}
 +
-+      /* Get the slot list for processing */
-+      rv = pFuncList->C_GetSlotList(0, pSlotList, &ulSlotCount);
-+      if (rv != CKR_OK)
++static void
++ERR_unload_pk11_strings(void)
++      {
++      if (pk11_error_init == 0)
 +              {
-+              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
-+              OPENSSL_free(pSlotList);
-+              return (0);
++#ifndef OPENSSL_NO_ERR
++              ERR_unload_strings(pk11_lib_error_code, pk11_str_functs);
++              ERR_unload_strings(pk11_lib_error_code, pk11_str_reasons);
++#endif
++              pk11_error_init = 1;
 +              }
++}
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
-+      fprintf(stderr, "%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
-+
-+      fprintf(stderr, "%s: == checking rand slots ==\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+      for (i = 0; i < ulSlotCount; i++)
-+              {
-+              current_slot = pSlotList[i];
++void
++ERR_pk11_error(int function, int reason, char *file, int line)
++{
++      if (pk11_lib_error_code == 0)
++              pk11_lib_error_code = ERR_get_next_error_library();
++      ERR_PUT_error(pk11_lib_error_code, function, reason, file, line);
++}
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              /* Check if slot has random support. */
-+              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
-+              if (rv != CKR_OK)
-+                      continue;
++void
++PK11err_add_data(int function, int reason, CK_RV rv)
++{
++      char tmp_buf[20];
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
-+#endif        /* DEBUG_SLOT_SELECTION */
++      PK11err(function, reason);
++      (void) BIO_snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
++      ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
++}
+Index: openssl/crypto/engine/hw_pk11_err.h
+diff -u /dev/null openssl/crypto/engine/hw_pk11_err.h:1.9
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11_err.h        Wed Dec 17 15:01:45 2008
+@@ -0,0 +1,402 @@
++/*
++ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
++ * Use is subject to license terms.
++ */
 +
-+              if (token_info.flags & CKF_RNG)
-+                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: this token has CKF_RNG flag\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      pk11_have_random = CK_TRUE;
-+                      rand_SLOTID = current_slot;
-+                      break;
-+                      }
-+              }
++/* crypto/engine/hw_pk11_err.h */
++/*
++ * 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).
++ *
++ */
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: == checking pubkey slots ==\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
++#ifndef       HW_PK11_ERR_H
++#define       HW_PK11_ERR_H
 +
-+      pubkey_SLOTID = pSlotList[0];
-+      for (i = 0; i < ulSlotCount; i++)
-+              {
-+              CK_BBOOL slot_has_rsa = CK_FALSE;
-+              CK_BBOOL slot_has_recover = CK_FALSE;
-+              CK_BBOOL slot_has_dsa = CK_FALSE;
-+              CK_BBOOL slot_has_dh = CK_FALSE;
-+              current_slot = pSlotList[i];
++void ERR_pk11_error(int function, int reason, char *file, int line);
++void PK11err_add_data(int function, int reason, CK_RV rv);
++#define       PK11err(f, r)   ERR_pk11_error((f), (r), __FILE__, __LINE__)
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
-+              if (rv != CKR_OK)
-+                      continue;
++/* Error codes for the PK11 functions. */
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
-+#endif        /* DEBUG_SLOT_SELECTION */
++/* Function codes. */
 +
-+#ifndef OPENSSL_NO_RSA
-+              /*
-+               * Check if this slot is capable of signing and
-+               * verifying with CKM_RSA_PKCS.
-+               */
-+              rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
-+                      &mech_info);
++#define       PK11_F_INIT                             100
++#define       PK11_F_FINISH                           101
++#define       PK11_F_DESTROY                          102
++#define       PK11_F_CTRL                             103
++#define       PK11_F_RSA_INIT                         104
++#define       PK11_F_RSA_FINISH                       105
++#define       PK11_F_GET_PUB_RSA_KEY                  106
++#define       PK11_F_GET_PRIV_RSA_KEY                 107
++#define       PK11_F_RSA_GEN_KEY                      108
++#define       PK11_F_RSA_PUB_ENC                      109
++#define       PK11_F_RSA_PRIV_ENC                     110
++#define       PK11_F_RSA_PUB_DEC                      111
++#define       PK11_F_RSA_PRIV_DEC                     112
++#define       PK11_F_RSA_SIGN                         113
++#define       PK11_F_RSA_VERIFY                       114
++#define       PK11_F_RAND_ADD                         115
++#define       PK11_F_RAND_BYTES                       116
++#define       PK11_F_GET_SESSION                      117
++#define       PK11_F_FREE_SESSION                     118
++#define       PK11_F_LOAD_PUBKEY                      119
++#define       PK11_F_LOAD_PRIVKEY                     120
++#define       PK11_F_RSA_PUB_ENC_LOW                  121
++#define       PK11_F_RSA_PRIV_ENC_LOW                 122
++#define       PK11_F_RSA_PUB_DEC_LOW                  123
++#define       PK11_F_RSA_PRIV_DEC_LOW                 124
++#define       PK11_F_DSA_SIGN                         125
++#define       PK11_F_DSA_VERIFY                       126
++#define       PK11_F_DSA_INIT                         127
++#define       PK11_F_DSA_FINISH                       128
++#define       PK11_F_GET_PUB_DSA_KEY                  129
++#define       PK11_F_GET_PRIV_DSA_KEY                 130
++#define       PK11_F_DH_INIT                          131
++#define       PK11_F_DH_FINISH                        132
++#define       PK11_F_MOD_EXP_DH                       133
++#define       PK11_F_GET_DH_KEY                       134
++#define       PK11_F_FREE_ALL_SESSIONS                135
++#define       PK11_F_SETUP_SESSION                    136
++#define       PK11_F_DESTROY_OBJECT                   137
++#define       PK11_F_CIPHER_INIT                      138
++#define       PK11_F_CIPHER_DO_CIPHER                 139
++#define       PK11_F_GET_CIPHER_KEY                   140
++#define       PK11_F_DIGEST_INIT                      141
++#define       PK11_F_DIGEST_UPDATE                    142
++#define       PK11_F_DIGEST_FINAL                     143
++#define       PK11_F_CHOOSE_SLOT                      144
++#define       PK11_F_CIPHER_FINAL                     145
++#define       PK11_F_LIBRARY_INIT                     146
++#define       PK11_F_LOAD                             147
++#define       PK11_F_DH_GEN_KEY                       148
++#define       PK11_F_DH_COMP_KEY                      149
++#define       PK11_F_DIGEST_COPY                      150
++#define       PK11_F_CIPHER_CLEANUP                   151
++#define       PK11_F_ACTIVE_ADD                       152
++#define       PK11_F_ACTIVE_DELETE                    153
++#define       PK11_F_CHECK_HW_MECHANISMS              154
++#define       PK11_F_INIT_SYMMETRIC                   155
++#define       PK11_F_ADD_AES_CTR_NIDS                 156
++#define       PK11_F_INIT_ALL_LOCKS                   157
++#define       PK11_F_RETURN_SESSION                   158
 +
-+              if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
-+                              (mech_info.flags & CKF_VERIFY)))
-+                      {
-+                      /*
-+                       * Check if this slot is capable of encryption,
-+                       * decryption, sign, and verify with CKM_RSA_X_509.
-+                       */
-+                      rv = pFuncList->C_GetMechanismInfo(current_slot,
-+                          CKM_RSA_X_509, &mech_info);
++/* Reason codes. */
++#define       PK11_R_ALREADY_LOADED                   100
++#define       PK11_R_DSO_FAILURE                      101
++#define       PK11_R_NOT_LOADED                       102
++#define       PK11_R_PASSED_NULL_PARAMETER            103
++#define       PK11_R_COMMAND_NOT_IMPLEMENTED          104
++#define       PK11_R_INITIALIZE                       105
++#define       PK11_R_FINALIZE                         106
++#define       PK11_R_GETINFO                          107
++#define       PK11_R_GETSLOTLIST                      108
++#define       PK11_R_NO_MODULUS_OR_NO_EXPONENT        109
++#define       PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID    110
++#define       PK11_R_GETATTRIBUTVALUE                 111
++#define       PK11_R_NO_MODULUS                       112
++#define       PK11_R_NO_EXPONENT                      113
++#define       PK11_R_FINDOBJECTSINIT                  114
++#define       PK11_R_FINDOBJECTS                      115
++#define       PK11_R_FINDOBJECTSFINAL                 116
++#define       PK11_R_CREATEOBJECT                     118
++#define       PK11_R_DESTROYOBJECT                    119
++#define       PK11_R_OPENSESSION                      120
++#define       PK11_R_CLOSESESSION                     121
++#define       PK11_R_ENCRYPTINIT                      122
++#define       PK11_R_ENCRYPT                          123
++#define       PK11_R_SIGNINIT                         124
++#define       PK11_R_SIGN                             125
++#define       PK11_R_DECRYPTINIT                      126
++#define       PK11_R_DECRYPT                          127
++#define       PK11_R_VERIFYINIT                       128
++#define       PK11_R_VERIFY                           129
++#define       PK11_R_VERIFYRECOVERINIT                130
++#define       PK11_R_VERIFYRECOVER                    131
++#define       PK11_R_GEN_KEY                          132
++#define       PK11_R_SEEDRANDOM                       133
++#define       PK11_R_GENERATERANDOM                   134
++#define       PK11_R_INVALID_MESSAGE_LENGTH           135
++#define       PK11_R_UNKNOWN_ALGORITHM_TYPE           136
++#define       PK11_R_UNKNOWN_ASN1_OBJECT_ID           137
++#define       PK11_R_UNKNOWN_PADDING_TYPE             138
++#define       PK11_R_PADDING_CHECK_FAILED             139
++#define       PK11_R_DIGEST_TOO_BIG                   140
++#define       PK11_R_MALLOC_FAILURE                   141
++#define       PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED     142
++#define       PK11_R_DATA_GREATER_THAN_MOD_LEN        143
++#define       PK11_R_DATA_TOO_LARGE_FOR_MODULUS       144
++#define       PK11_R_MISSING_KEY_COMPONENT            145
++#define       PK11_R_INVALID_SIGNATURE_LENGTH         146
++#define       PK11_R_INVALID_DSA_SIGNATURE_R          147
++#define       PK11_R_INVALID_DSA_SIGNATURE_S          148
++#define       PK11_R_INCONSISTENT_KEY                 149
++#define       PK11_R_ENCRYPTUPDATE                    150
++#define       PK11_R_DECRYPTUPDATE                    151
++#define       PK11_R_DIGESTINIT                       152
++#define       PK11_R_DIGESTUPDATE                     153
++#define       PK11_R_DIGESTFINAL                      154
++#define       PK11_R_ENCRYPTFINAL                     155
++#define       PK11_R_DECRYPTFINAL                     156
++#define       PK11_R_NO_PRNG_SUPPORT                  157
++#define       PK11_R_GETTOKENINFO                     158
++#define       PK11_R_DERIVEKEY                        159
++#define       PK11_R_GET_OPERATION_STATE              160
++#define       PK11_R_SET_OPERATION_STATE              161
++#define       PK11_R_INVALID_HANDLE                   162
++#define       PK11_R_KEY_OR_IV_LEN_PROBLEM            163
++#define       PK11_R_INVALID_OPERATION_TYPE           164
++#define       PK11_R_ADD_NID_FAILED                   165
++#define       PK11_R_ATFORK_FAILED                    166
++#define       PK11_R_INVALID_PIN                      167
++#define       PK11_R_TOO_MANY_OBJECTS                 168
++#define       PK11_R_OBJECT_NOT_FOUND                 169
 +
-+                      if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
-+                          (mech_info.flags & CKF_VERIFY) &&
-+                          (mech_info.flags & CKF_ENCRYPT) &&
-+                          (mech_info.flags & CKF_DECRYPT)))
-+                              {
-+                              slot_has_rsa = CK_TRUE;
-+                              if (mech_info.flags & CKF_VERIFY_RECOVER)
-+                                      {
-+                                      slot_has_recover = CK_TRUE;
-+                                      }
-+                              }
-+                      }
-+#endif        /* OPENSSL_NO_RSA */
++/* max byte length of a symetric key we support */
++#define       PK11_KEY_LEN_MAX                        32
++
++#ifdef NOPTHREADS
++/*
++ * CRYPTO_LOCK_PK11_ENGINE lock is primarily used for the protection of the
++ * free_session list and active_list but generally serves as a global
++ * per-process lock for the whole engine.
++ *
++ * We reuse CRYPTO_LOCK_EC lock (which is defined in OpenSSL for EC method) as
++ * the global engine lock. This is not optimal w.r.t. performance but
++ * it's safe.
++ */
++#define CRYPTO_LOCK_PK11_ENGINE       CRYPTO_LOCK_EC
++#endif
 +
++/*
++ * This structure encapsulates all reusable information for a PKCS#11
++ * session. A list of these objects is created on behalf of the
++ * calling application using an on-demand method. Each operation
++ * type (see PK11_OPTYPE below) has its own per-process list.
++ * Each of the lists is basically a cache for faster PKCS#11 object
++ * access to avoid expensive C_Find{,Init,Final}Object() calls.
++ *
++ * When a new request comes in, an object will be taken from the list
++ * (if there is one) or a new one is created to handle the request
++ * (if the list is empty). See pk11_get_session() on how it is done.
++ */
++typedef struct PK11_st_SESSION
++      {
++      struct PK11_st_SESSION  *next;
++      CK_SESSION_HANDLE       session;        /* PK11 session handle */
++      pid_t                   pid;            /* Current process ID */
++      union
++              {
++#ifndef OPENSSL_NO_RSA
++              struct
++                      {
++                      CK_OBJECT_HANDLE        rsa_pub_key; /* pub handle */
++                      CK_OBJECT_HANDLE        rsa_priv_key; /* priv handle */
++                      RSA                     *rsa_pub; /* pub key addr */
++                      BIGNUM                  *rsa_n_num; /* pub modulus */
++                      BIGNUM                  *rsa_e_num; /* pub exponent */
++                      RSA                     *rsa_priv; /* priv key addr */
++                      BIGNUM                  *rsa_d_num; /* priv exponent */
++                      } u_RSA;
++#endif /* OPENSSL_NO_RSA */
 +#ifndef OPENSSL_NO_DSA
-+              /*
-+               * Check if this slot is capable of signing and
-+               * verifying with CKM_DSA.
-+               */
-+              rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_DSA,
-+                      &mech_info);
-+              if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
-+                  (mech_info.flags & CKF_VERIFY)))
++              struct
 +                      {
-+                      slot_has_dsa = CK_TRUE;
-+                      }
-+
-+#endif        /* OPENSSL_NO_DSA */
-+
++                      CK_OBJECT_HANDLE        dsa_pub_key; /* pub handle */
++                      CK_OBJECT_HANDLE        dsa_priv_key; /* priv handle */
++                      DSA                     *dsa_pub; /* pub key addr */
++                      BIGNUM                  *dsa_pub_num; /* pub key */
++                      DSA                     *dsa_priv; /* priv key addr */
++                      BIGNUM                  *dsa_priv_num; /* priv key */
++                      } u_DSA;
++#endif /* OPENSSL_NO_DSA */
 +#ifndef OPENSSL_NO_DH
-+              /*
-+               * Check if this slot is capable of DH key generataion and
-+               * derivation.
-+               */
-+              rv = pFuncList->C_GetMechanismInfo(current_slot,
-+                  CKM_DH_PKCS_KEY_PAIR_GEN, &mech_info);
-+
-+              if (rv == CKR_OK && (mech_info.flags & CKF_GENERATE_KEY_PAIR))
++              struct
 +                      {
-+                      rv = pFuncList->C_GetMechanismInfo(current_slot,
-+                              CKM_DH_PKCS_DERIVE, &mech_info);
-+                      if (rv == CKR_OK && (mech_info.flags & CKF_DERIVE))
-+                              {
-+                              slot_has_dh = CK_TRUE;
-+                              }
-+                      }
-+#endif        /* OPENSSL_NO_DH */
-+
-+              if (!found_candidate_slot &&
-+                  (slot_has_rsa || slot_has_dsa || slot_has_dh))
++                      CK_OBJECT_HANDLE        dh_key; /* key handle */
++                      DH                      *dh; /* dh key addr */
++                      BIGNUM                  *dh_priv_num; /* priv dh key */
++                      } u_DH;
++#endif /* OPENSSL_NO_DH */
++              struct
 +                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+                      fprintf(stderr,
-+                          "%s: potential slot: %d\n", PK11_DBG, current_slot);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      best_slot_sofar = current_slot;
-+                      pk11_have_rsa = slot_has_rsa;
-+                      pk11_have_recover = slot_has_recover;
-+                      pk11_have_dsa = slot_has_dsa;
-+                      pk11_have_dh = slot_has_dh;
-+                      found_candidate_slot = CK_TRUE;
-+#ifdef        DEBUG_SLOT_SELECTION
-+                      fprintf(stderr,
-+                          "%s: setting found_candidate_slot to CK_TRUE\n",
-+                          PK11_DBG);
-+                      fprintf(stderr,
-+                          "%s: best so far slot: %d\n", PK11_DBG,
-+                          best_slot_sofar);
-+                      }
-+              else
-+                      {
-+                      fprintf(stderr,
-+                          "%s: no rsa/dsa/dh\n", PK11_DBG);
-+                      }
-+#else
-+                      } /* if */
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              } /* for */
-+
-+      if (found_candidate_slot)
-+              {
-+              pubkey_SLOTID = best_slot_sofar;
-+              }
-+
-+      found_candidate_slot = CK_FALSE;
-+      best_slot_sofar = 0;
-+
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: == checking cipher/digest ==\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+
-+      SLOTID = pSlotList[0];
-+      for (i = 0; i < ulSlotCount; i++)
-+              {
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+
-+              current_slot = pSlotList[i];
-+              current_slot_n_cipher = 0;
-+              current_slot_n_digest = 0;
-+              (void) memset(local_cipher_nids, 0, sizeof (local_cipher_nids));
-+              (void) memset(local_digest_nids, 0, sizeof (local_digest_nids));
-+
-+              pk11_find_symmetric_ciphers(pFuncList, current_slot,
-+                  &current_slot_n_cipher, local_cipher_nids);
++                      CK_OBJECT_HANDLE        cipher_key; /* key handle */
++                      unsigned char           key[PK11_KEY_LEN_MAX];
++                      int                     key_len; /* priv key len */
++                      int                     encrypt; /* 1/0 enc/decr */
++                      } u_cipher;
++              } opdata_u;
++      } PK11_SESSION;
 +
-+              pk11_find_digests(pFuncList, current_slot,
-+                  &current_slot_n_digest, local_digest_nids);
++#define       opdata_rsa_pub_key      opdata_u.u_RSA.rsa_pub_key
++#define       opdata_rsa_priv_key     opdata_u.u_RSA.rsa_priv_key
++#define       opdata_rsa_pub          opdata_u.u_RSA.rsa_pub
++#define       opdata_rsa_priv         opdata_u.u_RSA.rsa_priv
++#define       opdata_rsa_n_num        opdata_u.u_RSA.rsa_n_num
++#define       opdata_rsa_e_num        opdata_u.u_RSA.rsa_e_num
++#define       opdata_rsa_d_num        opdata_u.u_RSA.rsa_d_num
++#define       opdata_dsa_pub_key      opdata_u.u_DSA.dsa_pub_key
++#define       opdata_dsa_priv_key     opdata_u.u_DSA.dsa_priv_key
++#define       opdata_dsa_pub          opdata_u.u_DSA.dsa_pub
++#define       opdata_dsa_pub_num      opdata_u.u_DSA.dsa_pub_num
++#define       opdata_dsa_priv         opdata_u.u_DSA.dsa_priv
++#define       opdata_dsa_priv_num     opdata_u.u_DSA.dsa_priv_num
++#define       opdata_dh_key           opdata_u.u_DH.dh_key
++#define       opdata_dh               opdata_u.u_DH.dh
++#define       opdata_dh_priv_num      opdata_u.u_DH.dh_priv_num
++#define       opdata_cipher_key       opdata_u.u_cipher.cipher_key
++#define       opdata_key              opdata_u.u_cipher.key
++#define       opdata_key_len          opdata_u.u_cipher.key_len
++#define       opdata_encrypt          opdata_u.u_cipher.encrypt
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+              fprintf(stderr, "%s: current_slot_n_cipher %d\n", PK11_DBG,
-+                      current_slot_n_cipher);
-+              fprintf(stderr, "%s: current_slot_n_digest %d\n", PK11_DBG,
-+                      current_slot_n_digest);
-+              fprintf(stderr, "%s: best so far cipher/digest slot: %d\n",
-+                      PK11_DBG, best_slot_sofar);
-+#endif        /* DEBUG_SLOT_SELECTION */
++/*
++ * We have 3 different groups of operation types:
++ *   1) asymmetric operations
++ *   2) random operations
++ *   3) symmetric and digest operations
++ *
++ * This division into groups stems from the fact that it's common that hardware
++ * providers may support operations from one group only. For example, hardware
++ * providers on UltraSPARC T2, n2rng(7d), ncp(7d), and n2cp(7d), each support
++ * only a single group of operations.
++ *
++ * For every group a different slot can be chosen. That means that we must have
++ * at least 3 different lists of cached PKCS#11 sessions since sessions from
++ * different groups may be initialized in different slots.
++ *
++ * To provide locking granularity in multithreaded environment, the groups are
++ * further splitted into types with each type having a separate session cache.
++ */
++typedef enum PK11_OPTYPE_ENUM
++      {
++      OP_RAND,
++      OP_RSA,
++      OP_DSA,
++      OP_DH,
++      OP_CIPHER,
++      OP_DIGEST,
++      OP_MAX
++      } PK11_OPTYPE;
 +
-+              /*
-+               * If the current slot supports more ciphers/digests than
-+               * the previous best one we change the current best to this one,
-+               * otherwise leave it where it is.
-+               */
-+              if ((current_slot_n_cipher + current_slot_n_digest) >
-+                  (slot_n_cipher + slot_n_digest))
-+                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+                      fprintf(stderr,
-+                              "%s: changing best so far slot to %d\n",
-+                              PK11_DBG, current_slot);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      best_slot_sofar = SLOTID = current_slot;
-+                      cipher_count = slot_n_cipher = current_slot_n_cipher;
-+                      digest_count = slot_n_digest = current_slot_n_digest;
-+                      (void) memcpy(cipher_nids, local_cipher_nids,
-+                          sizeof (local_cipher_nids));
-+                      (void) memcpy(digest_nids, local_digest_nids, 
-+                          sizeof (local_digest_nids));
-+                      }
-+              }
++/*
++ * This structure contains the heads of the lists forming the object caches
++ * and locks associated with the lists.
++ */
++typedef struct PK11_st_CACHE
++      {
++      PK11_SESSION *head;
++#ifndef NOPTHREADS
++      pthread_mutex_t *lock;
++#endif
++      } PK11_CACHE;
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr,
-+          "%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
-+      fprintf(stderr,
-+          "%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
-+      fprintf(stderr,
-+          "%s: chosen cipher/digest slot: %d\n", PK11_DBG, SLOTID);
-+      fprintf(stderr,
-+          "%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
-+      fprintf(stderr,
-+          "%s: pk11_have_recover %d\n", PK11_DBG, pk11_have_recover);
-+      fprintf(stderr,
-+          "%s: pk11_have_dsa %d\n", PK11_DBG, pk11_have_dsa);
-+      fprintf(stderr,
-+          "%s: pk11_have_dh %d\n", PK11_DBG, pk11_have_dh);
-+      fprintf(stderr,
-+          "%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
-+      fprintf(stderr,
-+          "%s: cipher_count %d\n", PK11_DBG, cipher_count);
-+      fprintf(stderr,
-+          "%s: digest_count %d\n", PK11_DBG, digest_count);
-+#endif        /* DEBUG_SLOT_SELECTION */
++/* structure for tracking handles of asymmetric key objects */
++typedef struct PK11_active_st
++      {
++      CK_OBJECT_HANDLE h;
++      unsigned int refcnt;
++      struct PK11_active_st *prev;
++      struct PK11_active_st *next;
++      } PK11_active;
 +
-+      if (pSlotList != NULL)
-+              OPENSSL_free(pSlotList);
++#ifndef NOPTHREADS
++extern pthread_mutex_t *find_lock[];
++#endif
++extern PK11_active *active_list[];
 +
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
-+      OPENSSL_free(hw_cnids);
-+      OPENSSL_free(hw_dnids);
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
++#ifndef NOPTHREADS
++#define       LOCK_OBJSTORE(alg_type) \
++      (void) pthread_mutex_lock(find_lock[alg_type])
++#define       UNLOCK_OBJSTORE(alg_type)       \
++      (void) pthread_mutex_unlock(find_lock[alg_type])
++#else
++#define       LOCK_OBJSTORE(alg_type) \
++      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE)
++#define       UNLOCK_OBJSTORE(alg_type)       \
++      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE)
++#endif
 +
-+      if (any_slot_found != NULL)
-+              *any_slot_found = 1;
-+      return (1);
-+      }
++extern PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
++extern void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);
 +
-+static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR pflist,
-+    int slot_id, CK_MECHANISM_TYPE mech, int *current_slot_n_cipher,
-+    int *local_cipher_nids, int id)
-+      {
-+      CK_MECHANISM_INFO mech_info;
-+      CK_RV rv;
++#ifndef OPENSSL_NO_RSA
++extern int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
++extern int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
++extern int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
++extern EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data);
++extern EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data);
++extern RSA_METHOD *PK11_RSA(void);
++#endif /* OPENSSL_NO_RSA */
++#ifndef OPENSSL_NO_DSA
++extern int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
++extern int pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
++extern int pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
++extern DSA_METHOD *PK11_DSA(void);
++#endif /* OPENSSL_NO_DSA */
++#ifndef OPENSSL_NO_DH
++extern int pk11_destroy_dh_key_objects(PK11_SESSION *session);
++extern int pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock);
++extern DH_METHOD *PK11_DH(void);
++#endif /* OPENSSL_NO_DH */
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: checking mech: %x", PK11_DBG, mech);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+      rv = pflist->C_GetMechanismInfo(slot_id, mech, &mech_info);
++extern CK_FUNCTION_LIST_PTR pFuncList;
 +
-+      if (rv != CKR_OK)
-+              {
-+#ifdef        DEBUG_SLOT_SELECTION
-+              fprintf(stderr, " not found\n");
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              return;
-+              }
++#endif /* HW_PK11_ERR_H */
+Index: openssl/crypto/engine/hw_pk11_pub.c
+diff -u /dev/null openssl/crypto/engine/hw_pk11_pub.c:1.32
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11_pub.c        Mon Oct  5 13:16:55 2009
+@@ -0,0 +1,3140 @@
++/*
++ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
++ * Use is subject to license terms.
++ */
 +
-+      if ((mech_info.flags & CKF_ENCRYPT) &&
-+          (mech_info.flags & CKF_DECRYPT))
-+              {
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
-+              if (nid_in_table(ciphers[id].nid, hw_cnids))
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
-+                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+              fprintf(stderr, " usable\n");
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      local_cipher_nids[(*current_slot_n_cipher)++] =
-+                          ciphers[id].nid;
-+                      }
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
-+#ifdef        DEBUG_SLOT_SELECTION
-+              else
-+                      {
-+              fprintf(stderr, " rejected, software implementation only\n");
-+                      }
-+#endif        /* DEBUG_SLOT_SELECTION */
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
-+              }
-+#ifdef        DEBUG_SLOT_SELECTION
-+      else
-+              {
-+              fprintf(stderr, " unusable\n");
-+              }
-+#endif        /* DEBUG_SLOT_SELECTION */
++/* crypto/engine/hw_pk11_pub.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).
++ *
++ */
 +
-+      return;
-+      }
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++#include <sys/types.h>
 +
-+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)
-+      {
-+      CK_MECHANISM_INFO mech_info;
-+      CK_RV rv;
++#include <openssl/e_os2.h>
++#include <openssl/crypto.h>
++#include <cryptlib.h>
++#include <openssl/engine.h>
++#include <openssl/dso.h>
++#include <openssl/err.h>
++#include <openssl/bn.h>
++#include <openssl/pem.h>
++#ifndef OPENSSL_NO_RSA
++#include <openssl/rsa.h>
++#endif /* OPENSSL_NO_RSA */
++#ifndef OPENSSL_NO_DSA
++#include <openssl/dsa.h>
++#endif /* OPENSSL_NO_DSA */
++#ifndef OPENSSL_NO_DH
++#include <openssl/dh.h>
++#endif /* OPENSSL_NO_DH */
++#include <openssl/rand.h>
++#include <openssl/objects.h>
++#include <openssl/x509.h>
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: checking mech: %x", PK11_DBG, mech);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+      rv = pflist->C_GetMechanismInfo(slot_id, mech, &mech_info);
++#ifdef OPENSSL_SYS_WIN32
++#define NOPTHREADS
++typedef int pid_t;
++#define HAVE_GETPASSPHRASE
++static char *getpassphrase(const char *prompt);
++#ifndef NULL_PTR
++#define NULL_PTR NULL
++#endif
++#define CK_DEFINE_FUNCTION(returnType, name) \
++      returnType __declspec(dllexport) name
++#define CK_DECLARE_FUNCTION(returnType, name) \
++      returnType __declspec(dllimport) name
++#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
++      returnType __declspec(dllimport) (* name)
++#else
++#include <unistd.h>
++#endif
 +
-+      if (rv != CKR_OK)
-+              {
-+#ifdef        DEBUG_SLOT_SELECTION
-+              fprintf(stderr, " not found\n");
-+#endif        /* DEBUG_SLOT_SELECTION */
-+              return;
-+              }
++#ifndef NOPTHREADS
++#include <pthread.h>
++#endif
 +
-+      if (mech_info.flags & CKF_DIGEST)
-+              {
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
-+              if (nid_in_table(digests[id].nid, hw_dnids))
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
-+                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+              fprintf(stderr, " usable\n");
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      local_digest_nids[(*current_slot_n_digest)++] =
-+                          digests[id].nid;
-+                      }
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
-+#ifdef        DEBUG_SLOT_SELECTION
-+              else
-+                      {
-+              fprintf(stderr, " rejected, software implementation only\n");
-+                      }
-+#endif        /* DEBUG_SLOT_SELECTION */
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
-+              }
-+#ifdef        DEBUG_SLOT_SELECTION
-+      else
-+              {
-+              fprintf(stderr, " unusable\n");
-+              }
-+#endif        /* DEBUG_SLOT_SELECTION */
++#ifndef OPENSSL_NO_HW
++#ifndef OPENSSL_NO_HW_PK11
++#ifndef OPENSSL_NO_HW_PK11CA
 +
-+      return;
-+      }
++#ifdef OPENSSL_SYS_WIN32
++#pragma pack(push, cryptoki, 1)
++#include "cryptoki.h"
++#include "pkcs11.h"
++#pragma pack(pop, cryptoki)
++#else
++#include "cryptoki.h"
++#include "pkcs11.h"
++#endif
++#include "hw_pk11ca.h"
++#include "hw_pk11_err.h"
 +
-+#ifdef        SOLARIS_AES_CTR
-+/* create a new NID when we have no OID for that mechanism */
-+static int pk11_add_NID(char *sn, char *ln)
-+      {
-+      ASN1_OBJECT *o;
-+      int nid;
++#if !(defined(HAVE_GETPASSPHRASE) || (defined (__SVR4) && defined (__sun)))
++#define getpassphrase(x)      getpass(x)
++#endif
 +
-+      if ((o = ASN1_OBJECT_create(OBJ_new_nid(1), (unsigned char *)"",
-+          1, sn, ln)) == NULL)
-+              {
-+              return (0);
-+              }
++#ifndef OPENSSL_NO_RSA
++/* RSA stuff */
++static int pk11_RSA_public_encrypt(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa, int padding);
++static int pk11_RSA_private_encrypt(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa, int padding);
++static int pk11_RSA_public_decrypt(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa, int padding);
++static int pk11_RSA_private_decrypt(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa, int padding);
++static int pk11_RSA_init(RSA *rsa);
++static int pk11_RSA_finish(RSA *rsa);
++static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
++      unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
++static int pk11_RSA_verify(int dtype, const unsigned char *m,
++      unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
++      const RSA *rsa);
++EVP_PKEY *pk11_load_privkey(ENGINE*, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data);
++EVP_PKEY *pk11_load_pubkey(ENGINE*, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data);
 +
-+      /* will return NID_undef on error */
-+      nid = OBJ_add_object(o);
-+      ASN1_OBJECT_free(o);
++static int pk11_RSA_public_encrypt_low(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa);
++static int pk11_RSA_private_encrypt_low(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa);
++static int pk11_RSA_public_decrypt_low(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa);
++static int pk11_RSA_private_decrypt_low(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa);
 +
-+      return (nid);
-+      }
++static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA* rsa, RSA** key_ptr,
++      BIGNUM **rsa_n_num, BIGNUM **rsa_e_num, CK_SESSION_HANDLE session);
++static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, RSA** key_ptr,
++      BIGNUM **rsa_d_num, CK_SESSION_HANDLE session);
 +
-+/*
-+ * Create new NIDs for AES counter mode. OpenSSL doesn't support them now so we
-+ * have to help ourselves here.
-+ */
-+static int pk11_add_aes_ctr_NIDs(void)
-+      {
-+      /* are we already set? */
-+      if (NID_aes_256_ctr != NID_undef)
-+              return (1);
++static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa);
++static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa);
++#endif
 +
-+      /*
-+       * There are no official names for AES counter modes yet so we just
-+       * follow the format of those that exist.
-+       */
-+      if ((NID_aes_128_ctr = pk11_add_NID("AES-128-CTR", "aes-128-ctr")) ==
-+          NID_undef)
-+              goto err;
-+      ciphers[PK11_AES_128_CTR].nid = pk11_aes_128_ctr.nid = NID_aes_128_ctr;
-+      if ((NID_aes_192_ctr = pk11_add_NID("AES-192-CTR", "aes-192-ctr")) ==
-+          NID_undef)
-+              goto err;
-+      ciphers[PK11_AES_192_CTR].nid = pk11_aes_192_ctr.nid = NID_aes_192_ctr;
-+      if ((NID_aes_256_ctr = pk11_add_NID("AES-256-CTR", "aes-256-ctr")) ==
-+          NID_undef)
-+              goto err;
-+      ciphers[PK11_AES_256_CTR].nid = pk11_aes_256_ctr.nid = NID_aes_256_ctr;
-+      return (1);
++/* DSA stuff */
++#ifndef OPENSSL_NO_DSA
++static int pk11_DSA_init(DSA *dsa);
++static int pk11_DSA_finish(DSA *dsa);
++static DSA_SIG *pk11_dsa_do_sign(const unsigned char *dgst, int dlen,
++      DSA *dsa);
++static int pk11_dsa_do_verify(const unsigned char *dgst, int dgst_len,
++      DSA_SIG *sig, DSA *dsa);
 +
-+err:
-+      PK11err(PK11_F_ADD_AES_CTR_NIDS, PK11_R_ADD_NID_FAILED);
-+      return (0);
-+      }
-+#endif        /* SOLARIS_AES_CTR */
++static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa, DSA **key_ptr,
++      BIGNUM **dsa_pub_num, CK_SESSION_HANDLE session);
++static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa, DSA **key_ptr,
++      BIGNUM **dsa_priv_num, CK_SESSION_HANDLE session);
 +
-+/* Find what symmetric ciphers this slot supports. */
-+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)
-+      {
-+      int i;
++static int check_new_dsa_key_pub(PK11_SESSION *sp, DSA *dsa);
++static int check_new_dsa_key_priv(PK11_SESSION *sp, DSA *dsa);
++#endif
 +
-+      for (i = 0; i < PK11_CIPHER_MAX; ++i)
-+              {
-+              pk11_get_symmetric_cipher(pflist, current_slot,
-+                  ciphers[i].mech_type, current_slot_n_cipher,
-+                  local_cipher_nids, ciphers[i].id);
-+              }
-+      }
++/* DH stuff */
++#ifndef OPENSSL_NO_DH
++static int pk11_DH_init(DH *dh);
++static int pk11_DH_finish(DH *dh);
++static int pk11_DH_generate_key(DH *dh);
++static int pk11_DH_compute_key(unsigned char *key,
++      const BIGNUM *pub_key, DH *dh);
 +
-+/* Find what digest algorithms this slot supports. */
-+static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
-+    CK_SLOT_ID current_slot, int *current_slot_n_digest, int *local_digest_nids)
-+      {
-+      int i;
++static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh, DH **key_ptr,
++      BIGNUM **priv_key, CK_SESSION_HANDLE session);
 +
-+      for (i = 0; i < PK11_DIGEST_MAX; ++i)
-+              {
-+              pk11_get_digest(pflist, current_slot, digests[i].mech_type,
-+                  current_slot_n_digest, local_digest_nids, digests[i].id);
-+              }
++static int check_new_dh_key(PK11_SESSION *sp, DH *dh);
++#endif
++
++static int init_template_value(BIGNUM *bn, CK_VOID_PTR *pValue,
++      CK_ULONG *ulValueLen);
++static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn);
++
++/* Read mode string to be used for fopen() */
++#if SOLARIS_OPENSSL
++static char *read_mode_flags = "rF";
++#else
++static char *read_mode_flags = "r";
++#endif
++
++/*
++ * increment/create reference for an asymmetric key handle via active list
++ * manipulation. If active list operation fails, unlock (if locked), set error
++ * variable and jump to the specified label.
++ */
++#define       KEY_HANDLE_REFHOLD(key_handle, alg_type, unlock, var, label)    \
++      {                                                               \
++      if (pk11_active_add(key_handle, alg_type) < 0)                  \
++              {                                                       \
++              var = TRUE;                                             \
++              if (unlock)                                             \
++                      UNLOCK_OBJSTORE(alg_type);                      \
++              goto label;                                             \
++              }                                                       \
 +      }
 +
-+#ifdef        SOLARIS_HW_SLOT_SELECTION
 +/*
-+ * It would be great if we could use pkcs11_kernel directly since this library
-+ * offers hardware slots only. That's the easiest way to achieve the situation
-+ * where we use the hardware accelerators when present and OpenSSL native code
-+ * otherwise. That presumes the fact that OpenSSL native code is faster than the
-+ * code in the soft token. It's a logical assumption - Crypto Framework has some
-+ * inherent overhead so going there for the software implementation of a
-+ * mechanism should be logically slower in contrast to the OpenSSL native code,
-+ * presuming that both implementations are of similar speed. For example, the
-+ * soft token for AES is roughly three times slower than OpenSSL for 64 byte
-+ * blocks and still 20% slower for 8KB blocks. So, if we want to ship products
-+ * that use the PKCS#11 engine by default, we must somehow avoid that regression
-+ * on machines without hardware acceleration. That's why switching to the
-+ * pkcs11_kernel library seems like a very good idea.
-+ *
-+ * The problem is that OpenSSL built with SunStudio is roughly 2x slower for
-+ * asymmetric operations (RSA/DSA/DH) than the soft token built with the same
-+ * compiler. That means that if we switched to pkcs11_kernel from the libpkcs11
-+ * library, we would have had a performance regression on machines without
-+ * hardware acceleration for asymmetric operations for all applications that use
-+ * the PKCS#11 engine. There is one such application - Apache web server since
-+ * it's shipped configured to use the PKCS#11 engine by default. Having said
-+ * that, we can't switch to the pkcs11_kernel library now and have to come with
-+ * a solution that, on non-accelerated machines, uses the OpenSSL native code
-+ * for all symmetric ciphers and digests while it uses the soft token for
-+ * asymmetric operations.
-+ *
-+ * This is the idea: dlopen() pkcs11_kernel directly and find out what
-+ * mechanisms are there. We don't care about duplications (more slots can
-+ * support the same mechanism), we just want to know what mechanisms can be
-+ * possibly supported in hardware on that particular machine. As said before,
-+ * pkcs11_kernel will show you hardware providers only.
-+ *
-+ * Then, we rely on the fact that since we use libpkcs11 library we will find
-+ * the metaslot. When we go through the metaslot's mechanisms for symmetric
-+ * ciphers and digests, we check that any found mechanism is in the table
-+ * created using the pkcs11_kernel library. So, as a result we have two arrays
-+ * of mechanisms that were advertised as supported in hardware which was the
-+ * goal of that whole excercise. Thus, we can use libpkcs11 but avoid soft token
-+ * code for symmetric ciphers and digests. See pk11_choose_slots() for more
-+ * information.
++ * Find active list entry according to object handle and return pointer to the
++ * entry otherwise return NULL.
 + *
-+ * This is Solaris specific code, if SOLARIS_HW_SLOT_SELECTION is not defined
-+ * the code won't be used.
++ * This function presumes it is called with lock protecting the active list
++ * held.
 + */
-+#if defined(__sparcv9) || defined(__x86_64) || defined(__amd64)
-+static const char pkcs11_kernel[] = "/usr/lib/security/64/pkcs11_kernel.so.1";
-+#else
-+static const char pkcs11_kernel[] = "/usr/lib/security/pkcs11_kernel.so.1";
-+#endif
++static PK11_active *pk11_active_find(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
++      {
++      PK11_active *entry;
++
++      for (entry = active_list[type]; entry != NULL; entry = entry->next)
++              if (entry->h == h)
++                      return (entry);
++
++      return (NULL);
++      }
 +
 +/*
-+ * Check hardware capabilities of the machines. The output are two lists,
-+ * hw_cnids and hw_dnids, that contain hardware mechanisms found in all hardware
-+ * providers together. They are not sorted and may contain duplicate mechanisms.
++ * Search for an entry in the active list using PKCS#11 object handle as a
++ * search key and return refcnt of the found/created entry or -1 in case of
++ * failure.
++ *
++ * This function presumes it is called with lock protecting the active list
++ * held.
 + */
-+static int check_hw_mechanisms(void)
++int
++pk11_active_add(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
 +      {
-+      int i;
-+      CK_RV rv;
-+      void *handle;
-+      CK_C_GetFunctionList p;
-+      CK_TOKEN_INFO token_info;
-+      CK_ULONG ulSlotCount = 0;
-+      int n_cipher = 0, n_digest = 0;
-+      CK_FUNCTION_LIST_PTR pflist = NULL;
-+      CK_SLOT_ID_PTR pSlotList = NULL_PTR;
-+      int *tmp_hw_cnids = NULL, *tmp_hw_dnids = NULL;
-+      int hw_ctable_size, hw_dtable_size;
++      PK11_active *entry = NULL;
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: SOLARIS_HW_SLOT_SELECTION code running\n",
-+          PK11_DBG);
-+#endif
-+      if ((handle = dlopen(pkcs11_kernel, RTLD_LAZY)) == NULL)
++      if (h == CK_INVALID_HANDLE)
 +              {
-+              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
-+              goto err;
++              PK11err(PK11_F_ACTIVE_ADD, PK11_R_INVALID_HANDLE);
++              return (-1);
 +              }
 +
-+      if ((p = (CK_C_GetFunctionList)dlsym(handle,
-+          PK11_GET_FUNCTION_LIST)) == NULL)
++      /* search for entry in the active list */
++      if ((entry = pk11_active_find(h, type)) != NULL)
++              entry->refcnt++;
++      else
 +              {
-+              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
-+              goto err;
++              /* not found, create new entry and add it to the list */
++              entry = OPENSSL_malloc(sizeof (PK11_active));
++              if (entry == NULL)
++                      {
++                      PK11err(PK11_F_ACTIVE_ADD, PK11_R_MALLOC_FAILURE);
++                      return (-1);
++                      }
++              entry->h = h;
++              entry->refcnt = 1;
++              entry->prev = NULL;
++              entry->next = NULL;
++              /* connect the newly created entry to the list */
++              if (active_list[type] == NULL)
++                      active_list[type] = entry;
++              else /* make the entry first in the list */
++                      {
++                      entry->next = active_list[type];
++                      active_list[type]->prev = entry;
++                      active_list[type] = entry;
++                      }
 +              }
 +
-+      /* get the full function list from the loaded library */
-+      if (p(&pflist) != CKR_OK)
-+              {
-+              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
-+              goto err;
-+              }
++      return (entry->refcnt);
++      }
 +
-+      rv = pflist->C_Initialize(NULL_PTR);
-+      if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
++/*
++ * Remove active list entry from the list and free it.
++ *
++ * This function presumes it is called with lock protecting the active list
++ * held.
++ */
++void
++pk11_active_remove(PK11_active *entry, PK11_OPTYPE type)
++      {
++      PK11_active *prev_entry;
++
++      /* remove the entry from the list and free it */
++      if ((prev_entry = entry->prev) != NULL)
 +              {
-+              PK11err_add_data(PK11_F_CHECK_HW_MECHANISMS,
-+                  PK11_R_INITIALIZE, rv);
-+              goto err;
++              prev_entry->next = entry->next;
++              if (entry->next != NULL)
++                      entry->next->prev = prev_entry;
 +              }
-+
-+      if (pflist->C_GetSlotList(0, NULL_PTR, &ulSlotCount) != CKR_OK)
++      else
 +              {
-+              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
-+              goto err;
++              active_list[type] = entry->next;
++              /* we were the first but not the only one */
++              if (entry->next != NULL)
++                      entry->next->prev = NULL;
 +              }
 +
-+      /* no slots, set the hw mechanism tables as empty */
-+      if (ulSlotCount == 0)
-+              {
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: no hardware mechanisms found\n", PK11_DBG);
-+#endif
-+              hw_cnids = OPENSSL_malloc(sizeof (int));
-+              hw_dnids = OPENSSL_malloc(sizeof (int));
-+              if (hw_cnids == NULL || hw_dnids == NULL)
-+                      {
-+                      PK11err(PK11_F_CHECK_HW_MECHANISMS,
-+                          PK11_R_MALLOC_FAILURE);
-+                      return (0);
-+                      }
-+              /* this means empty tables */
-+              hw_cnids[0] = NID_undef;
-+              hw_dnids[0] = NID_undef;
-+              return (1);
-+              }
++      /* sanitization */
++      entry->h = CK_INVALID_HANDLE;
++      entry->prev = NULL;
++      entry->next = NULL;
++      OPENSSL_free(entry);
++      }
 +
-+      pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
-+      if (pSlotList == NULL)
++/* Free all entries from the active list. */
++void
++pk11_free_active_list(PK11_OPTYPE type)
++      {
++      PK11_active *entry;
++
++      /* only for asymmetric types since only they have C_Find* locks. */
++      switch (type)
 +              {
-+              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
-+              goto err;
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++                      break;
++              default:
++                      return;
 +              }
 +
-+      /* Get the slot list for processing */
-+      if (pflist->C_GetSlotList(0, pSlotList, &ulSlotCount) != CKR_OK)
++      /* see find_lock array definition for more info on object locking */
++      LOCK_OBJSTORE(type);
++      while ((entry = active_list[type]) != NULL)
++              pk11_active_remove(entry, type);
++      UNLOCK_OBJSTORE(type);
++      }
++
++/*
++ * Search for active list entry associated with given PKCS#11 object handle,
++ * decrement its refcnt and if it drops to 0, disconnect the entry and free it.
++ *
++ * Return 1 if the PKCS#11 object associated with the entry has no references,
++ * return 0 if there is at least one reference, -1 on error.
++ *
++ * This function presumes it is called with lock protecting the active list
++ * held.
++ */
++int
++pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
++      {
++      PK11_active *entry = NULL;
++
++      if ((entry = pk11_active_find(h, type)) == NULL)
 +              {
-+              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
-+              goto err;
++              PK11err(PK11_F_ACTIVE_DELETE, PK11_R_INVALID_HANDLE);
++              return (-1);
 +              }
 +
-+      /*
-+       * We don't care about duplicit mechanisms in multiple slots and also
-+       * reserve one slot for the terminal NID_undef which we use to stop the
-+       * search.
-+       */
-+      hw_ctable_size = ulSlotCount * PK11_CIPHER_MAX + 1;
-+      hw_dtable_size = ulSlotCount * PK11_DIGEST_MAX + 1;
-+      tmp_hw_cnids = OPENSSL_malloc(hw_ctable_size * sizeof (int));
-+      tmp_hw_dnids = OPENSSL_malloc(hw_dtable_size * sizeof (int));
-+      if (tmp_hw_cnids == NULL || tmp_hw_dnids == NULL)
++      OPENSSL_assert(entry->refcnt > 0);
++      entry->refcnt--;
++      if (entry->refcnt == 0)
 +              {
-+              PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
-+              goto err;
++              pk11_active_remove(entry, type);
++              return (1);
 +              }
 +
-+      /*
-+       * Do not use memset since we should not rely on the fact that NID_undef
-+       * is zero now.
-+       */
-+      for (i = 0; i < hw_ctable_size; ++i)
-+              tmp_hw_cnids[i] = NID_undef;
-+      for (i = 0; i < hw_dtable_size; ++i)
-+              tmp_hw_dnids[i] = NID_undef;
-+
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: provider: %s\n", PK11_DBG, pkcs11_kernel);
-+      fprintf(stderr, "%s: found %d hardware slots\n", PK11_DBG, ulSlotCount);
-+      fprintf(stderr, "%s: now looking for mechs supported in hw\n",
-+          PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
++      return (0);
++      }
 +
-+      for (i = 0; i < ulSlotCount; i++)
-+              {
-+              if (pflist->C_GetTokenInfo(pSlotList[i], &token_info) != CKR_OK)
-+                      continue;
++#ifndef OPENSSL_NO_RSA
++/* Our internal RSA_METHOD that we provide pointers to */
++static RSA_METHOD pk11_rsa =
++      {
++      "PKCS#11 RSA method",
++      pk11_RSA_public_encrypt,                /* rsa_pub_encrypt */
++      pk11_RSA_public_decrypt,                /* rsa_pub_decrypt */
++      pk11_RSA_private_encrypt,               /* rsa_priv_encrypt */
++      pk11_RSA_private_decrypt,               /* rsa_priv_decrypt */
++      NULL,                                   /* rsa_mod_exp */
++      NULL,                                   /* bn_mod_exp */
++      pk11_RSA_init,                          /* init */
++      pk11_RSA_finish,                        /* finish */
++      RSA_FLAG_SIGN_VER,                      /* flags */
++      NULL,                                   /* app_data */
++      pk11_RSA_sign,                          /* rsa_sign */
++      pk11_RSA_verify                         /* rsa_verify */
++      };
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
-+#endif        /* DEBUG_SLOT_SELECTION */
++RSA_METHOD *
++PK11_RSA(void)
++      {
++      return (&pk11_rsa);
++      }
++#endif
 +
-+              /*
-+               * We are filling the hw mech tables here. Global tables are
-+               * still NULL so all mechanisms are put into tmp tables.
-+               */
-+              pk11_find_symmetric_ciphers(pflist, pSlotList[i],
-+                  &n_cipher, tmp_hw_cnids);
-+              pk11_find_digests(pflist, pSlotList[i],
-+                  &n_digest, tmp_hw_dnids);
-+              }
++#ifndef OPENSSL_NO_DSA
++/* Our internal DSA_METHOD that we provide pointers to */
++static DSA_METHOD pk11_dsa =
++      {
++      "PKCS#11 DSA method",
++      pk11_dsa_do_sign,       /* dsa_do_sign */
++      NULL,                   /* dsa_sign_setup */
++      pk11_dsa_do_verify,     /* dsa_do_verify */
++      NULL,                   /* dsa_mod_exp */
++      NULL,                   /* bn_mod_exp */
++      pk11_DSA_init,          /* init */
++      pk11_DSA_finish,        /* finish */
++      0,                      /* flags */
++      NULL                    /* app_data */
++      };
 +
-+      /*
-+       * Since we are part of a library (libcrypto.so), calling this function
-+       * may have side-effects. Also, C_Finalize() is triggered by
-+       * dlclose(3C).
-+       */
-+#if 0
-+      pflist->C_Finalize(NULL);
++DSA_METHOD *
++PK11_DSA(void)
++      {
++      return (&pk11_dsa);
++      }
 +#endif
-+      OPENSSL_free(pSlotList);
-+      (void) dlclose(handle);
-+      hw_cnids = tmp_hw_cnids;
-+      hw_dnids = tmp_hw_dnids;
 +
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, "%s: hw mechs check complete\n", PK11_DBG);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+      return (1);
++#ifndef OPENSSL_NO_DH
++/*
++ * PKCS #11 V2.20, section 11.2 specifies that the number of bytes needed for
++ * output buffer may somewhat exceed the precise number of bytes needed, but
++ * should not exceed it by a large amount. That may be caused, for example, by
++ * rounding it up to multiple of X in the underlying bignum library. 8 should be
++ * enough.
++ */
++#define       DH_BUF_RESERVE  8
 +
-+err:
-+      if (pSlotList != NULL)
-+              OPENSSL_free(pSlotList);
-+      if (tmp_hw_cnids != NULL)
-+              OPENSSL_free(tmp_hw_cnids);
-+      if (tmp_hw_dnids != NULL)
-+              OPENSSL_free(tmp_hw_dnids);
++/* Our internal DH_METHOD that we provide pointers to */
++static DH_METHOD pk11_dh =
++      {
++      "PKCS#11 DH method",
++      pk11_DH_generate_key,   /* generate_key */
++      pk11_DH_compute_key,    /* compute_key */
++      NULL,                   /* bn_mod_exp */
++      pk11_DH_init,           /* init */
++      pk11_DH_finish,         /* finish */
++      0,                      /* flags */
++      NULL,                   /* app_data */
++      NULL                    /* generate_params */
++      };
 +
-+      return (0);
++DH_METHOD *
++PK11_DH(void)
++      {
++      return (&pk11_dh);
 +      }
++#endif
++
++/* Size of an SSL signature: MD5+SHA1 */
++#define       SSL_SIG_LENGTH          36
 +
++/* Lengths of DSA data and signature */
++#define       DSA_DATA_LEN            20
++#define       DSA_SIGNATURE_LEN       40
++
++static CK_BBOOL true = TRUE;
++static CK_BBOOL false = FALSE;
++
++#ifndef OPENSSL_NO_RSA
 +/*
-+ * Check presence of a NID in the table of NIDs. The table may be NULL (i.e.,
-+ * non-existent).
++ * Similiar to OpenSSL to take advantage of the paddings. The goal is to
++ * support all paddings in this engine although PK11 library does not
++ * support all the paddings used in OpenSSL.
++ * The input errors should have been checked in the padding functions.
 + */
-+static int nid_in_table(int nid, int *nid_table)
++static int pk11_RSA_public_encrypt(int flen, const unsigned char *from,
++              unsigned char *to, RSA *rsa, int padding)
 +      {
-+      int i = 0;
++      int i, num = 0, r = -1;
++      unsigned char *buf = NULL;
 +
-+      /*
-+       * a special case. NULL means that we are initializing a new
-+       * table.
-+       */
-+      if (nid_table == NULL)
-+              return (1);
++      num = BN_num_bytes(rsa->n);
++      if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
++              {
++              RSAerr(PK11_F_RSA_PUB_ENC, PK11_R_MALLOC_FAILURE);
++              goto err;
++              }
 +
-+      /*
-+       * the table is never full, there is always at least one
-+       * NID_undef.
-+       */
-+      while (nid_table[i] != NID_undef)
++      switch (padding)
 +              {
-+              if (nid_table[i++] == nid)
-+                      {
-+#ifdef        DEBUG_SLOT_SELECTION
-+      fprintf(stderr, " (NID %d in hw table, idx %d)", nid, i);
-+#endif        /* DEBUG_SLOT_SELECTION */
-+                      return (1);
-+                      }
++      case RSA_PKCS1_PADDING:
++              i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
++              break;
++#ifndef OPENSSL_NO_SHA
++      case RSA_PKCS1_OAEP_PADDING:
++              i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
++              break;
++#endif
++      case RSA_SSLV23_PADDING:
++              i = RSA_padding_add_SSLv23(buf, num, from, flen);
++              break;
++      case RSA_NO_PADDING:
++              i = RSA_padding_add_none(buf, num, from, flen);
++              break;
++      default:
++              RSAerr(PK11_F_RSA_PUB_ENC, PK11_R_UNKNOWN_PADDING_TYPE);
++              goto err;
 +              }
++      if (i <= 0) goto err;
 +
-+      return (0);
++      /* PK11 functions are called here */
++      r = pk11_RSA_public_encrypt_low(num, buf, to, rsa);
++err:
++      if (buf != NULL)
++              {
++              OPENSSL_cleanse(buf, num);
++              OPENSSL_free(buf);
++              }
++      return (r);
 +      }
-+#endif        /* SOLARIS_HW_SLOT_SELECTION */
 +
-+#endif        /* OPENSSL_NO_HW_PK11 */
-+#endif        /* OPENSSL_NO_HW */
-Index: openssl/crypto/engine/hw_pk11_err.c
-diff -u /dev/null openssl/crypto/engine/hw_pk11_err.c:1.4
---- /dev/null  Mon Oct  5 11:08:14 2009
-+++ openssl/crypto/engine/hw_pk11_err.c        Wed Dec 17 16:14:26 2008
-@@ -0,0 +1,259 @@
-+/*
-+ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
-+ * Use is subject to license terms.
-+ */
 +
-+/* crypto/engine/hw_pk11_err.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).
-+ *
++ * Similar to Openssl to take advantage of the paddings. The input errors
++ * should be catched in the padding functions
 + */
++static int pk11_RSA_private_encrypt(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa, int padding)
++      {
++      int i, num = 0, r = -1;
++      unsigned char *buf = NULL;
 +
-+#include <stdio.h>
-+#include <openssl/err.h>
-+#include "hw_pk11_err.h"
++      num = BN_num_bytes(rsa->n);
++      if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
++              {
++              RSAerr(PK11_F_RSA_PRIV_ENC, PK11_R_MALLOC_FAILURE);
++              goto err;
++              }
 +
-+/* BEGIN ERROR CODES */
-+#ifndef OPENSSL_NO_ERR
-+static ERR_STRING_DATA pk11_str_functs[]=
-+{
-+{ ERR_PACK(0, PK11_F_INIT, 0),                        "PK11_INIT"},
-+{ ERR_PACK(0, PK11_F_FINISH, 0),              "PK11_FINISH"},
-+{ ERR_PACK(0, PK11_F_DESTROY, 0),             "PK11_DESTROY"},
-+{ ERR_PACK(0, PK11_F_CTRL, 0),                        "PK11_CTRL"},
-+{ ERR_PACK(0, PK11_F_RSA_INIT, 0),            "PK11_RSA_INIT"},
-+{ ERR_PACK(0, PK11_F_RSA_FINISH, 0),          "PK11_RSA_FINISH"},
-+{ ERR_PACK(0, PK11_F_GET_PUB_RSA_KEY, 0),     "PK11_GET_PUB_RSA_KEY"},
-+{ ERR_PACK(0, PK11_F_GET_PRIV_RSA_KEY, 0),    "PK11_GET_PRIV_RSA_KEY"},
-+{ ERR_PACK(0, PK11_F_RSA_GEN_KEY, 0),         "PK11_RSA_GEN_KEY"},
-+{ ERR_PACK(0, PK11_F_RSA_PUB_ENC, 0),         "PK11_RSA_PUB_ENC"},
-+{ ERR_PACK(0, PK11_F_RSA_PRIV_ENC, 0),                "PK11_RSA_PRIV_ENC"},
-+{ ERR_PACK(0, PK11_F_RSA_PUB_DEC, 0),         "PK11_RSA_PUB_DEC"},
-+{ ERR_PACK(0, PK11_F_RSA_PRIV_DEC, 0),                "PK11_RSA_PRIV_DEC"},
-+{ ERR_PACK(0, PK11_F_RSA_SIGN, 0),            "PK11_RSA_SIGN"},
-+{ ERR_PACK(0, PK11_F_RSA_VERIFY, 0),          "PK11_RSA_VERIFY"},
-+{ ERR_PACK(0, PK11_F_RAND_ADD, 0),            "PK11_RAND_ADD"},
-+{ ERR_PACK(0, PK11_F_RAND_BYTES, 0),          "PK11_RAND_BYTES"},
-+{ ERR_PACK(0, PK11_F_GET_SESSION, 0),         "PK11_GET_SESSION"},
-+{ ERR_PACK(0, PK11_F_FREE_SESSION, 0),                "PK11_FREE_SESSION"},
-+{ ERR_PACK(0, PK11_F_LOAD_PUBKEY, 0),         "PK11_LOAD_PUBKEY"},
-+{ ERR_PACK(0, PK11_F_LOAD_PRIVKEY, 0),                "PK11_LOAD_PRIV_KEY"},
-+{ ERR_PACK(0, PK11_F_RSA_PUB_ENC_LOW, 0),     "PK11_RSA_PUB_ENC_LOW"},
-+{ ERR_PACK(0, PK11_F_RSA_PRIV_ENC_LOW, 0),    "PK11_RSA_PRIV_ENC_LOW"},
-+{ ERR_PACK(0, PK11_F_RSA_PUB_DEC_LOW, 0),     "PK11_RSA_PUB_DEC_LOW"},
-+{ ERR_PACK(0, PK11_F_RSA_PRIV_DEC_LOW, 0),    "PK11_RSA_PRIV_DEC_LOW"},
-+{ ERR_PACK(0, PK11_F_DSA_SIGN, 0),            "PK11_DSA_SIGN"},
-+{ ERR_PACK(0, PK11_F_DSA_VERIFY, 0),          "PK11_DSA_VERIFY"},
-+{ ERR_PACK(0, PK11_F_DSA_INIT, 0),            "PK11_DSA_INIT"},
-+{ ERR_PACK(0, PK11_F_DSA_FINISH, 0),          "PK11_DSA_FINISH"},
-+{ ERR_PACK(0, PK11_F_GET_PUB_DSA_KEY, 0),     "PK11_GET_PUB_DSA_KEY"},
-+{ ERR_PACK(0, PK11_F_GET_PRIV_DSA_KEY, 0),    "PK11_GET_PRIV_DSA_KEY"},
-+{ ERR_PACK(0, PK11_F_DH_INIT, 0),             "PK11_DH_INIT"},
-+{ ERR_PACK(0, PK11_F_DH_FINISH, 0),           "PK11_DH_FINISH"},
-+{ ERR_PACK(0, PK11_F_MOD_EXP_DH, 0),          "PK11_MOD_EXP_DH"},
-+{ ERR_PACK(0, PK11_F_GET_DH_KEY, 0),          "PK11_GET_DH_KEY"},
-+{ ERR_PACK(0, PK11_F_FREE_ALL_SESSIONS, 0),   "PK11_FREE_ALL_SESSIONS"},
-+{ ERR_PACK(0, PK11_F_SETUP_SESSION, 0),               "PK11_SETUP_SESSION"},
-+{ ERR_PACK(0, PK11_F_DESTROY_OBJECT, 0),      "PK11_DESTROY_OBJECT"},
-+{ ERR_PACK(0, PK11_F_CIPHER_INIT, 0),         "PK11_CIPHER_INIT"},
-+{ ERR_PACK(0, PK11_F_CIPHER_DO_CIPHER, 0),    "PK11_CIPHER_DO_CIPHER"},
-+{ ERR_PACK(0, PK11_F_GET_CIPHER_KEY, 0),      "PK11_GET_CIPHER_KEY"},
-+{ ERR_PACK(0, PK11_F_DIGEST_INIT, 0),         "PK11_DIGEST_INIT"},
-+{ ERR_PACK(0, PK11_F_DIGEST_UPDATE, 0),               "PK11_DIGEST_UPDATE"},
-+{ ERR_PACK(0, PK11_F_DIGEST_FINAL, 0),                "PK11_DIGEST_FINAL"},
-+{ ERR_PACK(0, PK11_F_CHOOSE_SLOT, 0),         "PK11_CHOOSE_SLOT"},
-+{ ERR_PACK(0, PK11_F_CIPHER_FINAL, 0),                "PK11_CIPHER_FINAL"},
-+{ ERR_PACK(0, PK11_F_LIBRARY_INIT, 0),                "PK11_LIBRARY_INIT"},
-+{ ERR_PACK(0, PK11_F_LOAD, 0),                        "ENGINE_LOAD_PK11"},
-+{ ERR_PACK(0, PK11_F_DH_GEN_KEY, 0),          "PK11_DH_GEN_KEY"},
-+{ ERR_PACK(0, PK11_F_DH_COMP_KEY, 0),         "PK11_DH_COMP_KEY"},
-+{ ERR_PACK(0, PK11_F_DIGEST_COPY, 0),         "PK11_DIGEST_COPY"},
-+{ ERR_PACK(0, PK11_F_CIPHER_CLEANUP, 0),      "PK11_CIPHER_CLEANUP"},
-+{ ERR_PACK(0, PK11_F_ACTIVE_ADD, 0),          "PK11_ACTIVE_ADD"},
-+{ ERR_PACK(0, PK11_F_ACTIVE_DELETE, 0),               "PK11_ACTIVE_DELETE"},
-+{ ERR_PACK(0, PK11_F_CHECK_HW_MECHANISMS, 0), "PK11_CHECK_HW_MECHANISMS"},
-+{ ERR_PACK(0, PK11_F_INIT_SYMMETRIC, 0),      "PK11_INIT_SYMMETRIC"},
-+{ ERR_PACK(0, PK11_F_ADD_AES_CTR_NIDS, 0),    "PK11_ADD_AES_CTR_NIDS"},
-+{ 0, NULL}
-+};
++      switch (padding)
++              {
++      case RSA_PKCS1_PADDING:
++              i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
++              break;
++      case RSA_NO_PADDING:
++              i = RSA_padding_add_none(buf, num, from, flen);
++              break;
++      case RSA_SSLV23_PADDING:
++      default:
++              RSAerr(PK11_F_RSA_PRIV_ENC, PK11_R_UNKNOWN_PADDING_TYPE);
++              goto err;
++              }
++      if (i <= 0) goto err;
 +
-+static ERR_STRING_DATA pk11_str_reasons[]=
-+{
-+{ PK11_R_ALREADY_LOADED,              "PKCS#11 DSO already loaded"},
-+{ PK11_R_DSO_FAILURE,                 "unable to load PKCS#11 DSO"},
-+{ PK11_R_NOT_LOADED,                  "PKCS#11 DSO not loaded"},
-+{ PK11_R_PASSED_NULL_PARAMETER,               "null parameter passed"},
-+{ PK11_R_COMMAND_NOT_IMPLEMENTED,     "command not implemented"},
-+{ PK11_R_INITIALIZE,                  "C_Initialize failed"},
-+{ PK11_R_FINALIZE,                    "C_Finalize failed"},
-+{ PK11_R_GETINFO,                     "C_GetInfo faile"},
-+{ PK11_R_GETSLOTLIST,                 "C_GetSlotList failed"},
-+{ PK11_R_NO_MODULUS_OR_NO_EXPONENT,   "no modulus or no exponent"},
-+{ PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID,       "attr sensitive or invalid"},
-+{ PK11_R_GETATTRIBUTVALUE,            "C_GetAttributeValue failed"},
-+{ PK11_R_NO_MODULUS,                  "no modulus"},
-+{ PK11_R_NO_EXPONENT,                 "no exponent"},
-+{ PK11_R_FINDOBJECTSINIT,             "C_FindObjectsInit failed"},
-+{ PK11_R_FINDOBJECTS,                 "C_FindObjects failed"},
-+{ PK11_R_FINDOBJECTSFINAL,            "C_FindObjectsFinal failed"},
-+{ PK11_R_CREATEOBJECT,                        "C_CreateObject failed"},
-+{ PK11_R_DESTROYOBJECT,                       "C_DestroyObject failed"},
-+{ PK11_R_OPENSESSION,                 "C_OpenSession failed"},
-+{ PK11_R_CLOSESESSION,                        "C_CloseSession failed"},
-+{ PK11_R_ENCRYPTINIT,                 "C_EncryptInit failed"},
-+{ PK11_R_ENCRYPT,                     "C_Encrypt failed"},
-+{ PK11_R_SIGNINIT,                    "C_SignInit failed"},
-+{ PK11_R_SIGN,                                "C_Sign failed"},
-+{ PK11_R_DECRYPTINIT,                 "C_DecryptInit failed"},
-+{ PK11_R_DECRYPT,                     "C_Decrypt failed"},
-+{ PK11_R_VERIFYINIT,                  "C_VerifyRecover failed"},
-+{ PK11_R_VERIFY,                      "C_Verify failed"},
-+{ PK11_R_VERIFYRECOVERINIT,           "C_VerifyRecoverInit failed"},
-+{ PK11_R_VERIFYRECOVER,                       "C_VerifyRecover failed"},
-+{ PK11_R_GEN_KEY,                     "C_GenerateKeyPair failed"},
-+{ PK11_R_SEEDRANDOM,                  "C_SeedRandom failed"},
-+{ PK11_R_GENERATERANDOM,              "C_GenerateRandom failed"},
-+{ PK11_R_INVALID_MESSAGE_LENGTH,      "invalid message length"},
-+{ PK11_R_UNKNOWN_ALGORITHM_TYPE,      "unknown algorithm type"},
-+{ PK11_R_UNKNOWN_ASN1_OBJECT_ID,      "unknown asn1 onject id"},
-+{ PK11_R_UNKNOWN_PADDING_TYPE,                "unknown padding type"},
-+{ PK11_R_PADDING_CHECK_FAILED,                "padding check failed"},
-+{ PK11_R_DIGEST_TOO_BIG,              "digest too big"},
-+{ PK11_R_MALLOC_FAILURE,              "malloc failure"},
-+{ PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED,        "ctl command not implemented"},
-+{ PK11_R_DATA_GREATER_THAN_MOD_LEN,   "data is bigger than mod"},
-+{ PK11_R_DATA_TOO_LARGE_FOR_MODULUS,  "data is too larger for mod"},
-+{ PK11_R_MISSING_KEY_COMPONENT,               "a dsa component is missing"},
-+{ PK11_R_INVALID_SIGNATURE_LENGTH,    "invalid signature length"},
-+{ PK11_R_INVALID_DSA_SIGNATURE_R,     "missing r in dsa verify"},
-+{ PK11_R_INVALID_DSA_SIGNATURE_S,     "missing s in dsa verify"},
-+{ PK11_R_INCONSISTENT_KEY,            "inconsistent key type"},
-+{ PK11_R_ENCRYPTUPDATE,                       "C_EncryptUpdate failed"},
-+{ PK11_R_DECRYPTUPDATE,                       "C_DecryptUpdate failed"},
-+{ PK11_R_DIGESTINIT,                  "C_DigestInit failed"},
-+{ PK11_R_DIGESTUPDATE,                        "C_DigestUpdate failed"},
-+{ PK11_R_DIGESTFINAL,                 "C_DigestFinal failed"},
-+{ PK11_R_ENCRYPTFINAL,                        "C_EncryptFinal failed"},
-+{ PK11_R_DECRYPTFINAL,                        "C_DecryptFinal failed"},
-+{ PK11_R_NO_PRNG_SUPPORT,             "Slot does not support PRNG"},
-+{ PK11_R_GETTOKENINFO,                        "C_GetTokenInfo failed"},
-+{ PK11_R_DERIVEKEY,                   "C_DeriveKey failed"},
-+{ PK11_R_GET_OPERATION_STATE,         "C_GetOperationState failed"},
-+{ PK11_R_SET_OPERATION_STATE,         "C_SetOperationState failed"},
-+{ PK11_R_INVALID_PIN,                 "invalid PIN"},
-+{ PK11_R_TOO_MANY_OBJECTS,            "too many objects"},
-+{ PK11_R_OBJECT_NOT_FOUND,            "object not found"},
-+{ PK11_R_INVALID_HANDLE,              "invalid PKCS#11 object handle"},
-+{ PK11_R_KEY_OR_IV_LEN_PROBLEM,               "IV or key length incorrect"},
-+{ PK11_R_INVALID_OPERATION_TYPE,      "invalid operation type"},
-+{ PK11_R_ADD_NID_FAILED,              "failed to add NID" },
-+{ 0,  NULL}
-+};
-+#endif        /* OPENSSL_NO_ERR */
-+
-+static int pk11_lib_error_code = 0;
-+static int pk11_error_init = 1;
++      /* PK11 functions are called here */
++      r = pk11_RSA_private_encrypt_low(num, buf, to, rsa);
++err:
++      if (buf != NULL)
++              {
++              OPENSSL_cleanse(buf, num);
++              OPENSSL_free(buf);
++              }
++      return (r);
++      }
 +
-+static void
-+ERR_load_pk11_strings(void)
++/* Similar to OpenSSL code. Input errors are also checked here */
++static int pk11_RSA_private_decrypt(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa, int padding)
 +      {
-+      if (pk11_lib_error_code == 0)
-+              pk11_lib_error_code = ERR_get_next_error_library();
++      BIGNUM f;
++      int j, num = 0, r = -1;
++      unsigned char *p;
++      unsigned char *buf = NULL;
 +
-+      if (pk11_error_init)
++      BN_init(&f);
++
++      num = BN_num_bytes(rsa->n);
++
++      if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
 +              {
-+              pk11_error_init = 0;
-+#ifndef OPENSSL_NO_ERR
-+              ERR_load_strings(pk11_lib_error_code, pk11_str_functs);
-+              ERR_load_strings(pk11_lib_error_code, pk11_str_reasons);
-+#endif
++              RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_MALLOC_FAILURE);
++              goto err;
 +              }
-+}
 +
-+static void
-+ERR_unload_pk11_strings(void)
-+      {
-+      if (pk11_error_init == 0)
++      /*
++       * This check was for equality but PGP does evil things
++       * and chops off the top '0' bytes
++       */
++      if (flen > num)
 +              {
-+#ifndef OPENSSL_NO_ERR
-+              ERR_unload_strings(pk11_lib_error_code, pk11_str_functs);
-+              ERR_unload_strings(pk11_lib_error_code, pk11_str_reasons);
-+#endif
-+              pk11_error_init = 1;
++              RSAerr(PK11_F_RSA_PRIV_DEC,
++                      PK11_R_DATA_GREATER_THAN_MOD_LEN);
++              goto err;
 +              }
-+}
 +
-+void
-+ERR_pk11_error(int function, int reason, char *file, int line)
-+{
-+      if (pk11_lib_error_code == 0)
-+              pk11_lib_error_code = ERR_get_next_error_library();
-+      ERR_PUT_error(pk11_lib_error_code, function, reason, file, line);
-+}
++      /* make data into a big number */
++      if (BN_bin2bn(from, (int)flen, &f) == NULL)
++              goto err;
 +
-+void
-+PK11err_add_data(int function, int reason, CK_RV rv)
-+{
-+      char tmp_buf[20];
++      if (BN_ucmp(&f, rsa->n) >= 0)
++              {
++              RSAerr(PK11_F_RSA_PRIV_DEC,
++                      PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
++              goto err;
++              }
 +
-+      PK11err(function, reason);
-+      (void) BIO_snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
-+      ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
-+}
-Index: openssl/crypto/engine/hw_pk11_err.h
-diff -u /dev/null openssl/crypto/engine/hw_pk11_err.h:1.9
---- /dev/null  Mon Oct  5 11:08:14 2009
-+++ openssl/crypto/engine/hw_pk11_err.h        Wed Dec 17 15:01:45 2008
-@@ -0,0 +1,402 @@
-+/*
-+ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
-+ * Use is subject to license terms.
-+ */
++      /* PK11 functions are called here */
++      r = pk11_RSA_private_decrypt_low(flen, from, buf, rsa);
 +
-+/* crypto/engine/hw_pk11_err.h */
-+/*
-+ * 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).
-+ *
-+ */
++      /*
++       * PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
++       * Needs to skip these 0's paddings here.
++       */
++      for (j = 0; j < r; j++)
++              if (buf[j] != 0)
++                      break;
 +
-+#ifndef       HW_PK11_ERR_H
-+#define       HW_PK11_ERR_H
++      p = buf + j;
++      j = r - j;  /* j is only used with no-padding mode */
 +
-+void ERR_pk11_error(int function, int reason, char *file, int line);
-+void PK11err_add_data(int function, int reason, CK_RV rv);
-+#define       PK11err(f, r)   ERR_pk11_error((f), (r), __FILE__, __LINE__)
++      switch (padding)
++              {
++      case RSA_PKCS1_PADDING:
++              r = RSA_padding_check_PKCS1_type_2(to, num, p, j, num);
++              break;
++#ifndef OPENSSL_NO_SHA
++      case RSA_PKCS1_OAEP_PADDING:
++              r = RSA_padding_check_PKCS1_OAEP(to, num, p, j, num, NULL, 0);
++              break;
++#endif
++      case RSA_SSLV23_PADDING:
++              r = RSA_padding_check_SSLv23(to, num, p, j, num);
++              break;
++      case RSA_NO_PADDING:
++              r = RSA_padding_check_none(to, num, p, j, num);
++              break;
++      default:
++              RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_UNKNOWN_PADDING_TYPE);
++              goto err;
++              }
++      if (r < 0)
++              RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_PADDING_CHECK_FAILED);
 +
-+/* Error codes for the PK11 functions. */
++err:
++      BN_clear_free(&f);
++      if (buf != NULL)
++              {
++              OPENSSL_cleanse(buf, num);
++              OPENSSL_free(buf);
++              }
++      return (r);
++      }
 +
-+/* Function codes. */
++/* Similar to OpenSSL code. Input errors are also checked here */
++static int pk11_RSA_public_decrypt(int flen, const unsigned char *from,
++      unsigned char *to, RSA *rsa, int padding)
++      {
++      BIGNUM f;
++      int i, num = 0, r = -1;
++      unsigned char *p;
++      unsigned char *buf = NULL;
 +
-+#define       PK11_F_INIT                             100
-+#define       PK11_F_FINISH                           101
-+#define       PK11_F_DESTROY                          102
-+#define       PK11_F_CTRL                             103
-+#define       PK11_F_RSA_INIT                         104
-+#define       PK11_F_RSA_FINISH                       105
-+#define       PK11_F_GET_PUB_RSA_KEY                  106
-+#define       PK11_F_GET_PRIV_RSA_KEY                 107
-+#define       PK11_F_RSA_GEN_KEY                      108
-+#define       PK11_F_RSA_PUB_ENC                      109
-+#define       PK11_F_RSA_PRIV_ENC                     110
-+#define       PK11_F_RSA_PUB_DEC                      111
-+#define       PK11_F_RSA_PRIV_DEC                     112
-+#define       PK11_F_RSA_SIGN                         113
-+#define       PK11_F_RSA_VERIFY                       114
-+#define       PK11_F_RAND_ADD                         115
-+#define       PK11_F_RAND_BYTES                       116
-+#define       PK11_F_GET_SESSION                      117
-+#define       PK11_F_FREE_SESSION                     118
-+#define       PK11_F_LOAD_PUBKEY                      119
-+#define       PK11_F_LOAD_PRIVKEY                     120
-+#define       PK11_F_RSA_PUB_ENC_LOW                  121
-+#define       PK11_F_RSA_PRIV_ENC_LOW                 122
-+#define       PK11_F_RSA_PUB_DEC_LOW                  123
-+#define       PK11_F_RSA_PRIV_DEC_LOW                 124
-+#define       PK11_F_DSA_SIGN                         125
-+#define       PK11_F_DSA_VERIFY                       126
-+#define       PK11_F_DSA_INIT                         127
-+#define       PK11_F_DSA_FINISH                       128
-+#define       PK11_F_GET_PUB_DSA_KEY                  129
-+#define       PK11_F_GET_PRIV_DSA_KEY                 130
-+#define       PK11_F_DH_INIT                          131
-+#define       PK11_F_DH_FINISH                        132
-+#define       PK11_F_MOD_EXP_DH                       133
-+#define       PK11_F_GET_DH_KEY                       134
-+#define       PK11_F_FREE_ALL_SESSIONS                135
-+#define       PK11_F_SETUP_SESSION                    136
-+#define       PK11_F_DESTROY_OBJECT                   137
-+#define       PK11_F_CIPHER_INIT                      138
-+#define       PK11_F_CIPHER_DO_CIPHER                 139
-+#define       PK11_F_GET_CIPHER_KEY                   140
-+#define       PK11_F_DIGEST_INIT                      141
-+#define       PK11_F_DIGEST_UPDATE                    142
-+#define       PK11_F_DIGEST_FINAL                     143
-+#define       PK11_F_CHOOSE_SLOT                      144
-+#define       PK11_F_CIPHER_FINAL                     145
-+#define       PK11_F_LIBRARY_INIT                     146
-+#define       PK11_F_LOAD                             147
-+#define       PK11_F_DH_GEN_KEY                       148
-+#define       PK11_F_DH_COMP_KEY                      149
-+#define       PK11_F_DIGEST_COPY                      150
-+#define       PK11_F_CIPHER_CLEANUP                   151
-+#define       PK11_F_ACTIVE_ADD                       152
-+#define       PK11_F_ACTIVE_DELETE                    153
-+#define       PK11_F_CHECK_HW_MECHANISMS              154
-+#define       PK11_F_INIT_SYMMETRIC                   155
-+#define       PK11_F_ADD_AES_CTR_NIDS                 156
-+#define       PK11_F_INIT_ALL_LOCKS                   157
-+#define       PK11_F_RETURN_SESSION                   158
++      BN_init(&f);
++      num = BN_num_bytes(rsa->n);
++      buf = (unsigned char *)OPENSSL_malloc(num);
++      if (buf == NULL)
++              {
++              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_MALLOC_FAILURE);
++              goto err;
++              }
++
++      /*
++       * This check was for equality but PGP does evil things
++       * and chops off the top '0' bytes
++       */
++      if (flen > num)
++              {
++              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_DATA_GREATER_THAN_MOD_LEN);
++              goto err;
++              }
++
++      if (BN_bin2bn(from, flen, &f) == NULL)
++              goto err;
++
++      if (BN_ucmp(&f, rsa->n) >= 0)
++              {
++              RSAerr(PK11_F_RSA_PUB_DEC,
++                      PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
++              goto err;
++              }
++
++      /* PK11 functions are called here */
++      r = pk11_RSA_public_decrypt_low(flen, from, buf, rsa);
++
++      /*
++       * PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
++       * Needs to skip these 0's here
++       */
++      for (i = 0; i < r; i++)
++              if (buf[i] != 0)
++                      break;
++
++      p = buf + i;
++      i = r - i;  /* i is only used with no-padding mode */
++
++      switch (padding)
++              {
++      case RSA_PKCS1_PADDING:
++              r = RSA_padding_check_PKCS1_type_1(to, num, p, i, num);
++              break;
++      case RSA_NO_PADDING:
++              r = RSA_padding_check_none(to, num, p, i, num);
++              break;
++      default:
++              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_UNKNOWN_PADDING_TYPE);
++              goto err;
++              }
++      if (r < 0)
++              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_PADDING_CHECK_FAILED);
++
++err:
++      BN_clear_free(&f);
++      if (buf != NULL)
++              {
++              OPENSSL_cleanse(buf, num);
++              OPENSSL_free(buf);
++              }
++      return (r);
++      }
++
++/*
++ * This function implements RSA public encryption using C_EncryptInit and
++ * C_Encrypt pk11 interfaces. Note that the CKM_RSA_X_509 is used here.
++ * The calling function allocated sufficient memory in "to" to store results.
++ */
++static int pk11_RSA_public_encrypt_low(int flen,
++      const unsigned char *from, unsigned char *to, RSA *rsa)
++      {
++      CK_ULONG bytes_encrypted = flen;
++      int retval = -1;
++      CK_RV rv;
++      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
++      CK_MECHANISM *p_mech = &mech_rsa;
++      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
++      PK11_SESSION *sp;
++
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              return (-1);
++
++      (void) check_new_rsa_key_pub(sp, rsa);
++
++      h_pub_key = sp->opdata_rsa_pub_key;
++      if (h_pub_key == CK_INVALID_HANDLE)
++              h_pub_key = sp->opdata_rsa_pub_key =
++                      pk11_get_public_rsa_key(rsa, &sp->opdata_rsa_pub,
++                          &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
++                          sp->session);
++
++      if (h_pub_key != CK_INVALID_HANDLE)
++              {
++              rv = pFuncList->C_EncryptInit(sp->session, p_mech,
++                      h_pub_key);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PUB_ENC_LOW,
++                          PK11_R_ENCRYPTINIT, rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++
++              rv = pFuncList->C_Encrypt(sp->session,
++                      (unsigned char *)from, flen, to, &bytes_encrypted);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PUB_ENC_LOW,
++                          PK11_R_ENCRYPT, rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++              retval = bytes_encrypted;
++              }
++
++      pk11_return_session(sp, OP_RSA);
++      return (retval);
++      }
++
++
++/*
++ * This function implements RSA private encryption using C_SignInit and
++ * C_Sign pk11 APIs. Note that CKM_RSA_X_509 is used here.
++ * The calling function allocated sufficient memory in "to" to store results.
++ */
++static int pk11_RSA_private_encrypt_low(int flen,
++      const unsigned char *from, unsigned char *to, RSA *rsa)
++      {
++      CK_ULONG ul_sig_len = flen;
++      int retval = -1;
++      CK_RV rv;
++      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
++      CK_MECHANISM *p_mech = &mech_rsa;
++      CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
++      PK11_SESSION *sp;
++
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              return (-1);
++
++      (void) check_new_rsa_key_priv(sp, rsa);
++
++      h_priv_key = sp->opdata_rsa_priv_key;
++      if (h_priv_key == CK_INVALID_HANDLE)
++              h_priv_key = sp->opdata_rsa_priv_key =
++                      pk11_get_private_rsa_key(rsa, &sp->opdata_rsa_priv,
++                          &sp->opdata_rsa_d_num, sp->session);
++
++      if (h_priv_key != CK_INVALID_HANDLE)
++              {
++              rv = pFuncList->C_SignInit(sp->session, p_mech,
++                      h_priv_key);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PRIV_ENC_LOW,
++                          PK11_R_SIGNINIT, rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++
++              rv = pFuncList->C_Sign(sp->session,
++                      (unsigned char *)from, flen, to, &ul_sig_len);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PRIV_ENC_LOW, PK11_R_SIGN,
++                          rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++
++              retval = ul_sig_len;
++              }
++
++      pk11_return_session(sp, OP_RSA);
++      return (retval);
++      }
++
++
++/*
++ * This function implements RSA private decryption using C_DecryptInit and
++ * C_Decrypt pk11 APIs. Note that CKM_RSA_X_509 mechanism is used here.
++ * The calling function allocated sufficient memory in "to" to store results.
++ */
++static int pk11_RSA_private_decrypt_low(int flen,
++      const unsigned char *from, unsigned char *to, RSA *rsa)
++      {
++      CK_ULONG bytes_decrypted = flen;
++      int retval = -1;
++      CK_RV rv;
++      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
++      CK_MECHANISM *p_mech = &mech_rsa;
++      CK_OBJECT_HANDLE h_priv_key;
++      PK11_SESSION *sp;
++
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              return (-1);
++
++      (void) check_new_rsa_key_priv(sp, rsa);
++
++      h_priv_key = sp->opdata_rsa_priv_key;
++      if (h_priv_key == CK_INVALID_HANDLE)
++              h_priv_key = sp->opdata_rsa_priv_key =
++                      pk11_get_private_rsa_key(rsa, &sp->opdata_rsa_priv,
++                          &sp->opdata_rsa_d_num, sp->session);
++
++      if (h_priv_key != CK_INVALID_HANDLE)
++              {
++              rv = pFuncList->C_DecryptInit(sp->session, p_mech,
++                      h_priv_key);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PRIV_DEC_LOW,
++                              PK11_R_DECRYPTINIT, rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++
++              rv = pFuncList->C_Decrypt(sp->session,
++                      (unsigned char *)from, flen, to, &bytes_decrypted);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PRIV_DEC_LOW,
++                          PK11_R_DECRYPT, rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++              retval = bytes_decrypted;
++              }
++
++      pk11_return_session(sp, OP_RSA);
++      return (retval);
++      }
++
++
++/*
++ * This function implements RSA public decryption using C_VerifyRecoverInit
++ * and C_VerifyRecover pk11 APIs. Note that CKM_RSA_X_509 is used here.
++ * The calling function allocated sufficient memory in "to" to store results.
++ */
++static int pk11_RSA_public_decrypt_low(int flen,
++      const unsigned char *from, unsigned char *to, RSA *rsa)
++      {
++      CK_ULONG bytes_decrypted = flen;
++      int retval = -1;
++      CK_RV rv;
++      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
++      CK_MECHANISM *p_mech = &mech_rsa;
++      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
++      PK11_SESSION *sp;
++
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              return (-1);
++
++      (void) check_new_rsa_key_pub(sp, rsa);
++
++      h_pub_key = sp->opdata_rsa_pub_key;
++      if (h_pub_key == CK_INVALID_HANDLE)
++              h_pub_key = sp->opdata_rsa_pub_key =
++                      pk11_get_public_rsa_key(rsa, &sp->opdata_rsa_pub,
++                          &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
++                          sp->session);
++
++      if (h_pub_key != CK_INVALID_HANDLE)
++              {
++              rv = pFuncList->C_VerifyRecoverInit(sp->session,
++                      p_mech, h_pub_key);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PUB_DEC_LOW,
++                              PK11_R_VERIFYRECOVERINIT, rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++
++              rv = pFuncList->C_VerifyRecover(sp->session,
++                      (unsigned char *)from, flen, to, &bytes_decrypted);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_PUB_DEC_LOW,
++                          PK11_R_VERIFYRECOVER, rv);
++                      pk11_return_session(sp, OP_RSA);
++                      return (-1);
++                      }
++              retval = bytes_decrypted;
++              }
++
++      pk11_return_session(sp, OP_RSA);
++      return (retval);
++      }
++
++static int pk11_RSA_init(RSA *rsa)
++      {
++      /*
++       * This flag in the RSA_METHOD enables the new rsa_sign,
++       * rsa_verify functions. See rsa.h for details.
++       */
++      rsa->flags |= RSA_FLAG_SIGN_VER;
++
++      return (1);
++      }
++
++static int pk11_RSA_finish(RSA *rsa)
++      {
++      /*
++       * Since we are overloading OpenSSL's native RSA_eay_finish() we need
++       * to do the same as in the original function, i.e. to free bignum
++       * structures.
++       */
++      if (rsa->_method_mod_n != NULL)
++              BN_MONT_CTX_free(rsa->_method_mod_n);
++      if (rsa->_method_mod_p != NULL)
++              BN_MONT_CTX_free(rsa->_method_mod_p);
++      if (rsa->_method_mod_q != NULL)
++              BN_MONT_CTX_free(rsa->_method_mod_q);
++
++      return (1);
++      }
++
++/*
++ * Standard engine interface function. Majority codes here are from
++ * rsa/rsa_sign.c. We replaced the decrypt function call by C_Sign of PKCS#11.
++ * See more details in rsa/rsa_sign.c
++ */
++static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
++      unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
++      {
++      X509_SIG sig;
++      ASN1_TYPE parameter;
++      int i, j = 0;
++      unsigned char *p, *s = NULL;
++      X509_ALGOR algor;
++      ASN1_OCTET_STRING digest;
++      CK_RV rv;
++      CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
++      CK_MECHANISM *p_mech = &mech_rsa;
++      CK_OBJECT_HANDLE h_priv_key;
++      PK11_SESSION *sp = NULL;
++      int ret = 0;
++      unsigned long ulsiglen;
 +
-+/* Reason codes. */
-+#define       PK11_R_ALREADY_LOADED                   100
-+#define       PK11_R_DSO_FAILURE                      101
-+#define       PK11_R_NOT_LOADED                       102
-+#define       PK11_R_PASSED_NULL_PARAMETER            103
-+#define       PK11_R_COMMAND_NOT_IMPLEMENTED          104
-+#define       PK11_R_INITIALIZE                       105
-+#define       PK11_R_FINALIZE                         106
-+#define       PK11_R_GETINFO                          107
-+#define       PK11_R_GETSLOTLIST                      108
-+#define       PK11_R_NO_MODULUS_OR_NO_EXPONENT        109
-+#define       PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID    110
-+#define       PK11_R_GETATTRIBUTVALUE                 111
-+#define       PK11_R_NO_MODULUS                       112
-+#define       PK11_R_NO_EXPONENT                      113
-+#define       PK11_R_FINDOBJECTSINIT                  114
-+#define       PK11_R_FINDOBJECTS                      115
-+#define       PK11_R_FINDOBJECTSFINAL                 116
-+#define       PK11_R_CREATEOBJECT                     118
-+#define       PK11_R_DESTROYOBJECT                    119
-+#define       PK11_R_OPENSESSION                      120
-+#define       PK11_R_CLOSESESSION                     121
-+#define       PK11_R_ENCRYPTINIT                      122
-+#define       PK11_R_ENCRYPT                          123
-+#define       PK11_R_SIGNINIT                         124
-+#define       PK11_R_SIGN                             125
-+#define       PK11_R_DECRYPTINIT                      126
-+#define       PK11_R_DECRYPT                          127
-+#define       PK11_R_VERIFYINIT                       128
-+#define       PK11_R_VERIFY                           129
-+#define       PK11_R_VERIFYRECOVERINIT                130
-+#define       PK11_R_VERIFYRECOVER                    131
-+#define       PK11_R_GEN_KEY                          132
-+#define       PK11_R_SEEDRANDOM                       133
-+#define       PK11_R_GENERATERANDOM                   134
-+#define       PK11_R_INVALID_MESSAGE_LENGTH           135
-+#define       PK11_R_UNKNOWN_ALGORITHM_TYPE           136
-+#define       PK11_R_UNKNOWN_ASN1_OBJECT_ID           137
-+#define       PK11_R_UNKNOWN_PADDING_TYPE             138
-+#define       PK11_R_PADDING_CHECK_FAILED             139
-+#define       PK11_R_DIGEST_TOO_BIG                   140
-+#define       PK11_R_MALLOC_FAILURE                   141
-+#define       PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED     142
-+#define       PK11_R_DATA_GREATER_THAN_MOD_LEN        143
-+#define       PK11_R_DATA_TOO_LARGE_FOR_MODULUS       144
-+#define       PK11_R_MISSING_KEY_COMPONENT            145
-+#define       PK11_R_INVALID_SIGNATURE_LENGTH         146
-+#define       PK11_R_INVALID_DSA_SIGNATURE_R          147
-+#define       PK11_R_INVALID_DSA_SIGNATURE_S          148
-+#define       PK11_R_INCONSISTENT_KEY                 149
-+#define       PK11_R_ENCRYPTUPDATE                    150
-+#define       PK11_R_DECRYPTUPDATE                    151
-+#define       PK11_R_DIGESTINIT                       152
-+#define       PK11_R_DIGESTUPDATE                     153
-+#define       PK11_R_DIGESTFINAL                      154
-+#define       PK11_R_ENCRYPTFINAL                     155
-+#define       PK11_R_DECRYPTFINAL                     156
-+#define       PK11_R_NO_PRNG_SUPPORT                  157
-+#define       PK11_R_GETTOKENINFO                     158
-+#define       PK11_R_DERIVEKEY                        159
-+#define       PK11_R_GET_OPERATION_STATE              160
-+#define       PK11_R_SET_OPERATION_STATE              161
-+#define       PK11_R_INVALID_HANDLE                   162
-+#define       PK11_R_KEY_OR_IV_LEN_PROBLEM            163
-+#define       PK11_R_INVALID_OPERATION_TYPE           164
-+#define       PK11_R_ADD_NID_FAILED                   165
-+#define       PK11_R_ATFORK_FAILED                    166
-+#define       PK11_R_INVALID_PIN                      167
-+#define       PK11_R_TOO_MANY_OBJECTS                 168
-+#define       PK11_R_OBJECT_NOT_FOUND                 169
++      /* Encode the digest */
++      /* Special case: SSL signature, just check the length */
++      if (type == NID_md5_sha1)
++              {
++              if (m_len != SSL_SIG_LENGTH)
++                      {
++                      PK11err(PK11_F_RSA_SIGN,
++                              PK11_R_INVALID_MESSAGE_LENGTH);
++                      goto err;
++                      }
++              i = SSL_SIG_LENGTH;
++              s = (unsigned char *)m;
++              }
++      else
++              {
++              sig.algor = &algor;
++              sig.algor->algorithm = OBJ_nid2obj(type);
++              if (sig.algor->algorithm == NULL)
++                      {
++                      PK11err(PK11_F_RSA_SIGN,
++                              PK11_R_UNKNOWN_ALGORITHM_TYPE);
++                      goto err;
++                      }
++              if (sig.algor->algorithm->length == 0)
++                      {
++                      PK11err(PK11_F_RSA_SIGN,
++                              PK11_R_UNKNOWN_ASN1_OBJECT_ID);
++                      goto err;
++                      }
++              parameter.type = V_ASN1_NULL;
++              parameter.value.ptr = NULL;
++              sig.algor->parameter = &parameter;
++
++              sig.digest = &digest;
++              sig.digest->data = (unsigned char *)m;
++              sig.digest->length = m_len;
++
++              i = i2d_X509_SIG(&sig, NULL);
++              }
++
++      j = RSA_size(rsa);
++      if ((i - RSA_PKCS1_PADDING) > j)
++              {
++              PK11err(PK11_F_RSA_SIGN, PK11_R_DIGEST_TOO_BIG);
++              goto err;
++              }
++
++      if (type != NID_md5_sha1)
++              {
++              s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
++              if (s == NULL)
++                      {
++                      PK11err(PK11_F_RSA_SIGN, PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
++              p = s;
++              (void) i2d_X509_SIG(&sig, &p);
++              }
++
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              goto err;
++
++      (void) check_new_rsa_key_priv(sp, rsa);
++
++      h_priv_key = sp->opdata_rsa_priv_key;
++      if (h_priv_key == CK_INVALID_HANDLE)
++              h_priv_key = sp->opdata_rsa_priv_key =
++                      pk11_get_private_rsa_key((RSA *)rsa,
++                          &sp->opdata_rsa_priv,
++                          &sp->opdata_rsa_d_num, sp->session);
++
++      if (h_priv_key != CK_INVALID_HANDLE)
++              {
++              rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGNINIT, rv);
++                      goto err;
++                      }
++
++              ulsiglen = j;
++              rv = pFuncList->C_Sign(sp->session, s, i, sigret,
++                      (CK_ULONG_PTR) &ulsiglen);
++              *siglen = ulsiglen;
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGN, rv);
++                      goto err;
++                      }
++              ret = 1;
++              }
++
++err:
++      if ((type != NID_md5_sha1) && (s != NULL))
++              {
++              (void) memset(s, 0, (unsigned int)(j + 1));
++              OPENSSL_free(s);
++              }
++
++      pk11_return_session(sp, OP_RSA);
++      return (ret);
++      }
++
++static int pk11_RSA_verify(int type, const unsigned char *m,
++      unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
++      const RSA *rsa)
++      {
++      X509_SIG sig;
++      ASN1_TYPE parameter;
++      int i, j = 0;
++      unsigned char *p, *s = NULL;
++      X509_ALGOR algor;
++      ASN1_OCTET_STRING digest;
++      CK_RV rv;
++      CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
++      CK_MECHANISM *p_mech = &mech_rsa;
++      CK_OBJECT_HANDLE h_pub_key;
++      PK11_SESSION *sp = NULL;
++      int ret = 0;
++
++      /* Encode the digest    */
++      /* Special case: SSL signature, just check the length */
++      if (type == NID_md5_sha1)
++              {
++              if (m_len != SSL_SIG_LENGTH)
++                      {
++                      PK11err(PK11_F_RSA_VERIFY,
++                              PK11_R_INVALID_MESSAGE_LENGTH);
++                      goto err;
++                      }
++              i = SSL_SIG_LENGTH;
++              s = (unsigned char *)m;
++              }
++      else
++              {
++              sig.algor = &algor;
++              sig.algor->algorithm = OBJ_nid2obj(type);
++              if (sig.algor->algorithm == NULL)
++                      {
++                      PK11err(PK11_F_RSA_VERIFY,
++                              PK11_R_UNKNOWN_ALGORITHM_TYPE);
++                      goto err;
++                      }
++              if (sig.algor->algorithm->length == 0)
++                      {
++                      PK11err(PK11_F_RSA_VERIFY,
++                              PK11_R_UNKNOWN_ASN1_OBJECT_ID);
++                      goto err;
++                      }
++              parameter.type = V_ASN1_NULL;
++              parameter.value.ptr = NULL;
++              sig.algor->parameter = &parameter;
++              sig.digest = &digest;
++              sig.digest->data = (unsigned char *)m;
++              sig.digest->length = m_len;
++              i = i2d_X509_SIG(&sig, NULL);
++              }
++
++      j = RSA_size(rsa);
++      if ((i - RSA_PKCS1_PADDING) > j)
++              {
++              PK11err(PK11_F_RSA_VERIFY, PK11_R_DIGEST_TOO_BIG);
++              goto err;
++              }
 +
-+/* max byte length of a symetric key we support */
-+#define       PK11_KEY_LEN_MAX                        32
++      if (type != NID_md5_sha1)
++              {
++              s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
++              if (s == NULL)
++                      {
++                      PK11err(PK11_F_RSA_VERIFY, PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
++              p = s;
++              (void) i2d_X509_SIG(&sig, &p);
++              }
 +
-+#ifdef NOPTHREADS
-+/*
-+ * CRYPTO_LOCK_PK11_ENGINE lock is primarily used for the protection of the
-+ * free_session list and active_list but generally serves as a global
-+ * per-process lock for the whole engine.
-+ *
-+ * We reuse CRYPTO_LOCK_EC lock (which is defined in OpenSSL for EC method) as
-+ * the global engine lock. This is not optimal w.r.t. performance but
-+ * it's safe.
-+ */
-+#define CRYPTO_LOCK_PK11_ENGINE       CRYPTO_LOCK_EC
-+#endif
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              goto err;
 +
-+/*
-+ * This structure encapsulates all reusable information for a PKCS#11
-+ * session. A list of these objects is created on behalf of the
-+ * calling application using an on-demand method. Each operation
-+ * type (see PK11_OPTYPE below) has its own per-process list.
-+ * Each of the lists is basically a cache for faster PKCS#11 object
-+ * access to avoid expensive C_Find{,Init,Final}Object() calls.
-+ *
-+ * When a new request comes in, an object will be taken from the list
-+ * (if there is one) or a new one is created to handle the request
-+ * (if the list is empty). See pk11_get_session() on how it is done.
-+ */
-+typedef struct PK11_st_SESSION
-+      {
-+      struct PK11_st_SESSION  *next;
-+      CK_SESSION_HANDLE       session;        /* PK11 session handle */
-+      pid_t                   pid;            /* Current process ID */
-+      union
++      (void) check_new_rsa_key_pub(sp, rsa);
++
++      h_pub_key = sp->opdata_rsa_pub_key;
++      if (h_pub_key == CK_INVALID_HANDLE)
++              h_pub_key = sp->opdata_rsa_pub_key =
++                      pk11_get_public_rsa_key((RSA *)rsa, &sp->opdata_rsa_pub,
++                          &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
++                          sp->session);
++
++      if (h_pub_key != CK_INVALID_HANDLE)
 +              {
-+#ifndef OPENSSL_NO_RSA
-+              struct
-+                      {
-+                      CK_OBJECT_HANDLE        rsa_pub_key; /* pub handle */
-+                      CK_OBJECT_HANDLE        rsa_priv_key; /* priv handle */
-+                      RSA                     *rsa_pub; /* pub key addr */
-+                      BIGNUM                  *rsa_n_num; /* pub modulus */
-+                      BIGNUM                  *rsa_e_num; /* pub exponent */
-+                      RSA                     *rsa_priv; /* priv key addr */
-+                      BIGNUM                  *rsa_d_num; /* priv exponent */
-+                      } u_RSA;
-+#endif /* OPENSSL_NO_RSA */
-+#ifndef OPENSSL_NO_DSA
-+              struct
-+                      {
-+                      CK_OBJECT_HANDLE        dsa_pub_key; /* pub handle */
-+                      CK_OBJECT_HANDLE        dsa_priv_key; /* priv handle */
-+                      DSA                     *dsa_pub; /* pub key addr */
-+                      BIGNUM                  *dsa_pub_num; /* pub key */
-+                      DSA                     *dsa_priv; /* priv key addr */
-+                      BIGNUM                  *dsa_priv_num; /* priv key */
-+                      } u_DSA;
-+#endif /* OPENSSL_NO_DSA */
-+#ifndef OPENSSL_NO_DH
-+              struct
++              rv = pFuncList->C_VerifyInit(sp->session, p_mech,
++                      h_pub_key);
++
++              if (rv != CKR_OK)
 +                      {
-+                      CK_OBJECT_HANDLE        dh_key; /* key handle */
-+                      DH                      *dh; /* dh key addr */
-+                      BIGNUM                  *dh_priv_num; /* priv dh key */
-+                      } u_DH;
-+#endif /* OPENSSL_NO_DH */
-+              struct
++                      PK11err_add_data(PK11_F_RSA_VERIFY, PK11_R_VERIFYINIT,
++                          rv);
++                      goto err;
++                      }
++              rv = pFuncList->C_Verify(sp->session, s, i, sigbuf,
++                      (CK_ULONG)siglen);
++
++              if (rv != CKR_OK)
 +                      {
-+                      CK_OBJECT_HANDLE        cipher_key; /* key handle */
-+                      unsigned char           key[PK11_KEY_LEN_MAX];
-+                      int                     key_len; /* priv key len */
-+                      int                     encrypt; /* 1/0 enc/decr */
-+                      } u_cipher;
-+              } opdata_u;
-+      } PK11_SESSION;
++                      PK11err_add_data(PK11_F_RSA_VERIFY, PK11_R_VERIFY, rv);
++                      goto err;
++                      }
++              ret = 1;
++              }
 +
-+#define       opdata_rsa_pub_key      opdata_u.u_RSA.rsa_pub_key
-+#define       opdata_rsa_priv_key     opdata_u.u_RSA.rsa_priv_key
-+#define       opdata_rsa_pub          opdata_u.u_RSA.rsa_pub
-+#define       opdata_rsa_priv         opdata_u.u_RSA.rsa_priv
-+#define       opdata_rsa_n_num        opdata_u.u_RSA.rsa_n_num
-+#define       opdata_rsa_e_num        opdata_u.u_RSA.rsa_e_num
-+#define       opdata_rsa_d_num        opdata_u.u_RSA.rsa_d_num
-+#define       opdata_dsa_pub_key      opdata_u.u_DSA.dsa_pub_key
-+#define       opdata_dsa_priv_key     opdata_u.u_DSA.dsa_priv_key
-+#define       opdata_dsa_pub          opdata_u.u_DSA.dsa_pub
-+#define       opdata_dsa_pub_num      opdata_u.u_DSA.dsa_pub_num
-+#define       opdata_dsa_priv         opdata_u.u_DSA.dsa_priv
-+#define       opdata_dsa_priv_num     opdata_u.u_DSA.dsa_priv_num
-+#define       opdata_dh_key           opdata_u.u_DH.dh_key
-+#define       opdata_dh               opdata_u.u_DH.dh
-+#define       opdata_dh_priv_num      opdata_u.u_DH.dh_priv_num
-+#define       opdata_cipher_key       opdata_u.u_cipher.cipher_key
-+#define       opdata_key              opdata_u.u_cipher.key
-+#define       opdata_key_len          opdata_u.u_cipher.key_len
-+#define       opdata_encrypt          opdata_u.u_cipher.encrypt
++err:
++      if ((type != NID_md5_sha1) && (s != NULL))
++              {
++              (void) memset(s, 0, (unsigned int)(j + 1));
++              OPENSSL_free(s);
++              }
 +
-+/*
-+ * We have 3 different groups of operation types:
-+ *   1) asymmetric operations
-+ *   2) random operations
-+ *   3) symmetric and digest operations
-+ *
-+ * This division into groups stems from the fact that it's common that hardware
-+ * providers may support operations from one group only. For example, hardware
-+ * providers on UltraSPARC T2, n2rng(7d), ncp(7d), and n2cp(7d), each support
-+ * only a single group of operations.
-+ *
-+ * For every group a different slot can be chosen. That means that we must have
-+ * at least 3 different lists of cached PKCS#11 sessions since sessions from
-+ * different groups may be initialized in different slots.
-+ *
-+ * To provide locking granularity in multithreaded environment, the groups are
-+ * further splitted into types with each type having a separate session cache.
-+ */
-+typedef enum PK11_OPTYPE_ENUM
-+      {
-+      OP_RAND,
-+      OP_RSA,
-+      OP_DSA,
-+      OP_DH,
-+      OP_CIPHER,
-+      OP_DIGEST,
-+      OP_MAX
-+      } PK11_OPTYPE;
++      pk11_return_session(sp, OP_RSA);
++      return (ret);
++      }
 +
-+/*
-+ * This structure contains the heads of the lists forming the object caches
-+ * and locks associated with the lists.
-+ */
-+typedef struct PK11_st_CACHE
++static int hndidx_rsa = -1;
++
++/* load RSA private key from a file */
++/* ARGSUSED */
++EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *privkey_file,
++      UI_METHOD *ui_method, void *callback_data)
 +      {
-+      PK11_SESSION *head;
-+#ifndef NOPTHREADS
-+      pthread_mutex_t *lock;
-+#endif
-+      } PK11_CACHE;
++      EVP_PKEY *pkey = NULL;
++      FILE *privkey;
++      CK_OBJECT_HANDLE  h_priv_key = CK_INVALID_HANDLE;
++      RSA *rsa;
++      PK11_SESSION *sp;
++      /* everything else below needed for key by reference extension */
++      CK_RV rv;
++      CK_ULONG objcnt = 0;
++      CK_BBOOL is_token = TRUE;
++      CK_BYTE attr_data[2][1024];
++      CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY;
++      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
++      extern char *pk11_pin;
++
++      /* we look for private keys only */
++      CK_ATTRIBUTE search_templ[] =
++              {
++              {CKA_TOKEN, &is_token, sizeof(is_token)},
++              {CKA_CLASS, &key_class, sizeof(key_class)},
++              {CKA_LABEL, NULL, 0}
++              };
++
++      /* these attributes are needed to initialize OpenSSL RSA structure */
++      CK_ATTRIBUTE get_templ[] =
++              {
++              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
++              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
++              };
++
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              return (NULL);
++
++      /*
++       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
++       */
++      if (strstr(privkey_file, "pkcs11:") == privkey_file)
++              {
++              search_templ[2].pValue = strstr(privkey_file, ":") + 1;
++              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
++
++              if (pk11_pin == NULL)
++                      {
++                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
++
++                      if (pk11_pin == NULL)
++                              {
++                              PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MALLOC_FAILURE);
++                              goto err;
++                              }
++                      }
++              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
++                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
++                      {
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_INVALID_PIN, rv);
++                      goto err;
++                      }
++
++              LOCK_OBJSTORE(OP_RSA);
++              if ((rv = pFuncList->C_FindObjectsInit(sp->session,
++                  search_templ, 3)) != CKR_OK)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_FINDOBJECTSINIT, rv);
++                      goto err;
++                      }
++
++              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
++              if (rv != CKR_OK)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_FINDOBJECTS, rv);
++                      goto err;
++                      }
 +
-+/* structure for tracking handles of asymmetric key objects */
-+typedef struct PK11_active_st
-+      {
-+      CK_OBJECT_HANDLE h;
-+      unsigned int refcnt;
-+      struct PK11_active_st *prev;
-+      struct PK11_active_st *next;
-+      } PK11_active;
++              if (objcnt > 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_TOO_MANY_OBJECTS);
++                      goto err;
++                      }
 +
-+#ifndef NOPTHREADS
-+extern pthread_mutex_t *find_lock[];
-+#endif
-+extern PK11_active *active_list[];
++              if (objcnt != 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_OBJECT_NOT_FOUND);
++                      goto err;
++                      }
 +
-+#ifndef NOPTHREADS
-+#define       LOCK_OBJSTORE(alg_type) \
-+      (void) pthread_mutex_lock(find_lock[alg_type])
-+#define       UNLOCK_OBJSTORE(alg_type)       \
-+      (void) pthread_mutex_unlock(find_lock[alg_type])
-+#else
-+#define       LOCK_OBJSTORE(alg_type) \
-+      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE)
-+#define       UNLOCK_OBJSTORE(alg_type)       \
-+      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE)
-+#endif
++              (void) pFuncList->C_FindObjectsFinal(sp->session);
++              UNLOCK_OBJSTORE(OP_RSA);
 +
-+extern PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
-+extern void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);
++              if (hndidx_rsa == -1)
++                      hndidx_rsa = RSA_get_ex_new_index(0,
++                                      "pkcs11 RSA HSM key handle",
++                                      NULL, NULL, NULL);
 +
-+#ifndef OPENSSL_NO_RSA
-+extern int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
-+extern int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
-+extern int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
-+extern EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data);
-+extern EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data);
-+extern RSA_METHOD *PK11_RSA(void);
-+#endif /* OPENSSL_NO_RSA */
-+#ifndef OPENSSL_NO_DSA
-+extern int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
-+extern int pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
-+extern int pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
-+extern DSA_METHOD *PK11_DSA(void);
-+#endif /* OPENSSL_NO_DSA */
-+#ifndef OPENSSL_NO_DH
-+extern int pk11_destroy_dh_key_objects(PK11_SESSION *session);
-+extern int pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock);
-+extern DH_METHOD *PK11_DH(void);
-+#endif /* OPENSSL_NO_DH */
++              pkey = EVP_PKEY_new();
++              if (pkey == NULL)
++                      goto err;
 +
-+extern CK_FUNCTION_LIST_PTR pFuncList;
++              rsa = RSA_new_method(e);
++              if (rsa == NULL) {
++                      EVP_PKEY_free(pkey);
++                      pkey = NULL;
++                      goto err;
++              }
++              EVP_PKEY_assign_RSA(pkey, rsa);
 +
-+#endif /* HW_PK11_ERR_H */
-Index: openssl/crypto/engine/hw_pk11_pub-kp.c
-diff -u /dev/null openssl/crypto/engine/hw_pk11_pub-kp.c:1.21
---- /dev/null  Mon Oct  5 11:08:14 2009
-+++ openssl/crypto/engine/hw_pk11_pub-kp.c     Tue Sep  1 06:02:18 2009
-@@ -0,0 +1,896 @@
-+/*
-+ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
-+ * Use is subject to license terms.
-+ */
++              if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
++                  get_templ, 2)) != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_GETATTRIBUTVALUE, rv);
++                      EVP_PKEY_free(pkey);
++                      pkey = NULL;
++                      goto err;
++                      }
 +
-+/* crypto/engine/hw_pk11_pub.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).
-+ *
-+ */
++              /*
++               * Now we have to initialize an OpenSSL RSA structure,
++               * everything else is 0 or NULL.
++               */
++              rsa->flags = RSA_FLAG_SIGN_VER | RSA_FLAG_EXT_PKEY;
++              RSA_set_ex_data(rsa, hndidx_rsa, (void *) ks_key);
++              (void) check_new_rsa_key_priv(sp, rsa);
++              sp->opdata_rsa_priv = rsa;
++              sp->opdata_rsa_priv_key = ks_key;
 +
-+/* Modified to keep only RNG and RSA Sign */
++              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
++              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
++              }
++      else if ((privkey = fopen(privkey_file, read_mode_flags)) != NULL)
++              {
++              pkey = PEM_read_PrivateKey(privkey, NULL, NULL, NULL);
++              (void) fclose(privkey);
++              if (pkey != NULL)
++                      {
++                      rsa = EVP_PKEY_get1_RSA(pkey);
++                      if (rsa != NULL)
++                              {
++                              (void) check_new_rsa_key_priv(sp, rsa);
 +
-+#ifdef OPENSSL_NO_RSA
-+#error RSA is disabled
-+#endif
++                              h_priv_key = sp->opdata_rsa_priv_key =
++                                  pk11_get_private_rsa_key(rsa,
++                                  &sp->opdata_rsa_priv, &sp->opdata_rsa_d_num,
++                                  sp->session);
++                              if (h_priv_key == CK_INVALID_HANDLE)
++                                      {
++                                      EVP_PKEY_free(pkey);
++                                      pkey = NULL;
++                                      }
++                              }
++                      else
++                              {
++                              EVP_PKEY_free(pkey);
++                              pkey = NULL;
++                              }
++                      }
++              }
 +
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <string.h>
-+#include <sys/types.h>
++err:
++      pk11_return_session(sp, OP_RSA);
++      return (pkey);
++      }
 +
-+#include <openssl/e_os2.h>
-+#include <openssl/crypto.h>
-+#include <cryptlib.h>
-+#include <openssl/engine.h>
-+#include <openssl/dso.h>
-+#include <openssl/err.h>
-+#include <openssl/bn.h>
-+#include <openssl/pem.h>
-+#include <openssl/rsa.h>
-+#include <openssl/rand.h>
-+#include <openssl/objects.h>
-+#include <openssl/x509.h>
++/* load RSA public key from a file */
++/* ARGSUSED */
++EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data)
++      {
++      EVP_PKEY *pkey = NULL;
++      FILE *pubkey;
++      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
++      RSA *rsa;
++      PK11_SESSION *sp;
++      /* everything else below needed for key by reference extension */
++      CK_RV rv;
++      CK_ULONG objcnt = 0;
++      CK_BBOOL is_token = TRUE;
++      CK_BYTE attr_data[2][1024];
++      CK_OBJECT_CLASS key_class = CKO_PUBLIC_KEY;
++      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
++      extern char *pk11_pin;
 +
-+#ifdef OPENSSL_SYS_WIN32
-+#define NOPTHREADS
-+typedef int pid_t;
-+#define HAVE_GETPASSPHRASE
-+static char *getpassphrase(const char *prompt);
-+#ifndef NULL_PTR
-+#define NULL_PTR NULL
-+#endif
-+#define CK_DEFINE_FUNCTION(returnType, name) \
-+      returnType __declspec(dllexport) name
-+#define CK_DECLARE_FUNCTION(returnType, name) \
-+      returnType __declspec(dllimport) name
-+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
-+      returnType __declspec(dllimport) (* name)
-+#else
-+#include <unistd.h>
-+#endif
++      /* we look for public keys only */
++      CK_ATTRIBUTE search_templ[] =
++              {
++              {CKA_TOKEN, &is_token, sizeof(is_token)},
++              {CKA_CLASS, &key_class, sizeof(key_class)},
++              {CKA_LABEL, NULL, 0}
++              };
 +
-+#ifndef NOPTHREADS
-+#include <pthread.h>
-+#endif
++      /* these attributes are needed to initialize OpenSSL RSA structure */
++      CK_ATTRIBUTE get_templ[] =
++              {
++              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
++              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
++              };
 +
-+#ifndef OPENSSL_NO_HW
-+#ifndef OPENSSL_NO_HW_PK11
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++              return (NULL);
 +
-+#ifndef OPENSSL_NO_DSA
-+#define OPENSSL_NO_DSA
-+#endif
-+#ifndef OPENSSL_NO_DH
-+#define OPENSSL_NO_DH
-+#endif
++      /*
++       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
++       */
++      if (strstr(pubkey_file, "pkcs11:") == pubkey_file)
++              {
++              search_templ[2].pValue = strstr(pubkey_file, ":") + 1;
++              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
 +
-+#ifdef OPENSSL_SYS_WIN32
-+#pragma pack(push, cryptoki, 1)
-+#include "cryptoki.h"
-+#include "pkcs11.h"
-+#pragma pack(pop, cryptoki)
-+#else
-+#include "cryptoki.h"
-+#include "pkcs11.h"
-+#endif
-+#include "hw_pk11_err.h"
++#define ALLWAYS_LOGIN
++#ifdef ALLWAYS_LOGIN
++              if (pk11_pin == NULL)
++                      {
++                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
 +
-+#if !(defined(HAVE_GETPASSPHRASE) || (defined (__SVR4) && defined (__sun)))
-+#define getpassphrase(x)      getpass(x)
++                      if (pk11_pin == NULL)
++                              {
++                              PK11err(PK11_F_LOAD_PUBKEY, PK11_R_MALLOC_FAILURE);
++                              goto err;
++                              }
++                      }
++              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
++                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
++                      {
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_INVALID_PIN, rv);
++                      goto err;
++                      }
 +#endif
 +
-+/* RSA stuff */
-+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
-+      unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
-+EVP_PKEY *pk11_load_privkey(ENGINE*, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data);
-+EVP_PKEY *pk11_load_pubkey(ENGINE*, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data);
++              LOCK_OBJSTORE(OP_RSA);
++              if (pFuncList->C_FindObjectsInit(sp->session, search_templ, 3) != CKR_OK)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_FINDOBJECTSINIT, rv);
++                      goto err;
++                      }
++              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
++              if (rv != CKR_OK)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_FINDOBJECTS, rv);
++                      goto err;
++                      }
 +
-+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, RSA** key_ptr,
-+      BIGNUM **rsa_d_num, CK_SESSION_HANDLE session);
++              if (objcnt > 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_TOO_MANY_OBJECTS);
++                      goto err;
++                      }
 +
-+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa);
-+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa);
++              if (objcnt != 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_OBJECT_NOT_FOUND);
++                      goto err;
++                      }
 +
-+static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn);
++              (void) pFuncList->C_FindObjectsFinal(sp->session);
++              UNLOCK_OBJSTORE(OP_RSA);
 +
-+/* Read mode string to be used for fopen() */
-+#if SOLARIS_OPENSSL
-+static char *read_mode_flags = "rF";
-+#else
-+static char *read_mode_flags = "r";
-+#endif
++              sp->opdata_rsa_pub_key = ks_key;
++              pkey = EVP_PKEY_new();
++              if (pkey == NULL)
++                      goto err;
 +
-+/*
-+ * increment/create reference for an asymmetric key handle via active list
-+ * manipulation. If active list operation fails, unlock (if locked), set error
-+ * variable and jump to the specified label.
-+ */
-+#define       KEY_HANDLE_REFHOLD(key_handle, alg_type, unlock, var, label)    \
-+      {                                                               \
-+      if (pk11_active_add(key_handle, alg_type) < 0)                  \
-+              {                                                       \
-+              var = TRUE;                                             \
-+              if (unlock)                                             \
-+                      UNLOCK_OBJSTORE(alg_type);                      \
-+              goto label;                                             \
-+              }                                                       \
-+      }
++              rsa = RSA_new_method(e);
++              if (rsa == NULL) {
++                      EVP_PKEY_free(pkey);
++                      pkey = NULL;
++                      goto err;
++              }
++              EVP_PKEY_assign_RSA(pkey, rsa);
 +
-+/*
-+ * Find active list entry according to object handle and return pointer to the
-+ * entry otherwise return NULL.
-+ *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
-+ */
-+static PK11_active *pk11_active_find(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
-+      {
-+      PK11_active *entry;
++              if (pFuncList->C_GetAttributeValue(sp->session, ks_key,
++                  get_templ, 2) != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_GETATTRIBUTVALUE, rv);
++                      goto err;
++                      }
 +
-+      for (entry = active_list[type]; entry != NULL; entry = entry->next)
-+              if (entry->h == h)
-+                      return (entry);
++              /*
++               * Now we have to initialize an OpenSSL RSA structure,
++               * everything else is 0 or NULL.
++               */
++              rsa->flags = RSA_FLAG_SIGN_VER;
++              (void) check_new_rsa_key_pub(sp, rsa);
++              sp->opdata_rsa_pub = rsa;
 +
-+      return (NULL);
++              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
++              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
++              }
++      else if ((pubkey = fopen(pubkey_file, read_mode_flags)) != NULL)
++              {
++              pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
++              (void) fclose(pubkey);
++              if (pkey != NULL)
++                      {
++                      rsa = EVP_PKEY_get1_RSA(pkey);
++                      if (rsa != NULL)
++                              {
++                              (void) check_new_rsa_key_pub(sp, rsa);
++
++                              h_pub_key = sp->opdata_rsa_pub_key =
++                                  pk11_get_public_rsa_key(rsa,
++                                  &sp->opdata_rsa_pub, &sp->opdata_rsa_n_num,
++                                  &sp->opdata_rsa_e_num, sp->session);
++                              if (h_pub_key == CK_INVALID_HANDLE)
++                                      {
++                                      EVP_PKEY_free(pkey);
++                                      pkey = NULL;
++                                      }
++                              }
++                      else
++                              {
++                              EVP_PKEY_free(pkey);
++                              pkey = NULL;
++                              }
++                      }
++              }
++
++err:
++      pk11_return_session(sp, OP_RSA);
++      return (pkey);
 +      }
 +
 +/*
-+ * Search for an entry in the active list using PKCS#11 object handle as a
-+ * search key and return refcnt of the found/created entry or -1 in case of
-+ * failure.
-+ *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
++ * Create a public key object in a session from a given rsa structure.
++ * The *rsa_n_num and *rsa_e_num pointers are non-NULL for RSA public keys.
 + */
-+int
-+pk11_active_add(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
++static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA *rsa,
++    RSA **key_ptr, BIGNUM **rsa_n_num, BIGNUM **rsa_e_num,
++    CK_SESSION_HANDLE session)
 +      {
-+      PK11_active *entry = NULL;
-+
-+      if (h == CK_INVALID_HANDLE)
-+              {
-+              PK11err(PK11_F_ACTIVE_ADD, PK11_R_INVALID_HANDLE);
-+              return (-1);
-+              }
++      CK_RV rv;
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      CK_ULONG found;
++      CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
++      CK_KEY_TYPE k_type = CKK_RSA;
++      CK_ULONG ul_key_attr_count = 8;
++      CK_BBOOL rollback = FALSE;
 +
-+      /* search for entry in the active list */
-+      if ((entry = pk11_active_find(h, type)) != NULL)
-+              entry->refcnt++;
-+      else
++      CK_ATTRIBUTE  a_key_template[] =
 +              {
-+              /* not found, create new entry and add it to the list */
-+              entry = OPENSSL_malloc(sizeof (PK11_active));
-+              if (entry == NULL)
-+                      {
-+                      PK11err(PK11_F_ACTIVE_ADD, PK11_R_MALLOC_FAILURE);
-+                      return (-1);
-+                      }
-+              entry->h = h;
-+              entry->refcnt = 1;
-+              entry->prev = NULL;
-+              entry->next = NULL;
-+              /* connect the newly created entry to the list */
-+              if (active_list[type] == NULL)
-+                      active_list[type] = entry;
-+              else /* make the entry first in the list */
-+                      {
-+                      entry->next = active_list[type];
-+                      active_list[type]->prev = entry;
-+                      active_list[type] = entry;
-+                      }
-+              }
++              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
++              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
++              {CKA_TOKEN, &false, sizeof (true)},
++              {CKA_ENCRYPT, &true, sizeof (true)},
++              {CKA_VERIFY, &true, sizeof (true)},
++              {CKA_VERIFY_RECOVER, &true, sizeof (true)},
++              {CKA_MODULUS, (void *)NULL, 0},
++              {CKA_PUBLIC_EXPONENT, (void *)NULL, 0}
++              };
 +
-+      return (entry->refcnt);
-+      }
++      int i;
 +
-+/*
-+ * Remove active list entry from the list and free it.
-+ *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
-+ */
-+void
-+pk11_active_remove(PK11_active *entry, PK11_OPTYPE type)
-+      {
-+      PK11_active *prev_entry;
++      a_key_template[0].pValue = &o_key;
++      a_key_template[1].pValue = &k_type;
 +
-+      /* remove the entry from the list and free it */
-+      if ((prev_entry = entry->prev) != NULL)
++      a_key_template[6].ulValueLen = BN_num_bytes(rsa->n);
++      a_key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
++              (size_t)a_key_template[6].ulValueLen);
++      if (a_key_template[6].pValue == NULL)
 +              {
-+              prev_entry->next = entry->next;
-+              if (entry->next != NULL)
-+                      entry->next->prev = prev_entry;
++              PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
 +              }
-+      else
++
++      BN_bn2bin(rsa->n, a_key_template[6].pValue);
++
++      a_key_template[7].ulValueLen = BN_num_bytes(rsa->e);
++      a_key_template[7].pValue = (CK_VOID_PTR)OPENSSL_malloc(
++              (size_t)a_key_template[7].ulValueLen);
++      if (a_key_template[7].pValue == NULL)
 +              {
-+              active_list[type] = entry->next;
-+              /* we were the first but not the only one */
-+              if (entry->next != NULL)
-+                      entry->next->prev = NULL;
++              PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
 +              }
 +
-+      /* sanitization */
-+      entry->h = CK_INVALID_HANDLE;
-+      entry->prev = NULL;
-+      entry->next = NULL;
-+      OPENSSL_free(entry);
-+      }
++      BN_bn2bin(rsa->e, a_key_template[7].pValue);
 +
-+/* Free all entries from the active list. */
-+void
-+pk11_free_active_list(PK11_OPTYPE type)
-+      {
-+      PK11_active *entry;
++      /* see find_lock array definition for more info on object locking */
++      LOCK_OBJSTORE(OP_RSA);
++      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
++              ul_key_attr_count);
 +
-+      /* only for asymmetric types since only they have C_Find* locks. */
-+      switch (type)
++      if (rv != CKR_OK)
 +              {
-+              case OP_RSA:
-+                      break;
-+              default:
-+                      return;
++              PK11err_add_data(PK11_F_GET_PUB_RSA_KEY, PK11_R_FINDOBJECTSINIT,
++                  rv);
++              goto err;
 +              }
 +
-+      /* see find_lock array definition for more info on object locking */
-+      LOCK_OBJSTORE(type);
-+      while ((entry = active_list[type]) != NULL)
-+              pk11_active_remove(entry, type);
-+      UNLOCK_OBJSTORE(type);
-+      }
++      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
 +
-+/*
-+ * Search for active list entry associated with given PKCS#11 object handle,
-+ * decrement its refcnt and if it drops to 0, disconnect the entry and free it.
-+ *
-+ * Return 1 if the PKCS#11 object associated with the entry has no references,
-+ * return 0 if there is at least one reference, -1 on error.
-+ *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
-+ */
-+int
-+pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
-+      {
-+      PK11_active *entry = NULL;
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
++                  PK11_R_FINDOBJECTS, rv);
++              goto err;
++              }
 +
-+      if ((entry = pk11_active_find(h, type)) == NULL)
++      rv = pFuncList->C_FindObjectsFinal(session);
++
++      if (rv != CKR_OK)
 +              {
-+              PK11err(PK11_F_ACTIVE_DELETE, PK11_R_INVALID_HANDLE);
-+              return (-1);
++              PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
++                  PK11_R_FINDOBJECTSFINAL, rv);
++              goto err;
 +              }
 +
-+      OPENSSL_assert(entry->refcnt > 0);
-+      entry->refcnt--;
-+      if (entry->refcnt == 0)
++      if (found == 0)
 +              {
-+              pk11_active_remove(entry, type);
-+              return (1);
++              rv = pFuncList->C_CreateObject(session,
++                      a_key_template, ul_key_attr_count, &h_key);
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
++                          PK11_R_CREATEOBJECT, rv);
++                      goto err;
++                      }
 +              }
 +
-+      return (0);
-+      }
++      if (rsa_n_num != NULL)
++              if ((*rsa_n_num = BN_dup(rsa->n)) == NULL)
++                      {
++                      PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
++                      rollback = TRUE;
++                      goto err;
++                      }
++      if (rsa_e_num != NULL)
++              if ((*rsa_e_num = BN_dup(rsa->e)) == NULL)
++                      {
++                      PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
++                      BN_free(*rsa_n_num);
++                      *rsa_n_num = NULL;
++                      rollback = TRUE;
++                      goto err;
++                      }
 +
-+/* Our internal RSA_METHOD that we provide pointers to */
-+static RSA_METHOD pk11_rsa;
++      /* LINTED: E_CONSTANT_CONDITION */
++      KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
++      if (key_ptr != NULL)
++              *key_ptr = rsa;
 +
-+RSA_METHOD *
-+PK11_RSA(void)
-+      {
-+      const RSA_METHOD *rsa;
++err:
++      if (rollback)
++              {
++              /*
++               * We do not care about the return value from C_DestroyObject()
++               * since we are doing rollback.
++               */
++              if (found == 0)
++                      (void) pFuncList->C_DestroyObject(session, h_key);
++              h_key = CK_INVALID_HANDLE;
++              }
 +
-+      if (pk11_rsa.name == NULL)
++      UNLOCK_OBJSTORE(OP_RSA);
++
++malloc_err:
++      for (i = 6; i <= 7; i++)
 +              {
-+              rsa = RSA_PKCS1_SSLeay();
-+              memcpy(&pk11_rsa, rsa, sizeof(*rsa));
-+              pk11_rsa.name = "PKCS#11 RSA method";
-+              pk11_rsa.rsa_sign = pk11_RSA_sign;
++              if (a_key_template[i].pValue != NULL)
++                      {
++                      OPENSSL_free(a_key_template[i].pValue);
++                      a_key_template[i].pValue = NULL;
++                      }
 +              }
-+      return (&pk11_rsa);
-+      }
 +
-+/* Size of an SSL signature: MD5+SHA1 */
-+#define       SSL_SIG_LENGTH          36
++      return (h_key);
++      }
 +
 +/*
-+ * Standard engine interface function. Majority codes here are from
-+ * rsa/rsa_sign.c. We replaced the decrypt function call by C_Sign of PKCS#11.
-+ * See more details in rsa/rsa_sign.c
++ * Create a private key object in the session from a given rsa structure.
++ * The *rsa_d_num pointer is non-NULL for RSA private keys.
 + */
-+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
-+      unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
++static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA *rsa,
++    RSA **key_ptr, BIGNUM **rsa_d_num, CK_SESSION_HANDLE session)
 +      {
-+      X509_SIG sig;
-+      ASN1_TYPE parameter;
-+      int i, j = 0;
-+      unsigned char *p, *s = NULL;
-+      X509_ALGOR algor;
-+      ASN1_OCTET_STRING digest;
 +      CK_RV rv;
-+      CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
-+      CK_MECHANISM *p_mech = &mech_rsa;
-+      CK_OBJECT_HANDLE h_priv_key;
-+      PK11_SESSION *sp = NULL;
-+      int ret = 0;
-+      unsigned long ulsiglen;
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      int i;
++      CK_ULONG found;
++      CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
++      CK_KEY_TYPE k_type = CKK_RSA;
++      CK_ULONG ul_key_attr_count = 14;
++      CK_BBOOL rollback = FALSE;
 +
-+      /* Encode the digest */
-+      /* Special case: SSL signature, just check the length */
-+      if (type == NID_md5_sha1)
-+              {
-+              if (m_len != SSL_SIG_LENGTH)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN,
-+                              PK11_R_INVALID_MESSAGE_LENGTH);
-+                      goto err;
-+                      }
-+              i = SSL_SIG_LENGTH;
-+              s = (unsigned char *)m;
-+              }
-+      else
++      /* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys */
++      CK_ATTRIBUTE  a_key_template[] =
 +              {
-+              sig.algor = &algor;
-+              sig.algor->algorithm = OBJ_nid2obj(type);
-+              if (sig.algor->algorithm == NULL)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN,
-+                              PK11_R_UNKNOWN_ALGORITHM_TYPE);
-+                      goto err;
-+                      }
-+              if (sig.algor->algorithm->length == 0)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN,
-+                              PK11_R_UNKNOWN_ASN1_OBJECT_ID);
-+                      goto err;
-+                      }
-+              parameter.type = V_ASN1_NULL;
-+              parameter.value.ptr = NULL;
-+              sig.algor->parameter = &parameter;
++              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
++              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
++              {CKA_TOKEN, &false, sizeof (true)},
++              {CKA_SENSITIVE, &false, sizeof (true)},
++              {CKA_DECRYPT, &true, sizeof (true)},
++              {CKA_SIGN, &true, sizeof (true)},
++              {CKA_MODULUS, (void *)NULL, 0},
++              {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
++              {CKA_PRIVATE_EXPONENT, (void *)NULL, 0},
++              {CKA_PRIME_1, (void *)NULL, 0},
++              {CKA_PRIME_2, (void *)NULL, 0},
++              {CKA_EXPONENT_1, (void *)NULL, 0},
++              {CKA_EXPONENT_2, (void *)NULL, 0},
++              {CKA_COEFFICIENT, (void *)NULL, 0}
++              };
 +
-+              sig.digest = &digest;
-+              sig.digest->data = (unsigned char *)m;
-+              sig.digest->length = m_len;
++      if ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0) {
++              h_key = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, hndidx_rsa);
++              LOCK_OBJSTORE(OP_RSA);
++              goto set;
++      }
++      
++      a_key_template[0].pValue = &o_key;
++      a_key_template[1].pValue = &k_type;
 +
-+              i = i2d_X509_SIG(&sig, NULL);
++      /* Put the private key components into the template */
++      if (init_template_value(rsa->n, &a_key_template[6].pValue,
++              &a_key_template[6].ulValueLen) == 0 ||
++          init_template_value(rsa->e, &a_key_template[7].pValue,
++              &a_key_template[7].ulValueLen) == 0 ||
++          init_template_value(rsa->d, &a_key_template[8].pValue,
++              &a_key_template[8].ulValueLen) == 0 ||
++          init_template_value(rsa->p, &a_key_template[9].pValue,
++              &a_key_template[9].ulValueLen) == 0 ||
++          init_template_value(rsa->q, &a_key_template[10].pValue,
++              &a_key_template[10].ulValueLen) == 0 ||
++          init_template_value(rsa->dmp1, &a_key_template[11].pValue,
++              &a_key_template[11].ulValueLen) == 0 ||
++          init_template_value(rsa->dmq1, &a_key_template[12].pValue,
++              &a_key_template[12].ulValueLen) == 0 ||
++          init_template_value(rsa->iqmp, &a_key_template[13].pValue,
++              &a_key_template[13].ulValueLen) == 0)
++              {
++              PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
 +              }
 +
-+      j = RSA_size(rsa);
-+      if ((i - RSA_PKCS1_PADDING) > j)
++      /* see find_lock array definition for more info on object locking */
++      LOCK_OBJSTORE(OP_RSA);
++      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
++              ul_key_attr_count);
++
++      if (rv != CKR_OK)
 +              {
-+              PK11err(PK11_F_RSA_SIGN, PK11_R_DIGEST_TOO_BIG);
++              PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
++                  PK11_R_FINDOBJECTSINIT, rv);
 +              goto err;
 +              }
 +
-+      if (type != NID_md5_sha1)
-+              {
-+              s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
-+              if (s == NULL)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN, PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
-+              p = s;
-+              (void) i2d_X509_SIG(&sig, &p);
-+              }
++      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
 +
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
++                  PK11_R_FINDOBJECTS, rv);
 +              goto err;
++              }
 +
-+      (void) check_new_rsa_key_priv(sp, rsa);
-+
-+      h_priv_key = sp->opdata_rsa_priv_key;
-+      if (h_priv_key == CK_INVALID_HANDLE)
-+              h_priv_key = sp->opdata_rsa_priv_key =
-+                      pk11_get_private_rsa_key((RSA *)rsa,
-+                          &sp->opdata_rsa_priv,
-+                          &sp->opdata_rsa_d_num, sp->session);
++      rv = pFuncList->C_FindObjectsFinal(session);
 +
-+      if (h_priv_key != CK_INVALID_HANDLE)
++      if (rv != CKR_OK)
 +              {
-+              rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
++              PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
++                  PK11_R_FINDOBJECTSFINAL, rv);
++              goto err;
++              }
 +
++      if (found == 0)
++              {
++              rv = pFuncList->C_CreateObject(session,
++                      a_key_template, ul_key_attr_count, &h_key);
 +              if (rv != CKR_OK)
 +                      {
-+                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGNINIT, rv);
++                      PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
++                              PK11_R_CREATEOBJECT, rv);
 +                      goto err;
 +                      }
++              }
 +
-+              ulsiglen = j;
-+              rv = pFuncList->C_Sign(sp->session, s, i, sigret,
-+                      (CK_ULONG_PTR) &ulsiglen);
-+              *siglen = ulsiglen;
-+
-+              if (rv != CKR_OK)
++set:
++      if (rsa_d_num != NULL)
++              {
++              if (rsa->d == NULL)
++                      *rsa_d_num = NULL;
++              else if ((*rsa_d_num = BN_dup(rsa->d)) == NULL)
 +                      {
-+                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGN, rv);
++                      PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
++                      rollback = TRUE;
 +                      goto err;
 +                      }
-+              ret = 1;
 +              }
 +
++      /* LINTED: E_CONSTANT_CONDITION */
++      KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
++      if (key_ptr != NULL)
++              *key_ptr = rsa;
++
 +err:
-+      if ((type != NID_md5_sha1) && (s != NULL))
++      if (rollback)
 +              {
-+              (void) memset(s, 0, (unsigned int)(j + 1));
-+              OPENSSL_free(s);
++              /*
++               * We do not care about the return value from C_DestroyObject()
++               * since we are doing rollback.
++               */
++              if (found == 0 &&
++                  (rsa->flags & RSA_FLAG_EXT_PKEY) == 0)
++                      (void) pFuncList->C_DestroyObject(session, h_key);
++              h_key = CK_INVALID_HANDLE;
 +              }
 +
-+      pk11_return_session(sp, OP_RSA);
-+      return (ret);
-+      }
-+
-+static int hndidx_rsa = -1;
-+
-+/* load RSA private key from a file */
-+/* ARGSUSED */
-+EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *privkey_file,
-+      UI_METHOD *ui_method, void *callback_data)
-+      {
-+      EVP_PKEY *pkey = NULL;
-+      FILE *privkey;
-+      RSA *rsa;
-+      PK11_SESSION *sp = NULL;
-+      /* everything else below needed for key by reference extension */
-+      CK_RV rv;
-+      CK_ULONG objcnt = 0;
-+      CK_BBOOL is_token = TRUE;
-+      CK_BYTE attr_data[2][1024];
-+      CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY;
-+      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
-+      extern char *pk11_pin;
-+
-+      /* we look for private keys only */
-+      CK_ATTRIBUTE search_templ[] =
-+              {
-+              {CKA_TOKEN, &is_token, sizeof(is_token)},
-+              {CKA_CLASS, &key_class, sizeof(key_class)},
-+              {CKA_LABEL, NULL, 0}
-+              };
-+
-+      /* these attributes are needed to initialize OpenSSL RSA structure */
-+      CK_ATTRIBUTE get_templ[] =
-+              {
-+              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
-+              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
-+              };
++      UNLOCK_OBJSTORE(OP_RSA);
 +
++malloc_err:
 +      /*
-+       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
++       * 6 to 13 entries in the key template are key components.
++       * They need to be freed apon exit or error.
 +       */
-+      if (strstr(privkey_file, "pkcs11:") == privkey_file)
++      for (i = 6; i <= 13; i++)
 +              {
-+              if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+                      return (NULL);
-+
-+              search_templ[2].pValue = strstr(privkey_file, ":") + 1;
-+              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
-+
-+              if (pk11_pin == NULL)
-+                      {
-+                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
-+
-+                      if (pk11_pin == NULL)
-+                              {
-+                              PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MALLOC_FAILURE);
-+                              goto err;
-+                              }
-+                      }
-+              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
-+                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
-+                      {
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_INVALID_PIN, rv);
-+                      goto err;
-+                      }
-+
-+              LOCK_OBJSTORE(OP_RSA);
-+              if ((rv = pFuncList->C_FindObjectsInit(sp->session,
-+                  search_templ, 3)) != CKR_OK)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_FINDOBJECTSINIT, rv);
-+                      goto err;
-+                      }
-+
-+              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
-+              if (rv != CKR_OK)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_FINDOBJECTS, rv);
-+                      goto err;
-+                      }
-+
-+              if (objcnt > 1)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_TOO_MANY_OBJECTS);
-+                      goto err;
-+                      }
-+
-+              if (objcnt != 1)
++              if (a_key_template[i].pValue != NULL)
 +                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_OBJECT_NOT_FOUND);
-+                      goto err;
++                      (void) memset(a_key_template[i].pValue, 0,
++                              a_key_template[i].ulValueLen);
++                      OPENSSL_free(a_key_template[i].pValue);
++                      a_key_template[i].pValue = NULL;
 +                      }
++              }
 +
-+              (void) pFuncList->C_FindObjectsFinal(sp->session);
-+              UNLOCK_OBJSTORE(OP_RSA);
-+
-+              if (hndidx_rsa == -1)
-+                      hndidx_rsa = RSA_get_ex_new_index(0,
-+                                      "pkcs11 RSA HSM key handle",
-+                                      NULL, NULL, NULL);
-+
-+              pkey = EVP_PKEY_new();
-+              if (pkey == NULL)
-+                      goto err;
++      return (h_key);
++      }
 +
-+              rsa = RSA_new_method(e);
-+              if (rsa == NULL) {
-+                      EVP_PKEY_free(pkey);
-+                      pkey = NULL;
-+                      goto err;
++/*
++ * Check for cache miss and clean the object pointer and handle
++ * in such case. Return 1 for cache hit, 0 for cache miss.
++ */
++static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa)
++      {
++      /*
++       * Provide protection against RSA structure reuse by making the
++       * check for cache hit stronger. Only public components of RSA
++       * key matter here so it is sufficient to compare them with values
++       * cached in PK11_SESSION structure.
++       */
++      if ((sp->opdata_rsa_pub != rsa) ||
++          (BN_cmp(sp->opdata_rsa_n_num, rsa->n) != 0) ||
++          (BN_cmp(sp->opdata_rsa_e_num, rsa->e) != 0))
++              {
++              /*
++               * We do not check the return value because even in case of
++               * failure the sp structure will have both key pointer
++               * and object handle cleaned and pk11_destroy_object()
++               * reports the failure to the OpenSSL error message buffer.
++               */
++              (void) pk11_destroy_rsa_object_pub(sp, TRUE);
++              return (0);
 +              }
-+              EVP_PKEY_set1_RSA(pkey, rsa);
-+
-+              if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
-+                  get_templ, 2)) != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_GETATTRIBUTVALUE, rv);
-+                      EVP_PKEY_free(pkey);
-+                      pkey = NULL;
-+                      goto err;
-+                      }
-+
-+              /* Note: these flags are critical! */
-+              rsa->flags = RSA_FLAG_SIGN_VER | RSA_FLAG_EXT_PKEY;
-+              RSA_set_ex_data(rsa, hndidx_rsa, (void *) ks_key);
-+              (void) check_new_rsa_key_priv(sp, rsa);
-+              sp->opdata_rsa_priv = rsa;
-+              sp->opdata_rsa_priv_key = ks_key;
++      return (1);
++      }
 +
-+              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
-+              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
-+              }
-+      else if ((privkey = fopen(privkey_file, read_mode_flags)) != NULL)
++/*
++ * Check for cache miss and clean the object pointer and handle
++ * in such case. Return 1 for cache hit, 0 for cache miss.
++ */
++static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa)
++      {
++      /*
++       * Provide protection against RSA structure reuse by making the
++       * check for cache hit stronger. Comparing private exponent of RSA
++       * key with value cached in PK11_SESSION structure should
++       * be sufficient.
++       */
++      if ((sp->opdata_rsa_priv != rsa) ||
++          (BN_cmp(sp->opdata_rsa_d_num, rsa->d) != 0) ||
++          ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0))
 +              {
-+              pkey = PEM_read_PrivateKey(privkey, NULL, NULL, NULL);
-+              (void) fclose(privkey);
++              /*
++               * We do not check the return value because even in case of
++               * failure the sp structure will have both key pointer
++               * and object handle cleaned and pk11_destroy_object()
++               * reports the failure to the OpenSSL error message buffer.
++               */
++              (void) pk11_destroy_rsa_object_priv(sp, TRUE);
++              return (0);
 +              }
++      return (1);
++      }
++#endif
 +
-+err:
-+      if (sp != NULL)
-+              pk11_return_session(sp, OP_RSA);
-+      return (pkey);
++#ifndef OPENSSL_NO_DSA
++/* The DSA function implementation */
++/* ARGSUSED */
++static int pk11_DSA_init(DSA *dsa)
++      {
++      return (1);
 +      }
 +
-+/* load RSA public key from a file */
 +/* ARGSUSED */
-+EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data)
++static int pk11_DSA_finish(DSA *dsa)
 +      {
-+      EVP_PKEY *pkey = NULL;
-+      FILE *pubkey;
-+      RSA *rsa;
-+      PK11_SESSION *sp = NULL;
-+      /* everything else below needed for key by reference extension */
-+      CK_RV rv;
-+      CK_ULONG objcnt = 0;
-+      CK_BBOOL is_token = TRUE;
-+      CK_BYTE attr_data[2][1024];
-+      CK_OBJECT_CLASS key_class = CKO_PUBLIC_KEY;
-+      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
-+      extern char *pk11_pin;
++      return (1);
++      }
 +
-+      /* we look for public keys only */
-+      CK_ATTRIBUTE search_templ[] =
-+              {
-+              {CKA_TOKEN, &is_token, sizeof(is_token)},
-+              {CKA_CLASS, &key_class, sizeof(key_class)},
-+              {CKA_LABEL, NULL, 0}
-+              };
 +
-+      /* these attributes are needed to initialize OpenSSL RSA structure */
-+      CK_ATTRIBUTE get_templ[] =
-+              {
-+              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
-+              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
-+              };
++static DSA_SIG *
++pk11_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
++      {
++      BIGNUM *r = NULL, *s = NULL;
++      int i;
++      DSA_SIG *dsa_sig = NULL;
++
++      CK_RV rv;
++      CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
++      CK_MECHANISM *p_mech = &Mechanism_dsa;
++      CK_OBJECT_HANDLE h_priv_key;
 +
 +      /*
-+       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
++       * The signature is the concatenation of r and s,
++       * each is 20 bytes long
 +       */
-+      if (strstr(pubkey_file, "pkcs11:") == pubkey_file)
++      unsigned char sigret[DSA_SIGNATURE_LEN];
++      unsigned long siglen = DSA_SIGNATURE_LEN;
++      unsigned int siglen2 = DSA_SIGNATURE_LEN / 2;
++
++      PK11_SESSION *sp = NULL;
++
++      if ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))
 +              {
-+              if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+                      return (NULL);
++              PK11err(PK11_F_DSA_SIGN, PK11_R_MISSING_KEY_COMPONENT);
++              goto ret;
++              }
 +
-+              search_templ[2].pValue = strstr(pubkey_file, ":") + 1;
-+              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
++      i = BN_num_bytes(dsa->q); /* should be 20 */
++      if (dlen > i)
++              {
++              PK11err(PK11_F_DSA_SIGN, PK11_R_INVALID_SIGNATURE_LENGTH);
++              goto ret;
++              }
 +
-+#define ALLWAYS_LOGIN
-+#ifdef ALLWAYS_LOGIN
-+              if (pk11_pin == NULL)
-+                      {
-+                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
++      if ((sp = pk11_get_session(OP_DSA)) == NULL)
++              goto ret;
 +
-+                      if (pk11_pin == NULL)
-+                              {
-+                              PK11err(PK11_F_LOAD_PUBKEY, PK11_R_MALLOC_FAILURE);
-+                              goto err;
-+                              }
-+                      }
-+              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
-+                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
-+                      {
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_INVALID_PIN, rv);
-+                      goto err;
-+                      }
-+#endif
++      (void) check_new_dsa_key_priv(sp, dsa);
++
++      h_priv_key = sp->opdata_dsa_priv_key;
++      if (h_priv_key == CK_INVALID_HANDLE)
++              h_priv_key = sp->opdata_dsa_priv_key =
++                      pk11_get_private_dsa_key((DSA *)dsa,
++                          &sp->opdata_dsa_priv,
++                          &sp->opdata_dsa_priv_num, sp->session);
++
++      if (h_priv_key != CK_INVALID_HANDLE)
++              {
++              rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
 +
-+              LOCK_OBJSTORE(OP_RSA);
-+              if (pFuncList->C_FindObjectsInit(sp->session, search_templ, 3) != CKR_OK)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_FINDOBJECTSINIT, rv);
-+                      goto err;
-+                      }
-+              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
 +              if (rv != CKR_OK)
 +                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_FINDOBJECTS, rv);
-+                      goto err;
++                      PK11err_add_data(PK11_F_DSA_SIGN, PK11_R_SIGNINIT, rv);
++                      goto ret;
 +                      }
 +
-+              if (objcnt > 1)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_TOO_MANY_OBJECTS);
-+                      goto err;
-+                      }
++              (void) memset(sigret, 0, siglen);
++              rv = pFuncList->C_Sign(sp->session,
++                      (unsigned char*) dgst, dlen, sigret,
++                      (CK_ULONG_PTR) &siglen);
 +
-+              if (objcnt != 1)
++              if (rv != CKR_OK)
 +                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_OBJECT_NOT_FOUND);
-+                      goto err;
++                      PK11err_add_data(PK11_F_DSA_SIGN, PK11_R_SIGN, rv);
++                      goto ret;
 +                      }
-+
-+              (void) pFuncList->C_FindObjectsFinal(sp->session);
-+              UNLOCK_OBJSTORE(OP_RSA);
-+
-+              sp->opdata_rsa_pub_key = ks_key;
-+              pkey = EVP_PKEY_new();
-+              if (pkey == NULL)
-+                      goto err;
-+
-+              rsa = RSA_new_method(e);
-+              if (rsa == NULL) {
-+                      EVP_PKEY_free(pkey);
-+                      pkey = NULL;
-+                      goto err;
 +              }
-+              EVP_PKEY_set1_RSA(pkey, rsa);
 +
-+              if (pFuncList->C_GetAttributeValue(sp->session, ks_key,
-+                  get_templ, 2) != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_GETATTRIBUTVALUE, rv);
-+                      goto err;
-+                      }
 +
-+              (void) check_new_rsa_key_pub(sp, rsa);
-+              sp->opdata_rsa_pub = rsa;
++      if ((s = BN_new()) == NULL)
++              {
++              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
++              goto ret;
++              }
 +
-+              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
-+              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
++      if ((r = BN_new()) == NULL)
++              {
++              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
++              goto ret;
 +              }
-+      else if ((pubkey = fopen(pubkey_file, read_mode_flags)) != NULL)
++
++      if ((dsa_sig = DSA_SIG_new()) == NULL)
 +              {
-+              pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
-+              (void) fclose(pubkey);
++              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
++              goto ret;
 +              }
 +
-+err:
-+      if (sp != NULL)
-+              pk11_return_session(sp, OP_RSA);
-+      return (pkey);
-+      }
++      if (BN_bin2bn(sigret, siglen2, r) == NULL ||
++          BN_bin2bn(&sigret[siglen2], siglen2, s) == NULL)
++              {
++              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
++              goto ret;
++              }
 +
-+/*
-+ * Create a private key object in the session from a given rsa structure.
-+ * The *rsa_d_num pointer is non-NULL for RSA private keys.
-+ */
-+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA *rsa,
-+    RSA **key_ptr, BIGNUM **rsa_d_num, CK_SESSION_HANDLE session)
-+      {
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      dsa_sig->r = r;
++      dsa_sig->s = s;
 +
-+      if ((rsa->flags & RSA_FLAG_EXT_PKEY) == 0) {
-+              PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_INCONSISTENT_KEY);
-+              return (h_key);
-+      }
-+      
-+      h_key = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, hndidx_rsa);
-+      (void) pk11_active_add(h_key, OP_RSA);
-+      if (key_ptr != NULL)
-+              *key_ptr = rsa;
-+      if (rsa_d_num != NULL)
++ret:
++      if (dsa_sig == NULL)
 +              {
-+              if (rsa->d == NULL)
-+                      *rsa_d_num = NULL;
-+              else if ((*rsa_d_num = BN_dup(rsa->d)) == NULL)
-+                      {
-+                      PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
-+                      return (h_key);
-+                      }
++              if (r != NULL)
++                      BN_free(r);
++              if (s != NULL)
++                      BN_free(s);
 +              }
-+      return (h_key);
++
++      pk11_return_session(sp, OP_DSA);
++      return (dsa_sig);
 +      }
 +
-+/*
-+ * Check for cache miss and clean the object pointer and handle
-+ * in such case. Return 1 for cache hit, 0 for cache miss.
-+ */
-+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa)
++static int
++pk11_dsa_do_verify(const unsigned char *dgst, int dlen, DSA_SIG *sig,
++      DSA *dsa)
 +      {
-+      /*
-+       * Provide protection against RSA structure reuse by making the
-+       * check for cache hit stronger. Only public components of RSA
-+       * key matter here so it is sufficient to compare them with values
-+       * cached in PK11_SESSION structure.
-+       */
-+      if ((sp->opdata_rsa_pub != rsa) ||
-+          (BN_cmp(sp->opdata_rsa_n_num, rsa->n) != 0) ||
-+          (BN_cmp(sp->opdata_rsa_e_num, rsa->e) != 0))
++      int i;
++      CK_RV rv;
++      int retval = 0;
++      CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
++      CK_MECHANISM *p_mech = &Mechanism_dsa;
++      CK_OBJECT_HANDLE h_pub_key;
++
++      unsigned char sigbuf[DSA_SIGNATURE_LEN];
++      unsigned long siglen = DSA_SIGNATURE_LEN;
++      unsigned long siglen2 = DSA_SIGNATURE_LEN/2;
++
++      PK11_SESSION *sp = NULL;
++
++      if (BN_is_zero(sig->r) || sig->r->neg || BN_ucmp(sig->r, dsa->q) >= 0)
 +              {
-+              /*
-+               * We do not check the return value because even in case of
-+               * failure the sp structure will have both key pointer
-+               * and object handle cleaned and pk11_destroy_object()
-+               * reports the failure to the OpenSSL error message buffer.
-+               */
-+              (void) pk11_destroy_rsa_object_pub(sp, TRUE);
-+              return (0);
++              PK11err(PK11_F_DSA_VERIFY,
++                      PK11_R_INVALID_DSA_SIGNATURE_R);
++              goto ret;
 +              }
-+      return (1);
-+      }
 +
-+/*
-+ * Check for cache miss and clean the object pointer and handle
-+ * in such case. Return 1 for cache hit, 0 for cache miss.
-+ */
-+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa)
-+      {
-+      /*
-+       * Provide protection against RSA structure reuse by making the
-+       * check for cache hit stronger. Comparing private exponent of RSA
-+       * key with value cached in PK11_SESSION structure should
-+       * be sufficient.
-+       */
-+      if ((sp->opdata_rsa_priv != rsa) ||
-+          (BN_cmp(sp->opdata_rsa_d_num, rsa->d) != 0) ||
-+          ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0))
++      if (BN_is_zero(sig->s) || sig->s->neg || BN_ucmp(sig->s, dsa->q) >= 0)
 +              {
-+              /*
-+               * We do not check the return value because even in case of
-+               * failure the sp structure will have both key pointer
-+               * and object handle cleaned and pk11_destroy_object()
-+               * reports the failure to the OpenSSL error message buffer.
-+               */
-+              (void) pk11_destroy_rsa_object_priv(sp, TRUE);
-+              return (0);
++              PK11err(PK11_F_DSA_VERIFY,
++                      PK11_R_INVALID_DSA_SIGNATURE_S);
++              goto ret;
 +              }
-+      return (1);
-+      }
 +
-+static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn)
-+      {
-+      if (attr->ulValueLen > 0)
++      i = BN_num_bytes(dsa->q); /* should be 20 */
++
++      if (dlen > i)
 +              {
-+              *bn = BN_bin2bn(attr_data, attr->ulValueLen, NULL);
++              PK11err(PK11_F_DSA_VERIFY,
++                      PK11_R_INVALID_SIGNATURE_LENGTH);
++              goto ret;
 +              }
-+      }
 +
-+#ifdef        OPENSSL_SYS_WIN32
-+char *getpassphrase(const char *prompt)
-+      {
-+      static char buf[128];
-+      HANDLE h;
-+      DWORD cc, mode;
-+      int cnt;
++      if ((sp = pk11_get_session(OP_DSA)) == NULL)
++              goto ret;
 +
-+      h = GetStdHandle(STD_INPUT_HANDLE);
-+      fputs(prompt, stderr);
-+      fflush(stderr);
-+      fflush(stdout);
-+      FlushConsoleInputBuffer(h);
-+      GetConsoleMode(h, &mode);
-+      SetConsoleMode(h, ENABLE_PROCESSED_INPUT);
++      (void) check_new_dsa_key_pub(sp, dsa);
 +
-+      for (cnt = 0; cnt < sizeof(buf) - 1; cnt++)
++      h_pub_key = sp->opdata_dsa_pub_key;
++      if (h_pub_key == CK_INVALID_HANDLE)
++              h_pub_key = sp->opdata_dsa_pub_key =
++                      pk11_get_public_dsa_key((DSA *)dsa, &sp->opdata_dsa_pub,
++                          &sp->opdata_dsa_pub_num, sp->session);
++
++      if (h_pub_key != CK_INVALID_HANDLE)
 +              {
-+              ReadFile(h, buf + cnt, 1, &cc, NULL);
-+              if (buf[cnt] == '\r')
-+                      break;
-+              fputc('*', stdout);
-+              fflush(stderr);
-+              fflush(stdout);
++              rv = pFuncList->C_VerifyInit(sp->session, p_mech,
++                      h_pub_key);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_DSA_VERIFY, PK11_R_VERIFYINIT,
++                          rv);
++                      goto ret;
++                      }
++
++              /*
++               * The representation of each of the two big numbers could
++               * be shorter than DSA_SIGNATURE_LEN/2 bytes so we need
++               * to act accordingly and shift if necessary.
++               */
++              (void) memset(sigbuf, 0, siglen);
++              BN_bn2bin(sig->r, sigbuf + siglen2 - BN_num_bytes(sig->r));
++              BN_bn2bin(sig->s, &sigbuf[siglen2] + siglen2 -
++                  BN_num_bytes(sig->s));
++
++              rv = pFuncList->C_Verify(sp->session,
++                      (unsigned char *) dgst, dlen, sigbuf, (CK_ULONG)siglen);
++
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_DSA_VERIFY, PK11_R_VERIFY, rv);
++                      goto ret;
++                      }
 +              }
 +
-+      SetConsoleMode(h, mode);
-+      buf[cnt] = '\0';
-+      fputs("\n", stderr);
-+      return buf;
++      retval = 1;
++ret:
++
++      pk11_return_session(sp, OP_DSA);
++      return (retval);
 +      }
-+#endif        /* OPENSSL_SYS_WIN32 */
-+#endif        /* OPENSSL_NO_HW_PK11 */
-+#endif        /* OPENSSL_NO_HW */
-Index: openssl/crypto/engine/hw_pk11_pub.c
-diff -u /dev/null openssl/crypto/engine/hw_pk11_pub.c:1.31
---- /dev/null  Mon Oct  5 11:08:14 2009
-+++ openssl/crypto/engine/hw_pk11_pub.c        Fri Aug 28 06:31:09 2009
-@@ -0,0 +1,3137 @@
-+/*
-+ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
-+ * Use is subject to license terms.
-+ */
 +
-+/* crypto/engine/hw_pk11_pub.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).
-+ *
++ * Create a public key object in a session from a given dsa structure.
++ * The *dsa_pub_num pointer is non-NULL for DSA public keys.
 + */
++static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa,
++    DSA **key_ptr, BIGNUM **dsa_pub_num, CK_SESSION_HANDLE session)
++      {
++      CK_RV rv;
++      CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      CK_ULONG found;
++      CK_KEY_TYPE k_type = CKK_DSA;
++      CK_ULONG ul_key_attr_count = 8;
++      CK_BBOOL rollback = FALSE;
++      int i;
 +
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <string.h>
-+#include <sys/types.h>
++      CK_ATTRIBUTE  a_key_template[] =
++              {
++              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
++              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
++              {CKA_TOKEN, &false, sizeof (true)},
++              {CKA_VERIFY, &true, sizeof (true)},
++              {CKA_PRIME, (void *)NULL, 0},           /* p */
++              {CKA_SUBPRIME, (void *)NULL, 0},        /* q */
++              {CKA_BASE, (void *)NULL, 0},            /* g */
++              {CKA_VALUE, (void *)NULL, 0}            /* pub_key - y */
++              };
 +
-+#include <openssl/e_os2.h>
-+#include <openssl/crypto.h>
-+#include <cryptlib.h>
-+#include <openssl/engine.h>
-+#include <openssl/dso.h>
-+#include <openssl/err.h>
-+#include <openssl/bn.h>
-+#include <openssl/pem.h>
-+#ifndef OPENSSL_NO_RSA
-+#include <openssl/rsa.h>
-+#endif /* OPENSSL_NO_RSA */
-+#ifndef OPENSSL_NO_DSA
-+#include <openssl/dsa.h>
-+#endif /* OPENSSL_NO_DSA */
-+#ifndef OPENSSL_NO_DH
-+#include <openssl/dh.h>
-+#endif /* OPENSSL_NO_DH */
-+#include <openssl/rand.h>
-+#include <openssl/objects.h>
-+#include <openssl/x509.h>
++      a_key_template[0].pValue = &o_key;
++      a_key_template[1].pValue = &k_type;
 +
-+#ifdef OPENSSL_SYS_WIN32
-+#define NOPTHREADS
-+typedef int pid_t;
-+#define HAVE_GETPASSPHRASE
-+static char *getpassphrase(const char *prompt);
-+#ifndef NULL_PTR
-+#define NULL_PTR NULL
-+#endif
-+#define CK_DEFINE_FUNCTION(returnType, name) \
-+      returnType __declspec(dllexport) name
-+#define CK_DECLARE_FUNCTION(returnType, name) \
-+      returnType __declspec(dllimport) name
-+#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
-+      returnType __declspec(dllimport) (* name)
-+#else
-+#include <unistd.h>
-+#endif
++      if (init_template_value(dsa->p, &a_key_template[4].pValue,
++              &a_key_template[4].ulValueLen) == 0 ||
++          init_template_value(dsa->q, &a_key_template[5].pValue,
++              &a_key_template[5].ulValueLen) == 0 ||
++          init_template_value(dsa->g, &a_key_template[6].pValue,
++              &a_key_template[6].ulValueLen) == 0 ||
++          init_template_value(dsa->pub_key, &a_key_template[7].pValue,
++              &a_key_template[7].ulValueLen) == 0)
++              {
++              PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
++              }
 +
-+#ifndef NOPTHREADS
-+#include <pthread.h>
-+#endif
++      /* see find_lock array definition for more info on object locking */
++      LOCK_OBJSTORE(OP_DSA);
++      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
++              ul_key_attr_count);
 +
-+#ifndef OPENSSL_NO_HW
-+#ifndef OPENSSL_NO_HW_PK11
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PUB_DSA_KEY, PK11_R_FINDOBJECTSINIT,
++                  rv);
++              goto err;
++              }
 +
-+#ifdef OPENSSL_SYS_WIN32
-+#pragma pack(push, cryptoki, 1)
-+#include "cryptoki.h"
-+#include "pkcs11.h"
-+#pragma pack(pop, cryptoki)
-+#else
-+#include "cryptoki.h"
-+#include "pkcs11.h"
-+#endif
-+#include "hw_pk11_err.h"
++      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
 +
-+#if !(defined(HAVE_GETPASSPHRASE) || (defined (__SVR4) && defined (__sun)))
-+#define getpassphrase(x)      getpass(x)
-+#endif
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
++                  PK11_R_FINDOBJECTS, rv);
++              goto err;
++              }
 +
-+#ifndef OPENSSL_NO_RSA
-+/* RSA stuff */
-+static int pk11_RSA_public_encrypt(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa, int padding);
-+static int pk11_RSA_private_encrypt(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa, int padding);
-+static int pk11_RSA_public_decrypt(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa, int padding);
-+static int pk11_RSA_private_decrypt(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa, int padding);
-+static int pk11_RSA_init(RSA *rsa);
-+static int pk11_RSA_finish(RSA *rsa);
-+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
-+      unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
-+static int pk11_RSA_verify(int dtype, const unsigned char *m,
-+      unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
-+      const RSA *rsa);
-+EVP_PKEY *pk11_load_privkey(ENGINE*, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data);
-+EVP_PKEY *pk11_load_pubkey(ENGINE*, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data);
++      rv = pFuncList->C_FindObjectsFinal(session);
 +
-+static int pk11_RSA_public_encrypt_low(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa);
-+static int pk11_RSA_private_encrypt_low(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa);
-+static int pk11_RSA_public_decrypt_low(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa);
-+static int pk11_RSA_private_decrypt_low(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa);
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
++                  PK11_R_FINDOBJECTSFINAL, rv);
++              goto err;
++              }
 +
-+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA* rsa, RSA** key_ptr,
-+      BIGNUM **rsa_n_num, BIGNUM **rsa_e_num, CK_SESSION_HANDLE session);
-+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, RSA** key_ptr,
-+      BIGNUM **rsa_d_num, CK_SESSION_HANDLE session);
++      if (found == 0)
++              {
++              rv = pFuncList->C_CreateObject(session,
++                      a_key_template, ul_key_attr_count, &h_key);
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
++                          PK11_R_CREATEOBJECT, rv);
++                      goto err;
++                      }
++              }
 +
-+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa);
-+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa);
-+#endif
++      if (dsa_pub_num != NULL)
++              if ((*dsa_pub_num = BN_dup(dsa->pub_key)) == NULL)
++                      {
++                      PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_MALLOC_FAILURE);
++                      rollback = TRUE;
++                      goto err;
++                      }
 +
-+/* DSA stuff */
-+#ifndef OPENSSL_NO_DSA
-+static int pk11_DSA_init(DSA *dsa);
-+static int pk11_DSA_finish(DSA *dsa);
-+static DSA_SIG *pk11_dsa_do_sign(const unsigned char *dgst, int dlen,
-+      DSA *dsa);
-+static int pk11_dsa_do_verify(const unsigned char *dgst, int dgst_len,
-+      DSA_SIG *sig, DSA *dsa);
++      /* LINTED: E_CONSTANT_CONDITION */
++      KEY_HANDLE_REFHOLD(h_key, OP_DSA, FALSE, rollback, err);
++      if (key_ptr != NULL)
++              *key_ptr = dsa;
 +
-+static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa, DSA **key_ptr,
-+      BIGNUM **dsa_pub_num, CK_SESSION_HANDLE session);
-+static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa, DSA **key_ptr,
-+      BIGNUM **dsa_priv_num, CK_SESSION_HANDLE session);
++err:
++      if (rollback)
++              {
++              /*
++               * We do not care about the return value from C_DestroyObject()
++               * since we are doing rollback.
++               */
++              if (found == 0)
++                      (void) pFuncList->C_DestroyObject(session, h_key);
++              h_key = CK_INVALID_HANDLE;
++              }
 +
-+static int check_new_dsa_key_pub(PK11_SESSION *sp, DSA *dsa);
-+static int check_new_dsa_key_priv(PK11_SESSION *sp, DSA *dsa);
-+#endif
++      UNLOCK_OBJSTORE(OP_DSA);
 +
-+/* DH stuff */
-+#ifndef OPENSSL_NO_DH
-+static int pk11_DH_init(DH *dh);
-+static int pk11_DH_finish(DH *dh);
-+static int pk11_DH_generate_key(DH *dh);
-+static int pk11_DH_compute_key(unsigned char *key,
-+      const BIGNUM *pub_key, DH *dh);
++malloc_err:
++      for (i = 4; i <= 7; i++)
++              {
++              if (a_key_template[i].pValue != NULL)
++                      {
++                      OPENSSL_free(a_key_template[i].pValue);
++                      a_key_template[i].pValue = NULL;
++                      }
++              }
++
++      return (h_key);
++      }
++
++/*
++ * Create a private key object in the session from a given dsa structure
++ * The *dsa_priv_num pointer is non-NULL for DSA private keys.
++ */
++static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa,
++    DSA **key_ptr, BIGNUM **dsa_priv_num, CK_SESSION_HANDLE session)
++      {
++      CK_RV rv;
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
++      int i;
++      CK_ULONG found;
++      CK_KEY_TYPE k_type = CKK_DSA;
++      CK_ULONG ul_key_attr_count = 9;
++      CK_BBOOL rollback = FALSE;
++
++      /* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys */
++      CK_ATTRIBUTE  a_key_template[] =
++              {
++              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
++              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
++              {CKA_TOKEN, &false, sizeof (true)},
++              {CKA_SENSITIVE, &false, sizeof (true)},
++              {CKA_SIGN, &true, sizeof (true)},
++              {CKA_PRIME, (void *)NULL, 0},           /* p */
++              {CKA_SUBPRIME, (void *)NULL, 0},        /* q */
++              {CKA_BASE, (void *)NULL, 0},            /* g */
++              {CKA_VALUE, (void *)NULL, 0}            /* priv_key - x */
++              };
++
++      a_key_template[0].pValue = &o_key;
++      a_key_template[1].pValue = &k_type;
++
++      /* Put the private key components into the template */
++      if (init_template_value(dsa->p, &a_key_template[5].pValue,
++              &a_key_template[5].ulValueLen) == 0 ||
++          init_template_value(dsa->q, &a_key_template[6].pValue,
++              &a_key_template[6].ulValueLen) == 0 ||
++          init_template_value(dsa->g, &a_key_template[7].pValue,
++              &a_key_template[7].ulValueLen) == 0 ||
++          init_template_value(dsa->priv_key, &a_key_template[8].pValue,
++              &a_key_template[8].ulValueLen) == 0)
++              {
++              PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
++              }
 +
-+static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh, DH **key_ptr,
-+      BIGNUM **priv_key, CK_SESSION_HANDLE session);
++      /* see find_lock array definition for more info on object locking */
++      LOCK_OBJSTORE(OP_DSA);
++      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
++              ul_key_attr_count);
 +
-+static int check_new_dh_key(PK11_SESSION *sp, DH *dh);
-+#endif
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
++                  PK11_R_FINDOBJECTSINIT, rv);
++              goto err;
++              }
 +
-+static int init_template_value(BIGNUM *bn, CK_VOID_PTR *pValue,
-+      CK_ULONG *ulValueLen);
-+static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn);
++      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
 +
-+/* Read mode string to be used for fopen() */
-+#if SOLARIS_OPENSSL
-+static char *read_mode_flags = "rF";
-+#else
-+static char *read_mode_flags = "r";
-+#endif
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
++                  PK11_R_FINDOBJECTS, rv);
++              goto err;
++              }
 +
-+/*
-+ * increment/create reference for an asymmetric key handle via active list
-+ * manipulation. If active list operation fails, unlock (if locked), set error
-+ * variable and jump to the specified label.
-+ */
-+#define       KEY_HANDLE_REFHOLD(key_handle, alg_type, unlock, var, label)    \
-+      {                                                               \
-+      if (pk11_active_add(key_handle, alg_type) < 0)                  \
-+              {                                                       \
-+              var = TRUE;                                             \
-+              if (unlock)                                             \
-+                      UNLOCK_OBJSTORE(alg_type);                      \
-+              goto label;                                             \
-+              }                                                       \
-+      }
++      rv = pFuncList->C_FindObjectsFinal(session);
 +
-+/*
-+ * Find active list entry according to object handle and return pointer to the
-+ * entry otherwise return NULL.
-+ *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
-+ */
-+static PK11_active *pk11_active_find(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
-+      {
-+      PK11_active *entry;
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
++                  PK11_R_FINDOBJECTSFINAL, rv);
++              goto err;
++              }
 +
-+      for (entry = active_list[type]; entry != NULL; entry = entry->next)
-+              if (entry->h == h)
-+                      return (entry);
++      if (found == 0)
++              {
++              rv = pFuncList->C_CreateObject(session,
++                      a_key_template, ul_key_attr_count, &h_key);
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
++                          PK11_R_CREATEOBJECT, rv);
++                      goto err;
++                      }
++              }
 +
-+      return (NULL);
-+      }
++      if (dsa_priv_num != NULL)
++              if ((*dsa_priv_num = BN_dup(dsa->priv_key)) == NULL)
++                      {
++                      PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_MALLOC_FAILURE);
++                      rollback = TRUE;
++                      goto err;
++                      }
 +
-+/*
-+ * Search for an entry in the active list using PKCS#11 object handle as a
-+ * search key and return refcnt of the found/created entry or -1 in case of
-+ * failure.
-+ *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
-+ */
-+int
-+pk11_active_add(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
-+      {
-+      PK11_active *entry = NULL;
++      /* LINTED: E_CONSTANT_CONDITION */
++      KEY_HANDLE_REFHOLD(h_key, OP_DSA, FALSE, rollback, err);
++      if (key_ptr != NULL)
++              *key_ptr = dsa;
 +
-+      if (h == CK_INVALID_HANDLE)
++err:
++      if (rollback)
 +              {
-+              PK11err(PK11_F_ACTIVE_ADD, PK11_R_INVALID_HANDLE);
-+              return (-1);
++              /*
++               * We do not care about the return value from C_DestroyObject()
++               * since we are doing rollback.
++               */
++              if (found == 0)
++                      (void) pFuncList->C_DestroyObject(session, h_key);
++              h_key = CK_INVALID_HANDLE;
 +              }
 +
-+      /* search for entry in the active list */
-+      if ((entry = pk11_active_find(h, type)) != NULL)
-+              entry->refcnt++;
-+      else
++      UNLOCK_OBJSTORE(OP_DSA);
++
++malloc_err:
++      /*
++       * 5 to 8 entries in the key template are key components.
++       * They need to be freed apon exit or error.
++       */
++      for (i = 5; i <= 8; i++)
 +              {
-+              /* not found, create new entry and add it to the list */
-+              entry = OPENSSL_malloc(sizeof (PK11_active));
-+              if (entry == NULL)
-+                      {
-+                      PK11err(PK11_F_ACTIVE_ADD, PK11_R_MALLOC_FAILURE);
-+                      return (-1);
-+                      }
-+              entry->h = h;
-+              entry->refcnt = 1;
-+              entry->prev = NULL;
-+              entry->next = NULL;
-+              /* connect the newly created entry to the list */
-+              if (active_list[type] == NULL)
-+                      active_list[type] = entry;
-+              else /* make the entry first in the list */
++              if (a_key_template[i].pValue != NULL)
 +                      {
-+                      entry->next = active_list[type];
-+                      active_list[type]->prev = entry;
-+                      active_list[type] = entry;
++                      (void) memset(a_key_template[i].pValue, 0,
++                              a_key_template[i].ulValueLen);
++                      OPENSSL_free(a_key_template[i].pValue);
++                      a_key_template[i].pValue = NULL;
 +                      }
 +              }
 +
-+      return (entry->refcnt);
++      return (h_key);
 +      }
 +
 +/*
-+ * Remove active list entry from the list and free it.
-+ *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
++ * Check for cache miss and clean the object pointer and handle
++ * in such case. Return 1 for cache hit, 0 for cache miss.
 + */
-+void
-+pk11_active_remove(PK11_active *entry, PK11_OPTYPE type)
++static int check_new_dsa_key_pub(PK11_SESSION *sp, DSA *dsa)
 +      {
-+      PK11_active *prev_entry;
-+
-+      /* remove the entry from the list and free it */
-+      if ((prev_entry = entry->prev) != NULL)
-+              {
-+              prev_entry->next = entry->next;
-+              if (entry->next != NULL)
-+                      entry->next->prev = prev_entry;
-+              }
-+      else
++      /*
++       * Provide protection against DSA structure reuse by making the
++       * check for cache hit stronger. Only public key component of DSA
++       * key matters here so it is sufficient to compare it with value
++       * cached in PK11_SESSION structure.
++       */
++      if ((sp->opdata_dsa_pub != dsa) ||
++          (BN_cmp(sp->opdata_dsa_pub_num, dsa->pub_key) != 0))
 +              {
-+              active_list[type] = entry->next;
-+              /* we were the first but not the only one */
-+              if (entry->next != NULL)
-+                      entry->next->prev = NULL;
++              /*
++               * We do not check the return value because even in case of
++               * failure the sp structure will have both key pointer
++               * and object handle cleaned and pk11_destroy_object()
++               * reports the failure to the OpenSSL error message buffer.
++               */
++              (void) pk11_destroy_dsa_object_pub(sp, TRUE);
++              return (0);
 +              }
-+
-+      /* sanitization */
-+      entry->h = CK_INVALID_HANDLE;
-+      entry->prev = NULL;
-+      entry->next = NULL;
-+      OPENSSL_free(entry);
++      return (1);
 +      }
 +
-+/* Free all entries from the active list. */
-+void
-+pk11_free_active_list(PK11_OPTYPE type)
++/*
++ * Check for cache miss and clean the object pointer and handle
++ * in such case. Return 1 for cache hit, 0 for cache miss.
++ */
++static int check_new_dsa_key_priv(PK11_SESSION *sp, DSA *dsa)
 +      {
-+      PK11_active *entry;
-+
-+      /* only for asymmetric types since only they have C_Find* locks. */
-+      switch (type)
++      /*
++       * Provide protection against DSA structure reuse by making the
++       * check for cache hit stronger. Only private key component of DSA
++       * key matters here so it is sufficient to compare it with value
++       * cached in PK11_SESSION structure.
++       */
++      if ((sp->opdata_dsa_priv != dsa) ||
++          (BN_cmp(sp->opdata_dsa_priv_num, dsa->priv_key) != 0))
 +              {
-+              case OP_RSA:
-+              case OP_DSA:
-+              case OP_DH:
-+                      break;
-+              default:
-+                      return;
++              /*
++               * We do not check the return value because even in case of
++               * failure the sp structure will have both key pointer
++               * and object handle cleaned and pk11_destroy_object()
++               * reports the failure to the OpenSSL error message buffer.
++               */
++              (void) pk11_destroy_dsa_object_priv(sp, TRUE);
++              return (0);
 +              }
++      return (1);
++      }
++#endif
 +
-+      /* see find_lock array definition for more info on object locking */
-+      LOCK_OBJSTORE(type);
-+      while ((entry = active_list[type]) != NULL)
-+              pk11_active_remove(entry, type);
-+      UNLOCK_OBJSTORE(type);
++
++#ifndef OPENSSL_NO_DH
++/* The DH function implementation */
++/* ARGSUSED */
++static int pk11_DH_init(DH *dh)
++      {
++      return (1);
++      }
++
++/* ARGSUSED */
++static int pk11_DH_finish(DH *dh)
++      {
++      return (1);
 +      }
 +
 +/*
-+ * Search for active list entry associated with given PKCS#11 object handle,
-+ * decrement its refcnt and if it drops to 0, disconnect the entry and free it.
-+ *
-+ * Return 1 if the PKCS#11 object associated with the entry has no references,
-+ * return 0 if there is at least one reference, -1 on error.
++ * Generate DH key-pair.
 + *
-+ * This function presumes it is called with lock protecting the active list
-+ * held.
++ * Warning: Unlike OpenSSL's DH_generate_key(3) we ignore dh->priv_key
++ * and override it even if it is set. OpenSSL does not touch dh->priv_key
++ * if set and just computes dh->pub_key. It looks like PKCS#11 standard
++ * is not capable of providing this functionality. This could be a problem
++ * for applications relying on OpenSSL's semantics.
 + */
-+int
-+pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
++static int pk11_DH_generate_key(DH *dh)
 +      {
-+      PK11_active *entry = NULL;
++      CK_ULONG i;
++      CK_RV rv, rv1;
++      int reuse_mem_len = 0, ret = 0;
++      PK11_SESSION *sp = NULL;
++      CK_BYTE_PTR reuse_mem;
 +
-+      if ((entry = pk11_active_find(h, type)) == NULL)
++      CK_MECHANISM mechanism = {CKM_DH_PKCS_KEY_PAIR_GEN, NULL_PTR, 0};
++      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
++      CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
++
++      CK_ULONG ul_pub_key_attr_count = 3;
++      CK_ATTRIBUTE pub_key_template[] =
 +              {
-+              PK11err(PK11_F_ACTIVE_DELETE, PK11_R_INVALID_HANDLE);
-+              return (-1);
-+              }
++              {CKA_PRIVATE, &false, sizeof (false)},
++              {CKA_PRIME, (void *)NULL, 0},
++              {CKA_BASE, (void *)NULL, 0}
++              };
 +
-+      OPENSSL_assert(entry->refcnt > 0);
-+      entry->refcnt--;
-+      if (entry->refcnt == 0)
++      CK_ULONG ul_priv_key_attr_count = 3;
++      CK_ATTRIBUTE priv_key_template[] =
 +              {
-+              pk11_active_remove(entry, type);
-+              return (1);
-+              }
++              {CKA_PRIVATE, &false, sizeof (false)},
++              {CKA_SENSITIVE, &false, sizeof (false)},
++              {CKA_DERIVE, &true, sizeof (true)}
++              };
 +
-+      return (0);
-+      }
++      CK_ULONG pub_key_attr_result_count = 1;
++      CK_ATTRIBUTE pub_key_result[] =
++              {
++              {CKA_VALUE, (void *)NULL, 0}
++              };
 +
-+#ifndef OPENSSL_NO_RSA
-+/* Our internal RSA_METHOD that we provide pointers to */
-+static RSA_METHOD pk11_rsa =
-+      {
-+      "PKCS#11 RSA method",
-+      pk11_RSA_public_encrypt,                /* rsa_pub_encrypt */
-+      pk11_RSA_public_decrypt,                /* rsa_pub_decrypt */
-+      pk11_RSA_private_encrypt,               /* rsa_priv_encrypt */
-+      pk11_RSA_private_decrypt,               /* rsa_priv_decrypt */
-+      NULL,                                   /* rsa_mod_exp */
-+      NULL,                                   /* bn_mod_exp */
-+      pk11_RSA_init,                          /* init */
-+      pk11_RSA_finish,                        /* finish */
-+      RSA_FLAG_SIGN_VER,                      /* flags */
-+      NULL,                                   /* app_data */
-+      pk11_RSA_sign,                          /* rsa_sign */
-+      pk11_RSA_verify                         /* rsa_verify */
-+      };
++      CK_ULONG priv_key_attr_result_count = 1;
++      CK_ATTRIBUTE priv_key_result[] =
++              {
++              {CKA_VALUE, (void *)NULL, 0}
++              };
 +
-+RSA_METHOD *
-+PK11_RSA(void)
-+      {
-+      return (&pk11_rsa);
-+      }
-+#endif
++      pub_key_template[1].ulValueLen = BN_num_bytes(dh->p);
++      if (pub_key_template[1].ulValueLen > 0)
++              {
++              /*
++               * We must not increase ulValueLen by DH_BUF_RESERVE since that
++               * could cause the same rounding problem. See definition of
++               * DH_BUF_RESERVE above.
++               */
++              pub_key_template[1].pValue =
++                      OPENSSL_malloc(pub_key_template[1].ulValueLen +
++                      DH_BUF_RESERVE);
++              if (pub_key_template[1].pValue == NULL)
++                      {
++                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
 +
-+#ifndef OPENSSL_NO_DSA
-+/* Our internal DSA_METHOD that we provide pointers to */
-+static DSA_METHOD pk11_dsa =
-+      {
-+      "PKCS#11 DSA method",
-+      pk11_dsa_do_sign,       /* dsa_do_sign */
-+      NULL,                   /* dsa_sign_setup */
-+      pk11_dsa_do_verify,     /* dsa_do_verify */
-+      NULL,                   /* dsa_mod_exp */
-+      NULL,                   /* bn_mod_exp */
-+      pk11_DSA_init,          /* init */
-+      pk11_DSA_finish,        /* finish */
-+      0,                      /* flags */
-+      NULL                    /* app_data */
-+      };
++              i = BN_bn2bin(dh->p, pub_key_template[1].pValue);
++              }
++      else
++              goto err;
 +
-+DSA_METHOD *
-+PK11_DSA(void)
-+      {
-+      return (&pk11_dsa);
-+      }
-+#endif
++      pub_key_template[2].ulValueLen = BN_num_bytes(dh->g);
++      if (pub_key_template[2].ulValueLen > 0)
++              {
++              pub_key_template[2].pValue =
++                      OPENSSL_malloc(pub_key_template[2].ulValueLen +
++                      DH_BUF_RESERVE);
++              if (pub_key_template[2].pValue == NULL)
++                      {
++                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
 +
-+#ifndef OPENSSL_NO_DH
-+/*
-+ * PKCS #11 V2.20, section 11.2 specifies that the number of bytes needed for
-+ * output buffer may somewhat exceed the precise number of bytes needed, but
-+ * should not exceed it by a large amount. That may be caused, for example, by
-+ * rounding it up to multiple of X in the underlying bignum library. 8 should be
-+ * enough.
-+ */
-+#define       DH_BUF_RESERVE  8
++              i = BN_bn2bin(dh->g, pub_key_template[2].pValue);
++              }
++      else
++              goto err;
 +
-+/* Our internal DH_METHOD that we provide pointers to */
-+static DH_METHOD pk11_dh =
-+      {
-+      "PKCS#11 DH method",
-+      pk11_DH_generate_key,   /* generate_key */
-+      pk11_DH_compute_key,    /* compute_key */
-+      NULL,                   /* bn_mod_exp */
-+      pk11_DH_init,           /* init */
-+      pk11_DH_finish,         /* finish */
-+      0,                      /* flags */
-+      NULL,                   /* app_data */
-+      NULL                    /* generate_params */
-+      };
++      /*
++       * Note: we are only using PK11_SESSION structure for getting
++       *       a session handle. The objects created in this function are
++       *       destroyed before return and thus not cached.
++       */
++      if ((sp = pk11_get_session(OP_DH)) == NULL)
++              goto err;
 +
-+DH_METHOD *
-+PK11_DH(void)
-+      {
-+      return (&pk11_dh);
-+      }
-+#endif
++      rv = pFuncList->C_GenerateKeyPair(sp->session,
++          &mechanism,
++          pub_key_template,
++          ul_pub_key_attr_count,
++          priv_key_template,
++          ul_priv_key_attr_count,
++          &h_pub_key,
++          &h_priv_key);
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_DH_GEN_KEY, PK11_R_GEN_KEY, rv);
++              goto err;
++              }
 +
-+/* Size of an SSL signature: MD5+SHA1 */
-+#define       SSL_SIG_LENGTH          36
++      /*
++       * Reuse the larger memory allocated. We know the larger memory
++       * should be sufficient for reuse.
++       */
++      if (pub_key_template[1].ulValueLen > pub_key_template[2].ulValueLen)
++              {
++              reuse_mem = pub_key_template[1].pValue;
++              reuse_mem_len = pub_key_template[1].ulValueLen + DH_BUF_RESERVE;
++              }
++      else
++              {
++              reuse_mem = pub_key_template[2].pValue;
++              reuse_mem_len = pub_key_template[2].ulValueLen + DH_BUF_RESERVE;
++              }
 +
-+/* Lengths of DSA data and signature */
-+#define       DSA_DATA_LEN            20
-+#define       DSA_SIGNATURE_LEN       40
++      rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key,
++              pub_key_result, pub_key_attr_result_count);
++      rv1 = pFuncList->C_GetAttributeValue(sp->session, h_priv_key,
++              priv_key_result, priv_key_attr_result_count);
 +
-+static CK_BBOOL true = TRUE;
-+static CK_BBOOL false = FALSE;
++      if (rv != CKR_OK || rv1 != CKR_OK)
++              {
++              rv = (rv != CKR_OK) ? rv : rv1;
++              PK11err_add_data(PK11_F_DH_GEN_KEY,
++                  PK11_R_GETATTRIBUTVALUE, rv);
++              goto err;
++              }
 +
-+#ifndef OPENSSL_NO_RSA
-+/*
-+ * Similiar to OpenSSL to take advantage of the paddings. The goal is to
-+ * support all paddings in this engine although PK11 library does not
-+ * support all the paddings used in OpenSSL.
-+ * The input errors should have been checked in the padding functions.
-+ */
-+static int pk11_RSA_public_encrypt(int flen, const unsigned char *from,
-+              unsigned char *to, RSA *rsa, int padding)
-+      {
-+      int i, num = 0, r = -1;
-+      unsigned char *buf = NULL;
++      if (((CK_LONG) pub_key_result[0].ulValueLen) <= 0 ||
++              ((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
++              {
++              PK11err(PK11_F_DH_GEN_KEY, PK11_R_GETATTRIBUTVALUE);
++              goto err;
++              }
 +
-+      num = BN_num_bytes(rsa->n);
-+      if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
++      /* Reuse the memory allocated */
++      pub_key_result[0].pValue = reuse_mem;
++      pub_key_result[0].ulValueLen = reuse_mem_len;
++
++      rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key,
++              pub_key_result, pub_key_attr_result_count);
++
++      if (rv != CKR_OK)
 +              {
-+              RSAerr(PK11_F_RSA_PUB_ENC, PK11_R_MALLOC_FAILURE);
++              PK11err_add_data(PK11_F_DH_GEN_KEY,
++                  PK11_R_GETATTRIBUTVALUE, rv);
 +              goto err;
 +              }
 +
-+      switch (padding)
++      if (pub_key_result[0].type == CKA_VALUE)
 +              {
-+      case RSA_PKCS1_PADDING:
-+              i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
-+              break;
-+#ifndef OPENSSL_NO_SHA
-+      case RSA_PKCS1_OAEP_PADDING:
-+              i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
-+              break;
-+#endif
-+      case RSA_SSLV23_PADDING:
-+              i = RSA_padding_add_SSLv23(buf, num, from, flen);
-+              break;
-+      case RSA_NO_PADDING:
-+              i = RSA_padding_add_none(buf, num, from, flen);
-+              break;
-+      default:
-+              RSAerr(PK11_F_RSA_PUB_ENC, PK11_R_UNKNOWN_PADDING_TYPE);
++              if (dh->pub_key == NULL)
++                      if ((dh->pub_key = BN_new()) == NULL)
++                              {
++                              PK11err(PK11_F_DH_GEN_KEY,
++                                      PK11_R_MALLOC_FAILURE);
++                              goto err;
++                              }
++              dh->pub_key = BN_bin2bn(pub_key_result[0].pValue,
++                      pub_key_result[0].ulValueLen, dh->pub_key);
++              if (dh->pub_key == NULL)
++                      {
++                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
++              }
++
++      /* Reuse the memory allocated */
++      priv_key_result[0].pValue = reuse_mem;
++      priv_key_result[0].ulValueLen = reuse_mem_len;
++
++      rv = pFuncList->C_GetAttributeValue(sp->session, h_priv_key,
++              priv_key_result, priv_key_attr_result_count);
++
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_DH_GEN_KEY,
++                  PK11_R_GETATTRIBUTVALUE, rv);
 +              goto err;
 +              }
-+      if (i <= 0) goto err;
 +
-+      /* PK11 functions are called here */
-+      r = pk11_RSA_public_encrypt_low(num, buf, to, rsa);
-+err:
-+      if (buf != NULL)
++      if (priv_key_result[0].type == CKA_VALUE)
 +              {
-+              OPENSSL_cleanse(buf, num);
-+              OPENSSL_free(buf);
++              if (dh->priv_key == NULL)
++                      if ((dh->priv_key = BN_new()) == NULL)
++                              {
++                              PK11err(PK11_F_DH_GEN_KEY,
++                                      PK11_R_MALLOC_FAILURE);
++                              goto err;
++                              }
++              dh->priv_key = BN_bin2bn(priv_key_result[0].pValue,
++                      priv_key_result[0].ulValueLen, dh->priv_key);
++              if (dh->priv_key == NULL)
++                      {
++                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
 +              }
-+      return (r);
-+      }
 +
++      ret = 1;
 +
-+/*
-+ * Similar to Openssl to take advantage of the paddings. The input errors
-+ * should be catched in the padding functions
-+ */
-+static int pk11_RSA_private_encrypt(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa, int padding)
-+      {
-+      int i, num = 0, r = -1;
-+      unsigned char *buf = NULL;
++err:
 +
-+      num = BN_num_bytes(rsa->n);
-+      if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
++      if (h_pub_key != CK_INVALID_HANDLE)
 +              {
-+              RSAerr(PK11_F_RSA_PRIV_ENC, PK11_R_MALLOC_FAILURE);
-+              goto err;
++              rv = pFuncList->C_DestroyObject(sp->session, h_pub_key);
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_DH_GEN_KEY,
++                          PK11_R_DESTROYOBJECT, rv);
++                      }
 +              }
 +
-+      switch (padding)
++      if (h_priv_key != CK_INVALID_HANDLE)
 +              {
-+      case RSA_PKCS1_PADDING:
-+              i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
-+              break;
-+      case RSA_NO_PADDING:
-+              i = RSA_padding_add_none(buf, num, from, flen);
-+              break;
-+      case RSA_SSLV23_PADDING:
-+      default:
-+              RSAerr(PK11_F_RSA_PRIV_ENC, PK11_R_UNKNOWN_PADDING_TYPE);
-+              goto err;
++              rv = pFuncList->C_DestroyObject(sp->session, h_priv_key);
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_DH_GEN_KEY,
++                          PK11_R_DESTROYOBJECT, rv);
++                      }
 +              }
-+      if (i <= 0) goto err;
 +
-+      /* PK11 functions are called here */
-+      r = pk11_RSA_private_encrypt_low(num, buf, to, rsa);
-+err:
-+      if (buf != NULL)
++      for (i = 1; i <= 2; i++)
 +              {
-+              OPENSSL_cleanse(buf, num);
-+              OPENSSL_free(buf);
++              if (pub_key_template[i].pValue != NULL)
++                      {
++                      OPENSSL_free(pub_key_template[i].pValue);
++                      pub_key_template[i].pValue = NULL;
++                      }
 +              }
-+      return (r);
++
++      pk11_return_session(sp, OP_DH);
++      return (ret);
 +      }
 +
-+/* Similar to OpenSSL code. Input errors are also checked here */
-+static int pk11_RSA_private_decrypt(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa, int padding)
++static int pk11_DH_compute_key(unsigned char *key, const BIGNUM *pub_key,
++      DH *dh)
 +      {
-+      BIGNUM f;
-+      int j, num = 0, r = -1;
-+      unsigned char *p;
-+      unsigned char *buf = NULL;
-+
-+      BN_init(&f);
-+
-+      num = BN_num_bytes(rsa->n);
++      unsigned int i;
++      CK_MECHANISM mechanism = {CKM_DH_PKCS_DERIVE, NULL_PTR, 0};
++      CK_OBJECT_CLASS key_class = CKO_SECRET_KEY;
++      CK_KEY_TYPE key_type = CKK_GENERIC_SECRET;
++      CK_OBJECT_HANDLE h_derived_key = CK_INVALID_HANDLE;
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
 +
-+      if ((buf = (unsigned char *)OPENSSL_malloc(num)) == NULL)
++      CK_ULONG ul_priv_key_attr_count = 2;
++      CK_ATTRIBUTE priv_key_template[] =
 +              {
-+              RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_MALLOC_FAILURE);
-+              goto err;
-+              }
++              {CKA_CLASS, (void*) NULL, sizeof (key_class)},
++              {CKA_KEY_TYPE, (void*) NULL, sizeof (key_type)},
++              };
 +
-+      /*
-+       * This check was for equality but PGP does evil things
-+       * and chops off the top '0' bytes
-+       */
-+      if (flen > num)
++      CK_ULONG priv_key_attr_result_count = 1;
++      CK_ATTRIBUTE priv_key_result[] =
 +              {
-+              RSAerr(PK11_F_RSA_PRIV_DEC,
-+                      PK11_R_DATA_GREATER_THAN_MOD_LEN);
++              {CKA_VALUE, (void *)NULL, 0}
++              };
++
++      CK_RV rv;
++      int ret = -1;
++      PK11_SESSION *sp = NULL;
++
++      if (dh->priv_key == NULL)
 +              goto err;
-+              }
 +
-+      /* make data into a big number */
-+      if (BN_bin2bn(from, (int)flen, &f) == NULL)
++      priv_key_template[0].pValue = &key_class;
++      priv_key_template[1].pValue = &key_type;
++
++      if ((sp = pk11_get_session(OP_DH)) == NULL)
 +              goto err;
 +
-+      if (BN_ucmp(&f, rsa->n) >= 0)
++      mechanism.ulParameterLen = BN_num_bytes(pub_key);
++      mechanism.pParameter = OPENSSL_malloc(mechanism.ulParameterLen);
++      if (mechanism.pParameter == NULL)
 +              {
-+              RSAerr(PK11_F_RSA_PRIV_DEC,
-+                      PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
++              PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
 +              goto err;
 +              }
++      BN_bn2bin(pub_key, mechanism.pParameter);
 +
-+      /* PK11 functions are called here */
-+      r = pk11_RSA_private_decrypt_low(flen, from, buf, rsa);
-+
-+      /*
-+       * PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
-+       * Needs to skip these 0's paddings here.
-+       */
-+      for (j = 0; j < r; j++)
-+              if (buf[j] != 0)
-+                      break;
++      (void) check_new_dh_key(sp, dh);
 +
-+      p = buf + j;
-+      j = r - j;  /* j is only used with no-padding mode */
++      h_key = sp->opdata_dh_key;
++      if (h_key == CK_INVALID_HANDLE)
++              h_key = sp->opdata_dh_key =
++                      pk11_get_dh_key((DH*) dh, &sp->opdata_dh,
++                          &sp->opdata_dh_priv_num, sp->session);
 +
-+      switch (padding)
++      if (h_key == CK_INVALID_HANDLE)
 +              {
-+      case RSA_PKCS1_PADDING:
-+              r = RSA_padding_check_PKCS1_type_2(to, num, p, j, num);
-+              break;
-+#ifndef OPENSSL_NO_SHA
-+      case RSA_PKCS1_OAEP_PADDING:
-+              r = RSA_padding_check_PKCS1_OAEP(to, num, p, j, num, NULL, 0);
-+              break;
-+#endif
-+      case RSA_SSLV23_PADDING:
-+              r = RSA_padding_check_SSLv23(to, num, p, j, num);
-+              break;
-+      case RSA_NO_PADDING:
-+              r = RSA_padding_check_none(to, num, p, j, num);
-+              break;
-+      default:
-+              RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_UNKNOWN_PADDING_TYPE);
++              PK11err(PK11_F_DH_COMP_KEY, PK11_R_CREATEOBJECT);
 +              goto err;
 +              }
-+      if (r < 0)
-+              RSAerr(PK11_F_RSA_PRIV_DEC, PK11_R_PADDING_CHECK_FAILED);
 +
-+err:
-+      BN_clear_free(&f);
-+      if (buf != NULL)
++      rv = pFuncList->C_DeriveKey(sp->session,
++          &mechanism,
++          h_key,
++          priv_key_template,
++          ul_priv_key_attr_count,
++          &h_derived_key);
++      if (rv != CKR_OK)
 +              {
-+              OPENSSL_cleanse(buf, num);
-+              OPENSSL_free(buf);
++              PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_DERIVEKEY, rv);
++              goto err;
 +              }
-+      return (r);
-+      }
 +
-+/* Similar to OpenSSL code. Input errors are also checked here */
-+static int pk11_RSA_public_decrypt(int flen, const unsigned char *from,
-+      unsigned char *to, RSA *rsa, int padding)
-+      {
-+      BIGNUM f;
-+      int i, num = 0, r = -1;
-+      unsigned char *p;
-+      unsigned char *buf = NULL;
++      rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key,
++          priv_key_result, priv_key_attr_result_count);
 +
-+      BN_init(&f);
-+      num = BN_num_bytes(rsa->n);
-+      buf = (unsigned char *)OPENSSL_malloc(num);
-+      if (buf == NULL)
++      if (rv != CKR_OK)
 +              {
-+              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_MALLOC_FAILURE);
++              PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE,
++                  rv);
 +              goto err;
 +              }
 +
-+      /*
-+       * This check was for equality but PGP does evil things
-+       * and chops off the top '0' bytes
-+       */
-+      if (flen > num)
++      if (((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
 +              {
-+              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_DATA_GREATER_THAN_MOD_LEN);
++              PK11err(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE);
 +              goto err;
 +              }
-+
-+      if (BN_bin2bn(from, flen, &f) == NULL)
++      priv_key_result[0].pValue =
++              OPENSSL_malloc(priv_key_result[0].ulValueLen);
++      if (!priv_key_result[0].pValue)
++              {
++              PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
 +              goto err;
++              }
 +
-+      if (BN_ucmp(&f, rsa->n) >= 0)
++      rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key,
++              priv_key_result, priv_key_attr_result_count);
++
++      if (rv != CKR_OK)
 +              {
-+              RSAerr(PK11_F_RSA_PUB_DEC,
-+                      PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
++              PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE,
++                  rv);
 +              goto err;
 +              }
 +
-+      /* PK11 functions are called here */
-+      r = pk11_RSA_public_decrypt_low(flen, from, buf, rsa);
-+
 +      /*
-+       * PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
-+       * Needs to skip these 0's here
++       * OpenSSL allocates the output buffer 'key' which is the same
++       * length of the public key. It is long enough for the derived key
 +       */
-+      for (i = 0; i < r; i++)
-+              if (buf[i] != 0)
-+                      break;
++      if (priv_key_result[0].type == CKA_VALUE)
++              {
++              /*
++               * CKM_DH_PKCS_DERIVE mechanism is not supposed to strip
++               * leading zeros from a computed shared secret. However,
++               * OpenSSL always did it so we must do the same here. The
++               * vagueness of the spec regarding leading zero bytes was
++               * finally cleared with TLS 1.1 (RFC 4346) saying that leading
++               * zeros are stripped before the computed data is used as the
++               * pre-master secret.
++               */
++              for (i = 0; i < priv_key_result[0].ulValueLen; ++i)
++                      {
++                      if (((char *)priv_key_result[0].pValue)[i] != 0)
++                              break;
++                      }
 +
-+      p = buf + i;
-+      i = r - i;  /* i is only used with no-padding mode */
++              (void) memcpy(key, ((char *)priv_key_result[0].pValue) + i,
++                      priv_key_result[0].ulValueLen - i);
++              ret = priv_key_result[0].ulValueLen - i;
++              }
 +
-+      switch (padding)
++err:
++
++      if (h_derived_key != CK_INVALID_HANDLE)
 +              {
-+      case RSA_PKCS1_PADDING:
-+              r = RSA_padding_check_PKCS1_type_1(to, num, p, i, num);
-+              break;
-+      case RSA_NO_PADDING:
-+              r = RSA_padding_check_none(to, num, p, i, num);
-+              break;
-+      default:
-+              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_UNKNOWN_PADDING_TYPE);
-+              goto err;
++              rv = pFuncList->C_DestroyObject(sp->session, h_derived_key);
++              if (rv != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_DH_COMP_KEY,
++                          PK11_R_DESTROYOBJECT, rv);
++                      }
++              }
++      if (priv_key_result[0].pValue)
++              {
++              OPENSSL_free(priv_key_result[0].pValue);
++              priv_key_result[0].pValue = NULL;
 +              }
-+      if (r < 0)
-+              RSAerr(PK11_F_RSA_PUB_DEC, PK11_R_PADDING_CHECK_FAILED);
 +
-+err:
-+      BN_clear_free(&f);
-+      if (buf != NULL)
++      if (mechanism.pParameter)
 +              {
-+              OPENSSL_cleanse(buf, num);
-+              OPENSSL_free(buf);
++              OPENSSL_free(mechanism.pParameter);
++              mechanism.pParameter = NULL;
 +              }
-+      return (r);
++
++      pk11_return_session(sp, OP_DH);
++      return (ret);
 +      }
 +
-+/*
-+ * This function implements RSA public encryption using C_EncryptInit and
-+ * C_Encrypt pk11 interfaces. Note that the CKM_RSA_X_509 is used here.
-+ * The calling function allocated sufficient memory in "to" to store results.
-+ */
-+static int pk11_RSA_public_encrypt_low(int flen,
-+      const unsigned char *from, unsigned char *to, RSA *rsa)
++
++static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh,
++      DH **key_ptr, BIGNUM **dh_priv_num, CK_SESSION_HANDLE session)
 +      {
-+      CK_ULONG bytes_encrypted = flen;
-+      int retval = -1;
 +      CK_RV rv;
-+      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
-+      CK_MECHANISM *p_mech = &mech_rsa;
-+      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
-+      PK11_SESSION *sp;
-+
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              return (-1);
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
++      CK_KEY_TYPE key_type = CKK_DH;
++      CK_ULONG found;
++      CK_BBOOL rollback = FALSE;
++      int i;
 +
-+      (void) check_new_rsa_key_pub(sp, rsa);
++      CK_ULONG ul_key_attr_count = 7;
++      CK_ATTRIBUTE key_template[] =
++              {
++              {CKA_CLASS, (void*) NULL, sizeof (class)},
++              {CKA_KEY_TYPE, (void*) NULL, sizeof (key_type)},
++              {CKA_DERIVE, &true, sizeof (true)},
++              {CKA_PRIVATE, &false, sizeof (false)},
++              {CKA_PRIME, (void *) NULL, 0},
++              {CKA_BASE, (void *) NULL, 0},
++              {CKA_VALUE, (void *) NULL, 0},
++              };
 +
-+      h_pub_key = sp->opdata_rsa_pub_key;
-+      if (h_pub_key == CK_INVALID_HANDLE)
-+              h_pub_key = sp->opdata_rsa_pub_key =
-+                      pk11_get_public_rsa_key(rsa, &sp->opdata_rsa_pub,
-+                          &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
-+                          sp->session);
++      key_template[0].pValue = &class;
++      key_template[1].pValue = &key_type;
 +
-+      if (h_pub_key != CK_INVALID_HANDLE)
++      key_template[4].ulValueLen = BN_num_bytes(dh->p);
++      key_template[4].pValue = (CK_VOID_PTR)OPENSSL_malloc(
++              (size_t)key_template[4].ulValueLen);
++      if (key_template[4].pValue == NULL)
 +              {
-+              rv = pFuncList->C_EncryptInit(sp->session, p_mech,
-+                      h_pub_key);
++              PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
++              }
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_PUB_ENC_LOW,
-+                          PK11_R_ENCRYPTINIT, rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
-+                      }
++      BN_bn2bin(dh->p, key_template[4].pValue);
 +
-+              rv = pFuncList->C_Encrypt(sp->session,
-+                      (unsigned char *)from, flen, to, &bytes_encrypted);
++      key_template[5].ulValueLen = BN_num_bytes(dh->g);
++      key_template[5].pValue = (CK_VOID_PTR)OPENSSL_malloc(
++              (size_t)key_template[5].ulValueLen);
++      if (key_template[5].pValue == NULL)
++              {
++              PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
++              }
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_PUB_ENC_LOW,
-+                          PK11_R_ENCRYPT, rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
-+                      }
-+              retval = bytes_encrypted;
++      BN_bn2bin(dh->g, key_template[5].pValue);
++
++      key_template[6].ulValueLen = BN_num_bytes(dh->priv_key);
++      key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
++              (size_t)key_template[6].ulValueLen);
++      if (key_template[6].pValue == NULL)
++              {
++              PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
++              goto malloc_err;
 +              }
 +
-+      pk11_return_session(sp, OP_RSA);
-+      return (retval);
-+      }
++      BN_bn2bin(dh->priv_key, key_template[6].pValue);
 +
++      /* see find_lock array definition for more info on object locking */
++      LOCK_OBJSTORE(OP_DH);
++      rv = pFuncList->C_FindObjectsInit(session, key_template,
++              ul_key_attr_count);
 +
-+/*
-+ * This function implements RSA private encryption using C_SignInit and
-+ * C_Sign pk11 APIs. Note that CKM_RSA_X_509 is used here.
-+ * The calling function allocated sufficient memory in "to" to store results.
-+ */
-+static int pk11_RSA_private_encrypt_low(int flen,
-+      const unsigned char *from, unsigned char *to, RSA *rsa)
-+      {
-+      CK_ULONG ul_sig_len = flen;
-+      int retval = -1;
-+      CK_RV rv;
-+      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
-+      CK_MECHANISM *p_mech = &mech_rsa;
-+      CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
-+      PK11_SESSION *sp;
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSINIT, rv);
++              goto err;
++              }
 +
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              return (-1);
++      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
 +
-+      (void) check_new_rsa_key_priv(sp, rsa);
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTS, rv);
++              goto err;
++              }
 +
-+      h_priv_key = sp->opdata_rsa_priv_key;
-+      if (h_priv_key == CK_INVALID_HANDLE)
-+              h_priv_key = sp->opdata_rsa_priv_key =
-+                      pk11_get_private_rsa_key(rsa, &sp->opdata_rsa_priv,
-+                          &sp->opdata_rsa_d_num, sp->session);
++      rv = pFuncList->C_FindObjectsFinal(session);
 +
-+      if (h_priv_key != CK_INVALID_HANDLE)
++      if (rv != CKR_OK)
 +              {
-+              rv = pFuncList->C_SignInit(sp->session, p_mech,
-+                      h_priv_key);
++              PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSFINAL,
++                  rv);
++              goto err;
++              }
 +
++      if (found == 0)
++              {
++              rv = pFuncList->C_CreateObject(session,
++                      key_template, ul_key_attr_count, &h_key);
 +              if (rv != CKR_OK)
 +                      {
-+                      PK11err_add_data(PK11_F_RSA_PRIV_ENC_LOW,
-+                          PK11_R_SIGNINIT, rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
++                      PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_CREATEOBJECT,
++                          rv);
++                      goto err;
++                      }
++              }
++
++      if (dh_priv_num != NULL)
++              if ((*dh_priv_num = BN_dup(dh->priv_key)) == NULL)
++                      {
++                      PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
++                      rollback = TRUE;
++                      goto err;
 +                      }
 +
-+              rv = pFuncList->C_Sign(sp->session,
-+                      (unsigned char *)from, flen, to, &ul_sig_len);
++      /* LINTED: E_CONSTANT_CONDITION */
++      KEY_HANDLE_REFHOLD(h_key, OP_DH, FALSE, rollback, err);
++      if (key_ptr != NULL)
++              *key_ptr = dh;
 +
-+              if (rv != CKR_OK)
++err:
++      if (rollback)
++              {
++              /*
++               * We do not care about the return value from C_DestroyObject()
++               * since we are doing rollback.
++               */
++              if (found == 0)
++                      (void) pFuncList->C_DestroyObject(session, h_key);
++              h_key = CK_INVALID_HANDLE;
++              }
++
++      UNLOCK_OBJSTORE(OP_DH);
++
++malloc_err:
++      for (i = 4; i <= 6; i++)
++              {
++              if (key_template[i].pValue != NULL)
 +                      {
-+                      PK11err_add_data(PK11_F_RSA_PRIV_ENC_LOW, PK11_R_SIGN,
-+                          rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
++                      OPENSSL_free(key_template[i].pValue);
++                      key_template[i].pValue = NULL;
 +                      }
-+
-+              retval = ul_sig_len;
 +              }
 +
-+      pk11_return_session(sp, OP_RSA);
-+      return (retval);
++      return (h_key);
 +      }
 +
++/*
++ * Check for cache miss and clean the object pointer and handle
++ * in such case. Return 1 for cache hit, 0 for cache miss.
++ *
++ * Note: we rely on pk11_destroy_dh_key_objects() to set sp->opdata_dh
++ *       to CK_INVALID_HANDLE even when it fails to destroy the object.
++ */
++static int check_new_dh_key(PK11_SESSION *sp, DH *dh)
++      {
++      /*
++       * Provide protection against DH structure reuse by making the
++       * check for cache hit stronger. Private key component of DH key
++       * is unique so it is sufficient to compare it with value cached
++       * in PK11_SESSION structure.
++       */
++      if ((sp->opdata_dh != dh) ||
++          (BN_cmp(sp->opdata_dh_priv_num, dh->priv_key) != 0))
++              {
++              /*
++               * We do not check the return value because even in case of
++               * failure the sp structure will have both key pointer
++               * and object handle cleaned and pk11_destroy_object()
++               * reports the failure to the OpenSSL error message buffer.
++               */
++              (void) pk11_destroy_dh_object(sp, TRUE);
++              return (0);
++              }
++      return (1);
++      }
++#endif
 +
 +/*
-+ * This function implements RSA private decryption using C_DecryptInit and
-+ * C_Decrypt pk11 APIs. Note that CKM_RSA_X_509 mechanism is used here.
-+ * The calling function allocated sufficient memory in "to" to store results.
++ * Local function to simplify key template population
++ * Return 0 -- error, 1 -- no error
 + */
-+static int pk11_RSA_private_decrypt_low(int flen,
-+      const unsigned char *from, unsigned char *to, RSA *rsa)
++static int init_template_value(BIGNUM *bn, CK_VOID_PTR *p_value,
++      CK_ULONG *ul_value_len)
 +      {
-+      CK_ULONG bytes_decrypted = flen;
-+      int retval = -1;
-+      CK_RV rv;
-+      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
-+      CK_MECHANISM *p_mech = &mech_rsa;
-+      CK_OBJECT_HANDLE h_priv_key;
-+      PK11_SESSION *sp;
++      CK_ULONG len = BN_num_bytes(bn);
++      if (len == 0)
++              return (1);
 +
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              return (-1);
++      *ul_value_len = len;
++      *p_value = (CK_VOID_PTR)OPENSSL_malloc((size_t)*ul_value_len);
++      if (*p_value == NULL)
++              return (0);
 +
-+      (void) check_new_rsa_key_priv(sp, rsa);
++      BN_bn2bin(bn, *p_value);
 +
-+      h_priv_key = sp->opdata_rsa_priv_key;
-+      if (h_priv_key == CK_INVALID_HANDLE)
-+              h_priv_key = sp->opdata_rsa_priv_key =
-+                      pk11_get_private_rsa_key(rsa, &sp->opdata_rsa_priv,
-+                          &sp->opdata_rsa_d_num, sp->session);
++      return (1);
++      }
 +
-+      if (h_priv_key != CK_INVALID_HANDLE)
++static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn)
++      {
++      if (attr->ulValueLen > 0)
 +              {
-+              rv = pFuncList->C_DecryptInit(sp->session, p_mech,
-+                      h_priv_key);
-+
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_PRIV_DEC_LOW,
-+                              PK11_R_DECRYPTINIT, rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
-+                      }
++              *bn = BN_bin2bn(attr_data, attr->ulValueLen, NULL);
++              }
++      }
++#ifdef        OPENSSL_SYS_WIN32
++char *getpassphrase(const char *prompt)
++      {
++      static char buf[128];
++      HANDLE h;
++      DWORD cc, mode;
++      int cnt;
 +
-+              rv = pFuncList->C_Decrypt(sp->session,
-+                      (unsigned char *)from, flen, to, &bytes_decrypted);
++      h = GetStdHandle(STD_INPUT_HANDLE);
++      fputs(prompt, stderr);
++      fflush(stderr);
++      fflush(stdout);
++      FlushConsoleInputBuffer(h);
++      GetConsoleMode(h, &mode);
++      SetConsoleMode(h, ENABLE_PROCESSED_INPUT);
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_PRIV_DEC_LOW,
-+                          PK11_R_DECRYPT, rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
-+                      }
-+              retval = bytes_decrypted;
++      for (cnt = 0; cnt < sizeof(buf) - 1; cnt++)
++              {
++              ReadFile(h, buf + cnt, 1, &cc, NULL);
++              if (buf[cnt] == '\r')
++                      break;
++              fputc('*', stdout);
++              fflush(stderr);
++              fflush(stdout);
 +              }
 +
-+      pk11_return_session(sp, OP_RSA);
-+      return (retval);
++      SetConsoleMode(h, mode);
++      buf[cnt] = '\0';
++      fputs("\n", stderr);
++      return buf;
 +      }
-+
-+
++#endif        /* OPENSSL_SYS_WIN32 */
++#endif        /* OPENSSL_NO_HW_PK11CA */
++#endif        /* OPENSSL_NO_HW_PK11 */
++#endif        /* OPENSSL_NO_HW */
+Index: openssl/crypto/engine/hw_pk11ca.h
+diff -u /dev/null openssl/crypto/engine/hw_pk11ca.h:1.2
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11ca.h  Mon Oct  5 13:17:03 2009
+@@ -0,0 +1,28 @@
++/* Redefine all pk11/PK11 external symbols to pk11ca/PK11CA */
++
++#define find_lock                     pk11ca_find_lock
++#define active_list                   pk11ca_active_list
++#define ERR_pk11_error                        ERR_pk11ca_error
++#define PK11err_add_data              PK11CAerr_add_data
++#define pk11_get_session              pk11ca_get_session
++#define pk11_return_session           pk11ca_return_session
++#define pk11_active_add                       pk11ca_active_add
++#define pk11_active_delete            pk11ca_active_delete
++#define pk11_active_remove            pk11ca_active_remove
++#define pk11_free_active_list         pk11ca_free_active_list
++#define pk11_destroy_rsa_key_objects  pk11ca_destroy_rsa_key_objects
++#define pk11_destroy_rsa_object_pub   pk11ca_destroy_rsa_object_pub
++#define pk11_destroy_rsa_object_priv  pk11ca_destroy_rsa_object_priv
++#define pk11_load_privkey             pk11ca_load_privkey
++#define pk11_load_pubkey              pk11ca_load_pubkey
++#define PK11_RSA                      PK11CA_RSA
++#define pk11_destroy_dsa_key_objects  pk11ca_destroy_dsa_key_objects
++#define pk11_destroy_dsa_object_pub   pk11ca_destroy_dsa_object_pub
++#define pk11_destroy_dsa_object_priv  pk11ca_destroy_dsa_object_priv
++#define PK11_DSA                      PK11CA_DSA
++#define pk11_destroy_dh_key_objects   pk11ca_destroy_dh_key_objects
++#define pk11_destroy_dh_object                pk11ca_destroy_dh_object
++#define PK11_DH                               PK11CA_DH
++#define pFuncList                     pk11ca_pFuncList
++#define pk11_pin                      pk11ca_pin
++#define ENGINE_load_pk11              ENGINE_load_pk11ca
+Index: openssl/crypto/engine/hw_pk11so.c
+diff -u /dev/null openssl/crypto/engine/hw_pk11so.c:1.2
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11so.c  Mon Oct  5 13:17:03 2009
+@@ -0,0 +1,1618 @@
 +/*
-+ * This function implements RSA public decryption using C_VerifyRecoverInit
-+ * and C_VerifyRecover pk11 APIs. Note that CKM_RSA_X_509 is used here.
-+ * The calling function allocated sufficient memory in "to" to store results.
++ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
++ * Use is subject to license terms.
 + */
-+static int pk11_RSA_public_decrypt_low(int flen,
-+      const unsigned char *from, unsigned char *to, RSA *rsa)
-+      {
-+      CK_ULONG bytes_decrypted = flen;
-+      int retval = -1;
-+      CK_RV rv;
-+      CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
-+      CK_MECHANISM *p_mech = &mech_rsa;
-+      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
-+      PK11_SESSION *sp;
-+
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              return (-1);
 +
-+      (void) check_new_rsa_key_pub(sp, rsa);
++/* 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).
++ *
++ */
 +
-+      h_pub_key = sp->opdata_rsa_pub_key;
-+      if (h_pub_key == CK_INVALID_HANDLE)
-+              h_pub_key = sp->opdata_rsa_pub_key =
-+                      pk11_get_public_rsa_key(rsa, &sp->opdata_rsa_pub,
-+                          &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
-+                          sp->session);
++/* Modified to keep only RNG and RSA Sign */
 +
-+      if (h_pub_key != CK_INVALID_HANDLE)
-+              {
-+              rv = pFuncList->C_VerifyRecoverInit(sp->session,
-+                      p_mech, h_pub_key);
++#ifdef OPENSSL_NO_RSA
++#error RSA is disabled
++#endif
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_PUB_DEC_LOW,
-+                              PK11_R_VERIFYRECOVERINIT, rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
-+                      }
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++#include <sys/types.h>
 +
-+              rv = pFuncList->C_VerifyRecover(sp->session,
-+                      (unsigned char *)from, flen, to, &bytes_decrypted);
++#include <openssl/e_os2.h>
++#include <openssl/crypto.h>
++#include <cryptlib.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>
++#include <openssl/rsa.h>
++#include <openssl/rand.h>
++#include <openssl/objects.h>
++#include <openssl/x509.h>
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_PUB_DEC_LOW,
-+                          PK11_R_VERIFYRECOVER, rv);
-+                      pk11_return_session(sp, OP_RSA);
-+                      return (-1);
-+                      }
-+              retval = bytes_decrypted;
-+              }
++#ifdef OPENSSL_SYS_WIN32
++typedef int pid_t;
++#define getpid() GetCurrentProcessId()
++#define NOPTHREADS
++#ifndef NULL_PTR
++#define NULL_PTR NULL
++#endif
++#define CK_DEFINE_FUNCTION(returnType, name) \
++      returnType __declspec(dllexport) name
++#define CK_DECLARE_FUNCTION(returnType, name) \
++      returnType __declspec(dllimport) name
++#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
++      returnType __declspec(dllimport) (* name)
++#else
++#include <signal.h>
++#include <unistd.h>
++#include <dlfcn.h>
++#endif
 +
-+      pk11_return_session(sp, OP_RSA);
-+      return (retval);
-+      }
++#ifndef NOPTHREADS
++#include <pthread.h>
++#endif
 +
-+static int pk11_RSA_init(RSA *rsa)
-+      {
-+      /*
-+       * This flag in the RSA_METHOD enables the new rsa_sign,
-+       * rsa_verify functions. See rsa.h for details.
-+       */
-+      rsa->flags |= RSA_FLAG_SIGN_VER;
++#ifndef OPENSSL_NO_HW
++#ifndef OPENSSL_NO_HW_PK11
++#ifndef OPENSSL_NO_HW_PK11SO
 +
-+      return (1);
-+      }
++/* 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 */
 +
-+static int pk11_RSA_finish(RSA *rsa)
-+      {
-+      /*
-+       * Since we are overloading OpenSSL's native RSA_eay_finish() we need
-+       * to do the same as in the original function, i.e. to free bignum
-+       * structures.
-+       */
-+      if (rsa->_method_mod_n != NULL)
-+              BN_MONT_CTX_free(rsa->_method_mod_n);
-+      if (rsa->_method_mod_p != NULL)
-+              BN_MONT_CTX_free(rsa->_method_mod_p);
-+      if (rsa->_method_mod_q != NULL)
-+              BN_MONT_CTX_free(rsa->_method_mod_q);
++#ifndef OPENSSL_NO_DSA
++#define OPENSSL_NO_DSA
++#endif
++#ifndef OPENSSL_NO_DH
++#define OPENSSL_NO_DH
++#endif
 +
-+      return (1);
-+      }
++#ifdef OPENSSL_SYS_WIN32
++#pragma pack(push, cryptoki, 1)
++#include "cryptoki.h"
++#include "pkcs11.h"
++#pragma pack(pop, cryptoki)
++#else
++#include "cryptoki.h"
++#include "pkcs11.h"
++#endif
++#include "hw_pk11so.h"
++#include "hw_pk11_err.c"
++
++/* PKCS#11 session caches and their locks for all operation types */
++static PK11_CACHE session_cache[OP_MAX];
 +
 +/*
-+ * Standard engine interface function. Majority codes here are from
-+ * rsa/rsa_sign.c. We replaced the decrypt function call by C_Sign of PKCS#11.
-+ * See more details in rsa/rsa_sign.c
++ * 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.
 + */
-+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
-+      unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
-+      {
-+      X509_SIG sig;
-+      ASN1_TYPE parameter;
-+      int i, j = 0;
-+      unsigned char *p, *s = NULL;
-+      X509_ALGOR algor;
-+      ASN1_OCTET_STRING digest;
-+      CK_RV rv;
-+      CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
-+      CK_MECHANISM *p_mech = &mech_rsa;
-+      CK_OBJECT_HANDLE h_priv_key;
-+      PK11_SESSION *sp = NULL;
-+      int ret = 0;
-+      unsigned long ulsiglen;
-+
-+      /* Encode the digest */
-+      /* Special case: SSL signature, just check the length */
-+      if (type == NID_md5_sha1)
-+              {
-+              if (m_len != SSL_SIG_LENGTH)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN,
-+                              PK11_R_INVALID_MESSAGE_LENGTH);
-+                      goto err;
-+                      }
-+              i = SSL_SIG_LENGTH;
-+              s = (unsigned char *)m;
-+              }
-+      else
-+              {
-+              sig.algor = &algor;
-+              sig.algor->algorithm = OBJ_nid2obj(type);
-+              if (sig.algor->algorithm == NULL)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN,
-+                              PK11_R_UNKNOWN_ALGORITHM_TYPE);
-+                      goto err;
-+                      }
-+              if (sig.algor->algorithm->length == 0)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN,
-+                              PK11_R_UNKNOWN_ASN1_OBJECT_ID);
-+                      goto err;
-+                      }
-+              parameter.type = V_ASN1_NULL;
-+              parameter.value.ptr = NULL;
-+              sig.algor->parameter = &parameter;
-+
-+              sig.digest = &digest;
-+              sig.digest->data = (unsigned char *)m;
-+              sig.digest->length = m_len;
++#ifndef NOPTHREADS
++pthread_mutex_t *find_lock[OP_MAX] = { NULL };
++#endif
 +
-+              i = i2d_X509_SIG(&sig, 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 };
 +
-+      j = RSA_size(rsa);
-+      if ((i - RSA_PKCS1_PADDING) > j)
-+              {
-+              PK11err(PK11_F_RSA_SIGN, PK11_R_DIGEST_TOO_BIG);
-+              goto err;
-+              }
++/*
++ * 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;
 +
-+      if (type != NID_md5_sha1)
-+              {
-+              s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
-+              if (s == NULL)
-+                      {
-+                      PK11err(PK11_F_RSA_SIGN, PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
-+              p = s;
-+              (void) i2d_X509_SIG(&sig, &p);
-+              }
++/* 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)(void));
++static int pk11_destroy(ENGINE *e);
 +
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              goto err;
++/* 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);
 +
-+      (void) check_new_rsa_key_priv(sp, rsa);
++/* 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);
 +
-+      h_priv_key = sp->opdata_rsa_priv_key;
-+      if (h_priv_key == CK_INVALID_HANDLE)
-+              h_priv_key = sp->opdata_rsa_priv_key =
-+                      pk11_get_private_rsa_key((RSA *)rsa,
-+                          &sp->opdata_rsa_priv,
-+                          &sp->opdata_rsa_d_num, sp->session);
++/* 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);
 +
-+      if (h_priv_key != CK_INVALID_HANDLE)
-+              {
-+              rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
++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);
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGNINIT, rv);
-+                      goto err;
-+                      }
++/* 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_object(CK_SESSION_HANDLE session,
++      CK_OBJECT_HANDLE oh);
++static const char *get_PK11_LIBNAME(void);
++static void free_PK11_LIBNAME(void);
++static long set_PK11_LIBNAME(const char *name);
 +
-+              ulsiglen = j;
-+              rv = pFuncList->C_Sign(sp->session, s, i, sigret,
-+                      (CK_ULONG_PTR) &ulsiglen);
-+              *siglen = ulsiglen;
++static int pk11_choose_slots(int *any_slot_found);
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGN, rv);
-+                      goto err;
-+                      }
-+              ret = 1;
-+              }
++static int pk11_init_all_locks(void);
++static void pk11_free_all_locks(void);
 +
-+err:
-+      if ((type != NID_md5_sha1) && (s != NULL))
-+              {
-+              (void) memset(s, 0, (unsigned int)(j + 1));
-+              OPENSSL_free(s);
-+              }
++#define       TRY_OBJ_DESTROY(sess_hdl, 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(sess_hdl, obj_hdl);        \
++              }                                                       \
++      if (uselock)                                                    \
++              UNLOCK_OBJSTORE(alg_type);                              \
++      }
 +
-+      pk11_return_session(sp, OP_RSA);
-+      return (ret);
++#define       TRY_OBJ_DELETE(sess_hdl, obj_hdl, retval, uselock, alg_type)    \
++      {                                                               \
++      if (uselock)                                                    \
++              LOCK_OBJSTORE(alg_type);                                \
++      (void) pk11_active_delete(obj_hdl, alg_type);                   \
++      if (uselock)                                                    \
++              UNLOCK_OBJSTORE(alg_type);                              \
 +      }
 +
-+static int pk11_RSA_verify(int type, const unsigned char *m,
-+      unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
-+      const RSA *rsa)
-+      {
-+      X509_SIG sig;
-+      ASN1_TYPE parameter;
-+      int i, j = 0;
-+      unsigned char *p, *s = NULL;
-+      X509_ALGOR algor;
-+      ASN1_OCTET_STRING digest;
-+      CK_RV rv;
-+      CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
-+      CK_MECHANISM *p_mech = &mech_rsa;
-+      CK_OBJECT_HANDLE h_pub_key;
-+      PK11_SESSION *sp = NULL;
-+      int ret = 0;
++static CK_BBOOL pk11_have_rsa = CK_FALSE;
++static CK_BBOOL pk11_have_random = CK_FALSE;
 +
-+      /* Encode the digest    */
-+      /* Special case: SSL signature, just check the length */
-+      if (type == NID_md5_sha1)
-+              {
-+              if (m_len != SSL_SIG_LENGTH)
-+                      {
-+                      PK11err(PK11_F_RSA_VERIFY,
-+                              PK11_R_INVALID_MESSAGE_LENGTH);
-+                      goto err;
-+                      }
-+              i = SSL_SIG_LENGTH;
-+              s = (unsigned char *)m;
-+              }
-+      else
++/*
++ * 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
++#define PK11_CMD_PIN                  (ENGINE_CMD_BASE+1)
++#define PK11_CMD_SLOT                 (ENGINE_CMD_BASE+2)
++static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
++      {
 +              {
-+              sig.algor = &algor;
-+              sig.algor->algorithm = OBJ_nid2obj(type);
-+              if (sig.algor->algorithm == NULL)
-+                      {
-+                      PK11err(PK11_F_RSA_VERIFY,
-+                              PK11_R_UNKNOWN_ALGORITHM_TYPE);
-+                      goto err;
-+                      }
-+              if (sig.algor->algorithm->length == 0)
-+                      {
-+                      PK11err(PK11_F_RSA_VERIFY,
-+                              PK11_R_UNKNOWN_ASN1_OBJECT_ID);
-+                      goto err;
-+                      }
-+              parameter.type = V_ASN1_NULL;
-+              parameter.value.ptr = NULL;
-+              sig.algor->parameter = &parameter;
-+              sig.digest = &digest;
-+              sig.digest->data = (unsigned char *)m;
-+              sig.digest->length = m_len;
-+              i = i2d_X509_SIG(&sig, NULL);
-+              }
-+
-+      j = RSA_size(rsa);
-+      if ((i - RSA_PKCS1_PADDING) > j)
++              PK11_CMD_SO_PATH,
++              "SO_PATH",
++              "Specifies the path to the 'pkcs#11' shared library",
++              ENGINE_CMD_FLAG_STRING
++              },
 +              {
-+              PK11err(PK11_F_RSA_VERIFY, PK11_R_DIGEST_TOO_BIG);
-+              goto err;
-+              }
-+
-+      if (type != NID_md5_sha1)
++              PK11_CMD_PIN,
++              "PIN",
++              "Specifies the pin code",
++              ENGINE_CMD_FLAG_STRING
++              },
 +              {
-+              s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
-+              if (s == NULL)
-+                      {
-+                      PK11err(PK11_F_RSA_VERIFY, PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
-+              p = s;
-+              (void) i2d_X509_SIG(&sig, &p);
-+              }
-+
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              goto err;
++              PK11_CMD_SLOT,
++              "SLOT",
++              "Specifies the slot (default is auto select)",
++              ENGINE_CMD_FLAG_NUMERIC,
++              },
++              {0, NULL, NULL, 0}
++      };
 +
-+      (void) check_new_rsa_key_pub(sp, rsa);
 +
-+      h_pub_key = sp->opdata_rsa_pub_key;
-+      if (h_pub_key == CK_INVALID_HANDLE)
-+              h_pub_key = sp->opdata_rsa_pub_key =
-+                      pk11_get_public_rsa_key((RSA *)rsa, &sp->opdata_rsa_pub,
-+                          &sp->opdata_rsa_n_num, &sp->opdata_rsa_e_num,
-+                          sp->session);
++static RAND_METHOD pk11_random =
++      {
++      pk11_rand_seed,
++      pk11_rand_bytes,
++      pk11_rand_cleanup,
++      pk11_rand_add,
++      pk11_rand_bytes,
++      pk11_rand_status
++      };
 +
-+      if (h_pub_key != CK_INVALID_HANDLE)
-+              {
-+              rv = pFuncList->C_VerifyInit(sp->session, p_mech,
-+                      h_pub_key);
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_VERIFY, PK11_R_VERIFYINIT,
-+                          rv);
-+                      goto err;
-+                      }
-+              rv = pFuncList->C_Verify(sp->session, s, i, sigbuf,
-+                      (CK_ULONG)siglen);
++/* Constants used when creating the ENGINE */
++#ifdef OPENSSL_NO_HW_PK11CA
++#error "can't load both crypto-accelerator and sign-only PKCS#11 engines"
++#endif
++static const char *engine_pk11_id = "pkcs11";
++static const char *engine_pk11_name = "PKCS #11 engine support (sign only)";
 +
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_RSA_VERIFY, PK11_R_VERIFY, rv);
-+                      goto err;
-+                      }
-+              ret = 1;
-+              }
++CK_FUNCTION_LIST_PTR pFuncList = NULL;
++static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
 +
-+err:
-+      if ((type != NID_md5_sha1) && (s != NULL))
-+              {
-+              (void) memset(s, 0, (unsigned int)(j + 1));
-+              OPENSSL_free(s);
-+              }
++/*
++ * These is the static string constant for the DSO file name and the function
++ * symbol names to bind to.
++ */
++static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
 +
-+      pk11_return_session(sp, OP_RSA);
-+      return (ret);
-+      }
++static CK_SLOT_ID pubkey_SLOTID = 0;
++static CK_SLOT_ID rand_SLOTID = 0;
++static CK_SLOT_ID SLOTID = 0;
++char *pk11_pin = NULL;
++static CK_BBOOL pk11_library_initialized = FALSE;
++static CK_BBOOL pk11_atfork_initialized = FALSE;
++static int pk11_pid = 0;
 +
-+static int hndidx_rsa = -1;
++static DSO *pk11_dso = NULL;
 +
-+/* load RSA private key from a file */
-+/* ARGSUSED */
-+EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *privkey_file,
-+      UI_METHOD *ui_method, void *callback_data)
++/* allocate and initialize all locks used by the engine itself */
++static int pk11_init_all_locks(void)
 +      {
-+      EVP_PKEY *pkey = NULL;
-+      FILE *privkey;
-+      CK_OBJECT_HANDLE  h_priv_key = CK_INVALID_HANDLE;
-+      RSA *rsa;
-+      PK11_SESSION *sp;
-+      /* everything else below needed for key by reference extension */
-+      CK_RV rv;
-+      CK_ULONG objcnt = 0;
-+      CK_BBOOL is_token = TRUE;
-+      CK_BYTE attr_data[2][1024];
-+      CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY;
-+      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
-+      extern char *pk11_pin;
++#ifndef NOPTHREADS
++      int type;
 +
-+      /* we look for private keys only */
-+      CK_ATTRIBUTE search_templ[] =
-+              {
-+              {CKA_TOKEN, &is_token, sizeof(is_token)},
-+              {CKA_CLASS, &key_class, sizeof(key_class)},
-+              {CKA_LABEL, NULL, 0}
-+              };
++      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);
 +
-+      /* these attributes are needed to initialize OpenSSL RSA structure */
-+      CK_ATTRIBUTE get_templ[] =
++      for (type = 0; type < OP_MAX; type++)
 +              {
-+              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
-+              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
-+              };
++              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);
++#else
++      return (1);
++#endif
++      }
 +
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              return (NULL);
++static void pk11_free_all_locks(void)
++      {
++#ifndef NOPTHREADS
++      int type;
 +
-+      /*
-+       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
-+       */
-+      if (strstr(privkey_file, "pkcs11:") == privkey_file)
++      if (find_lock[OP_RSA] != NULL)
 +              {
-+              search_templ[2].pValue = strstr(privkey_file, ":") + 1;
-+              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
-+
-+              if (pk11_pin == NULL)
-+                      {
-+                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
++              (void) pthread_mutex_destroy(find_lock[OP_RSA]);
++              OPENSSL_free(find_lock[OP_RSA]);
++              find_lock[OP_RSA] = NULL;
++              }
 +
-+                      if (pk11_pin == NULL)
-+                              {
-+                              PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MALLOC_FAILURE);
-+                              goto err;
-+                              }
-+                      }
-+              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
-+                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
++      for (type = 0; type < OP_MAX; type++)
++              {
++              if (session_cache[type].lock != NULL)
 +                      {
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_INVALID_PIN, rv);
-+                      goto err;
++                      (void) pthread_mutex_destroy(session_cache[type].lock);
++                      OPENSSL_free(session_cache[type].lock);
++                      session_cache[type].lock = NULL;
 +                      }
++              }
++#endif
++      }
 +
-+              LOCK_OBJSTORE(OP_RSA);
-+              if ((rv = pFuncList->C_FindObjectsInit(sp->session,
-+                  search_templ, 3)) != CKR_OK)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_FINDOBJECTSINIT, rv);
-+                      goto err;
-+                      }
++/*
++ * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
++ */
++static int bind_pk11(ENGINE *e)
++      {
++      if (!pk11_library_initialized)
++              if (!pk11_library_init(e))
++                      return (0);
 +
-+              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
-+              if (rv != CKR_OK)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_FINDOBJECTS, rv);
-+                      goto err;
-+                      }
++      if (!ENGINE_set_id(e, engine_pk11_id) ||
++          !ENGINE_set_name(e, engine_pk11_name))
++              return (0);
 +
-+              if (objcnt > 1)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_TOO_MANY_OBJECTS);
-+                      goto err;
-+                      }
++      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 */
++              }
 +
-+              if (objcnt != 1)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_OBJECT_NOT_FOUND);
-+                      goto err;
-+                      }
++      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);
 +
-+              (void) pFuncList->C_FindObjectsFinal(sp->session);
-+              UNLOCK_OBJSTORE(OP_RSA);
++      /* Ensure the pk11 error handling is set up */
++      ERR_load_pk11_strings();
 +
-+              if (hndidx_rsa == -1)
-+                      hndidx_rsa = RSA_get_ex_new_index(0,
-+                                      "pkcs11 RSA HSM key handle",
-+                                      NULL, NULL, NULL);
++      return (1);
++      }
 +
-+              pkey = EVP_PKEY_new();
-+              if (pkey == NULL)
-+                      goto err;
++/* Dynamic engine support is disabled at a higher level for Solaris */
++#ifdef        ENGINE_DYNAMIC_SUPPORT
++#error        "dynamic engine not supported"
++static int bind_helper(ENGINE *e, const char *id)
++      {
++      if (id && (strcmp(id, engine_pk11_id) != 0))
++              return (0);
 +
-+              rsa = RSA_new_method(e);
-+              if (rsa == NULL) {
-+                      EVP_PKEY_free(pkey);
-+                      pkey = NULL;
-+                      goto err;
-+              }
-+              EVP_PKEY_set1_RSA(pkey, rsa);
++      if (!bind_pk11(e))
++              return (0);
 +
-+              if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
-+                  get_templ, 2)) != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
-+                                       PK11_R_GETATTRIBUTVALUE, rv);
-+                      EVP_PKEY_free(pkey);
-+                      pkey = NULL;
-+                      goto err;
-+                      }
++      return (1);
++      }
 +
-+              /*
-+               * Now we have to initialize an OpenSSL RSA structure,
-+               * everything else is 0 or NULL.
-+               */
-+              rsa->flags = RSA_FLAG_SIGN_VER | RSA_FLAG_EXT_PKEY;
-+              RSA_set_ex_data(rsa, hndidx_rsa, (void *) ks_key);
-+              (void) check_new_rsa_key_priv(sp, rsa);
-+              sp->opdata_rsa_priv = rsa;
-+              sp->opdata_rsa_priv_key = ks_key;
++IMPLEMENT_DYNAMIC_CHECK_FN()
++IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
 +
-+              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
-+              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
-+              }
-+      else if ((privkey = fopen(privkey_file, read_mode_flags)) != NULL)
-+              {
-+              pkey = PEM_read_PrivateKey(privkey, NULL, NULL, NULL);
-+              (void) fclose(privkey);
-+              if (pkey != NULL)
-+                      {
-+                      rsa = EVP_PKEY_get1_RSA(pkey);
-+                      if (rsa != NULL)
-+                              {
-+                              (void) check_new_rsa_key_priv(sp, rsa);
++#else
++static ENGINE *engine_pk11(void)
++      {
++      ENGINE *ret = ENGINE_new();
 +
-+                              h_priv_key = sp->opdata_rsa_priv_key =
-+                                  pk11_get_private_rsa_key(rsa,
-+                                  &sp->opdata_rsa_priv, &sp->opdata_rsa_d_num,
-+                                  sp->session);
-+                              if (h_priv_key == CK_INVALID_HANDLE)
-+                                      {
-+                                      EVP_PKEY_free(pkey);
-+                                      pkey = NULL;
-+                                      }
-+                              }
-+                      else
-+                              {
-+                              EVP_PKEY_free(pkey);
-+                              pkey = NULL;
-+                              }
-+                      }
++      if (!ret)
++              return (NULL);
++
++      if (!bind_pk11(ret))
++              {
++              ENGINE_free(ret);
++              return (NULL);
 +              }
 +
-+err:
-+      pk11_return_session(sp, OP_RSA);
-+      return (pkey);
++      return (ret);
 +      }
 +
-+/* load RSA public key from a file */
-+/* ARGSUSED */
-+EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
-+      UI_METHOD *ui_method, void *callback_data)
++void
++ENGINE_load_pk11(void)
 +      {
-+      EVP_PKEY *pkey = NULL;
-+      FILE *pubkey;
-+      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
-+      RSA *rsa;
-+      PK11_SESSION *sp;
-+      /* everything else below needed for key by reference extension */
-+      CK_RV rv;
-+      CK_ULONG objcnt = 0;
-+      CK_BBOOL is_token = TRUE;
-+      CK_BYTE attr_data[2][1024];
-+      CK_OBJECT_CLASS key_class = CKO_PUBLIC_KEY;
-+      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
-+      extern char *pk11_pin;
++      ENGINE *e_pk11 = NULL;
 +
-+      /* we look for public keys only */
-+      CK_ATTRIBUTE search_templ[] =
-+              {
-+              {CKA_TOKEN, &is_token, sizeof(is_token)},
-+              {CKA_CLASS, &key_class, sizeof(key_class)},
-+              {CKA_LABEL, NULL, 0}
-+              };
++      /*
++       * 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);
 +
-+      /* these attributes are needed to initialize OpenSSL RSA structure */
-+      CK_ATTRIBUTE get_templ[] =
++      if (pk11_dso == NULL)
 +              {
-+              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
-+              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
-+              };
++              PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
++              return;
++              }
 +
-+      if ((sp = pk11_get_session(OP_RSA)) == NULL)
-+              return (NULL);
++      e_pk11 = engine_pk11();
++      if (!e_pk11)
++              {
++              DSO_free(pk11_dso);
++              pk11_dso = NULL;
++              return;
++              }
 +
 +      /*
-+       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
++       * 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 (strstr(pubkey_file, "pkcs11:") == pubkey_file)
++      if (!pk11_library_init(e_pk11))
 +              {
-+              search_templ[2].pValue = strstr(pubkey_file, ":") + 1;
-+              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
++              DSO_free(pk11_dso);
++              pk11_dso = NULL;
++              ENGINE_free(e_pk11);
++              return;
++              }
 +
-+#define ALLWAYS_LOGIN
-+#ifdef ALLWAYS_LOGIN
-+              if (pk11_pin == NULL)
-+                      {
-+                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
++      ENGINE_add(e_pk11);
 +
-+                      if (pk11_pin == NULL)
-+                              {
-+                              PK11err(PK11_F_LOAD_PUBKEY, PK11_R_MALLOC_FAILURE);
-+                              goto err;
-+                              }
-+                      }
-+              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
-+                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
-+                      {
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_INVALID_PIN, rv);
-+                      goto err;
-+                      }
-+#endif
++      ENGINE_free(e_pk11);
++      ERR_clear_error();
++      }
++#endif        /* ENGINE_DYNAMIC_SUPPORT */
 +
-+              LOCK_OBJSTORE(OP_RSA);
-+              if (pFuncList->C_FindObjectsInit(sp->session, search_templ, 3) != CKR_OK)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_FINDOBJECTSINIT, rv);
-+                      goto err;
-+                      }
-+              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
-+              if (rv != CKR_OK)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_FINDOBJECTS, rv);
-+                      goto err;
-+                      }
++/*
++ * 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;
 +
-+              if (objcnt > 1)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_TOO_MANY_OBJECTS);
-+                      goto err;
-+                      }
++static const char *get_PK11_LIBNAME(void)
++      {
++      if (PK11_LIBNAME)
++              return (PK11_LIBNAME);
 +
-+              if (objcnt != 1)
-+                      {
-+                      UNLOCK_OBJSTORE(OP_RSA);
-+                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_OBJECT_NOT_FOUND);
-+                      goto err;
-+                      }
++      return (def_PK11_LIBNAME);
++      }
 +
-+              (void) pFuncList->C_FindObjectsFinal(sp->session);
-+              UNLOCK_OBJSTORE(OP_RSA);
++static void free_PK11_LIBNAME(void)
++      {
++      if (PK11_LIBNAME)
++              OPENSSL_free((void*)PK11_LIBNAME);
 +
-+              sp->opdata_rsa_pub_key = ks_key;
-+              pkey = EVP_PKEY_new();
-+              if (pkey == NULL)
-+                      goto err;
++      PK11_LIBNAME = NULL;
++      }
 +
-+              rsa = RSA_new_method(e);
-+              if (rsa == NULL) {
-+                      EVP_PKEY_free(pkey);
-+                      pkey = NULL;
-+                      goto err;
-+              }
-+              EVP_PKEY_set1_RSA(pkey, rsa);
++static long set_PK11_LIBNAME(const char *name)
++      {
++      free_PK11_LIBNAME();
 +
-+              if (pFuncList->C_GetAttributeValue(sp->session, ks_key,
-+                  get_templ, 2) != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
-+                                       PK11_R_GETATTRIBUTVALUE, rv);
-+                      goto err;
-+                      }
++      return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
++      }
 +
-+              /*
-+               * Now we have to initialize an OpenSSL RSA structure,
-+               * everything else is 0 or NULL.
-+               */
-+              rsa->flags = RSA_FLAG_SIGN_VER;
-+              (void) check_new_rsa_key_pub(sp, rsa);
-+              sp->opdata_rsa_pub = rsa;
++/* acquire all engine specific mutexes before fork */
++static void pk11_fork_prepare(void)
++      {
++#ifndef NOPTHREADS
++      int i;
 +
-+              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
-+              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
-+              }
-+      else if ((pubkey = fopen(pubkey_file, read_mode_flags)) != NULL)
-+              {
-+              pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
-+              (void) fclose(pubkey);
-+              if (pkey != NULL)
-+                      {
-+                      rsa = EVP_PKEY_get1_RSA(pkey);
-+                      if (rsa != NULL)
-+                              {
-+                              (void) check_new_rsa_key_pub(sp, rsa);
++      if (!pk11_library_initialized)
++              return;
 +
-+                              h_pub_key = sp->opdata_rsa_pub_key =
-+                                  pk11_get_public_rsa_key(rsa,
-+                                  &sp->opdata_rsa_pub, &sp->opdata_rsa_n_num,
-+                                  &sp->opdata_rsa_e_num, sp->session);
-+                              if (h_pub_key == CK_INVALID_HANDLE)
-+                                      {
-+                                      EVP_PKEY_free(pkey);
-+                                      pkey = NULL;
-+                                      }
-+                              }
-+                      else
-+                              {
-+                              EVP_PKEY_free(pkey);
-+                              pkey = NULL;
-+                              }
-+                      }
++      LOCK_OBJSTORE(OP_RSA);
++      for (i = 0; i < OP_MAX; i++)
++              {
++              (void) pthread_mutex_lock(session_cache[i].lock);
 +              }
++#endif
++      }
 +
-+err:
-+      pk11_return_session(sp, OP_RSA);
-+      return (pkey);
++/* release all engine specific mutexes */
++static void pk11_fork_parent(void)
++      {
++#ifndef NOPTHREADS
++      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_RSA);
++#endif
 +      }
 +
 +/*
-+ * Create a public key object in a session from a given rsa structure.
-+ * The *rsa_n_num and *rsa_e_num pointers are non-NULL for RSA public keys.
++ * same situation as in parent - we need to unlock all locks to make them
++ * accessible to all threads.
 + */
-+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA *rsa,
-+    RSA **key_ptr, BIGNUM **rsa_n_num, BIGNUM **rsa_e_num,
-+    CK_SESSION_HANDLE session)
++static void pk11_fork_child(void)
 +      {
-+      CK_RV rv;
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
-+      CK_ULONG found;
-+      CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
-+      CK_KEY_TYPE k_type = CKK_RSA;
-+      CK_ULONG ul_key_attr_count = 8;
-+      CK_BBOOL rollback = FALSE;
++#ifndef NOPTHREADS
++      int i;
 +
-+      CK_ATTRIBUTE  a_key_template[] =
++      if (!pk11_library_initialized)
++              return;
++
++      for (i = OP_MAX - 1; i >= 0; i--)
 +              {
-+              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
-+              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
-+              {CKA_TOKEN, &false, sizeof (true)},
-+              {CKA_ENCRYPT, &true, sizeof (true)},
-+              {CKA_VERIFY, &true, sizeof (true)},
-+              {CKA_VERIFY_RECOVER, &true, sizeof (true)},
-+              {CKA_MODULUS, (void *)NULL, 0},
-+              {CKA_PUBLIC_EXPONENT, (void *)NULL, 0}
-+              };
++              (void) pthread_mutex_unlock(session_cache[i].lock);
++              }
++      UNLOCK_OBJSTORE(OP_RSA);
++#endif
++      }
++
++/* 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;
++      int any_slot_found;
 +      int i;
++#ifndef OPENSSL_SYS_WIN32
++      struct sigaction sigint_act, sigterm_act, sighup_act;
++#endif
 +
-+      a_key_template[0].pValue = &o_key;
-+      a_key_template[1].pValue = &k_type;
++      /*
++       * 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();
++                      }
++              }
 +
-+      a_key_template[6].ulValueLen = BN_num_bytes(rsa->n);
-+      a_key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
-+              (size_t)a_key_template[6].ulValueLen);
-+      if (a_key_template[6].pValue == NULL)
++      if (pk11_dso == NULL)
 +              {
-+              PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
++              PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
++              goto err;
 +              }
 +
-+      BN_bn2bin(rsa->n, a_key_template[6].pValue);
-+
-+      a_key_template[7].ulValueLen = BN_num_bytes(rsa->e);
-+      a_key_template[7].pValue = (CK_VOID_PTR)OPENSSL_malloc(
-+              (size_t)a_key_template[7].ulValueLen);
-+      if (a_key_template[7].pValue == NULL)
++      /* 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_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
++              PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
++              goto err;
 +              }
 +
-+      BN_bn2bin(rsa->e, a_key_template[7].pValue);
-+
-+      /* see find_lock array definition for more info on object locking */
-+      LOCK_OBJSTORE(OP_RSA);
-+      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
-+              ul_key_attr_count);
-+
++      /* get the full function list from the loaded library */
++      rv = p(&pFuncList);
 +      if (rv != CKR_OK)
 +              {
-+              PK11err_add_data(PK11_F_GET_PUB_RSA_KEY, PK11_R_FINDOBJECTSINIT,
-+                  rv);
++              PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE, rv);
 +              goto err;
 +              }
 +
-+      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
++#ifndef OPENSSL_SYS_WIN32
++      /* Not all PKCS#11 library are signal safe! */
 +
-+      if (rv != CKR_OK)
++      (void) memset(&sigint_act, 0, sizeof(sigint_act));
++      (void) memset(&sigterm_act, 0, sizeof(sigterm_act));
++      (void) memset(&sighup_act, 0, sizeof(sighup_act));
++      (void) sigaction(SIGINT, NULL, &sigint_act);
++      (void) sigaction(SIGTERM, NULL, &sigterm_act);
++      (void) sigaction(SIGHUP, NULL, &sighup_act);
++#endif
++      rv = pFuncList->C_Initialize(NULL_PTR);
++#ifndef OPENSSL_SYS_WIN32
++      (void) sigaction(SIGINT, &sigint_act, NULL);
++      (void) sigaction(SIGTERM, &sigterm_act, NULL);
++      (void) sigaction(SIGHUP, &sighup_act, NULL);
++#endif
++      if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
 +              {
-+              PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
-+                  PK11_R_FINDOBJECTS, rv);
++              PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
 +              goto err;
 +              }
 +
-+      rv = pFuncList->C_FindObjectsFinal(session);
-+
++      rv = pFuncList->C_GetInfo(&info);
 +      if (rv != CKR_OK)
 +              {
-+              PK11err_add_data(PK11_F_GET_PUB_RSA_KEY,
-+                  PK11_R_FINDOBJECTSFINAL, rv);
++              PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
 +              goto err;
 +              }
 +
-+      if (found == 0)
++      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)
 +              {
-+              rv = pFuncList->C_CreateObject(session,
-+                      a_key_template, ul_key_attr_count, &h_key);
++              /* 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_GET_PUB_RSA_KEY,
-+                          PK11_R_CREATEOBJECT, rv);
++                      PK11err_add_data(PK11_F_LIBRARY_INIT,
++                          PK11_R_OPENSESSION, rv);
 +                      goto err;
 +                      }
 +              }
 +
-+      if (rsa_n_num != NULL)
-+              if ((*rsa_n_num = BN_dup(rsa->n)) == NULL)
-+                      {
-+                      PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
-+                      rollback = TRUE;
-+                      goto err;
-+                      }
-+      if (rsa_e_num != NULL)
-+              if ((*rsa_e_num = BN_dup(rsa->e)) == NULL)
++      pk11_library_initialized = 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;
++
++#ifndef NOPTHREADS
++      if (!pk11_atfork_initialized)
++              {
++              if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
++                  pk11_fork_child) != 0)
 +                      {
-+                      PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
-+                      BN_free(*rsa_n_num);
-+                      *rsa_n_num = NULL;
-+                      rollback = TRUE;
++                      PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
 +                      goto err;
 +                      }
-+
-+      /* LINTED: E_CONSTANT_CONDITION */
-+      KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
-+      if (key_ptr != NULL)
-+              *key_ptr = rsa;
-+
-+err:
-+      if (rollback)
-+              {
-+              /*
-+               * We do not care about the return value from C_DestroyObject()
-+               * since we are doing rollback.
-+               */
-+              if (found == 0)
-+                      (void) pFuncList->C_DestroyObject(session, h_key);
-+              h_key = CK_INVALID_HANDLE;
++              pk11_atfork_initialized = TRUE;
 +              }
++#endif
 +
-+      UNLOCK_OBJSTORE(OP_RSA);
++      return (1);
 +
-+malloc_err:
-+      for (i = 6; i <= 7; i++)
-+              {
-+              if (a_key_template[i].pValue != NULL)
-+                      {
-+                      OPENSSL_free(a_key_template[i].pValue);
-+                      a_key_template[i].pValue = NULL;
-+                      }
-+              }
++err:
++      return (0);
++      }
 +
-+      return (h_key);
++/* Destructor (complements the "ENGINE_pk11()" constructor) */
++/* ARGSUSED */
++static int pk11_destroy(ENGINE *e)
++      {
++      free_PK11_LIBNAME();
++      ERR_unload_pk11_strings();
++      if (pk11_pin) {
++              memset(pk11_pin, 0, strlen(pk11_pin));
++              OPENSSL_free((void*)pk11_pin);
++      }
++      pk11_pin = NULL;
++      return (1);
 +      }
 +
 +/*
-+ * Create a private key object in the session from a given rsa structure.
-+ * The *rsa_d_num pointer is non-NULL for RSA private keys.
++ * Termination function to clean up the session, the token, and the pk11
++ * library.
 + */
-+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA *rsa,
-+    RSA **key_ptr, BIGNUM **rsa_d_num, CK_SESSION_HANDLE session)
++/* ARGSUSED */
++static int pk11_finish(ENGINE *e)
 +      {
-+      CK_RV rv;
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
 +      int i;
-+      CK_ULONG found;
-+      CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
-+      CK_KEY_TYPE k_type = CKK_RSA;
-+      CK_ULONG ul_key_attr_count = 14;
-+      CK_BBOOL rollback = FALSE;
-+
-+      /* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys */
-+      CK_ATTRIBUTE  a_key_template[] =
-+              {
-+              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
-+              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
-+              {CKA_TOKEN, &false, sizeof (true)},
-+              {CKA_SENSITIVE, &false, sizeof (true)},
-+              {CKA_DECRYPT, &true, sizeof (true)},
-+              {CKA_SIGN, &true, sizeof (true)},
-+              {CKA_MODULUS, (void *)NULL, 0},
-+              {CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
-+              {CKA_PRIVATE_EXPONENT, (void *)NULL, 0},
-+              {CKA_PRIME_1, (void *)NULL, 0},
-+              {CKA_PRIME_2, (void *)NULL, 0},
-+              {CKA_EXPONENT_1, (void *)NULL, 0},
-+              {CKA_EXPONENT_2, (void *)NULL, 0},
-+              {CKA_COEFFICIENT, (void *)NULL, 0}
-+              };
 +
-+      if ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0) {
-+              h_key = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, hndidx_rsa);
-+              LOCK_OBJSTORE(OP_RSA);
-+              goto set;
++      if (pk11_pin) {
++              memset(pk11_pin, 0, strlen(pk11_pin));
++              OPENSSL_free((void*)pk11_pin);
 +      }
-+      
-+      a_key_template[0].pValue = &o_key;
-+      a_key_template[1].pValue = &k_type;
++      pk11_pin = NULL;
 +
-+      /* Put the private key components into the template */
-+      if (init_template_value(rsa->n, &a_key_template[6].pValue,
-+              &a_key_template[6].ulValueLen) == 0 ||
-+          init_template_value(rsa->e, &a_key_template[7].pValue,
-+              &a_key_template[7].ulValueLen) == 0 ||
-+          init_template_value(rsa->d, &a_key_template[8].pValue,
-+              &a_key_template[8].ulValueLen) == 0 ||
-+          init_template_value(rsa->p, &a_key_template[9].pValue,
-+              &a_key_template[9].ulValueLen) == 0 ||
-+          init_template_value(rsa->q, &a_key_template[10].pValue,
-+              &a_key_template[10].ulValueLen) == 0 ||
-+          init_template_value(rsa->dmp1, &a_key_template[11].pValue,
-+              &a_key_template[11].ulValueLen) == 0 ||
-+          init_template_value(rsa->dmq1, &a_key_template[12].pValue,
-+              &a_key_template[12].ulValueLen) == 0 ||
-+          init_template_value(rsa->iqmp, &a_key_template[13].pValue,
-+              &a_key_template[13].ulValueLen) == 0)
++      if (pk11_dso == NULL)
 +              {
-+              PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
++              PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
++              goto err;
 +              }
 +
-+      /* see find_lock array definition for more info on object locking */
-+      LOCK_OBJSTORE(OP_RSA);
-+      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
-+              ul_key_attr_count);
++      OPENSSL_assert(pFuncList != NULL);
 +
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
-+                  PK11_R_FINDOBJECTSINIT, rv);
++      if (pk11_free_all_sessions() == 0)
 +              goto err;
-+              }
 +
-+      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
++      /* 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;
 +
-+      if (rv != CKR_OK)
++      /*
++       * Since we are part of a library (libcrypto.so), calling this function
++       * may have side-effects.
++       */
++#if 0
++      pFuncList->C_Finalize(NULL);
++#endif
++
++      if (!DSO_free(pk11_dso))
 +              {
-+              PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
-+                  PK11_R_FINDOBJECTS, rv);
++              PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
 +              goto err;
 +              }
++      pk11_dso = NULL;
++      pFuncList = NULL;
++      pk11_library_initialized = 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();
 +
-+      rv = pFuncList->C_FindObjectsFinal(session);
++      return (1);
 +
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
-+                  PK11_R_FINDOBJECTSFINAL, rv);
-+              goto err;
-+              }
++err:
++      return (0);
++      }
 +
-+      if (found == 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)(void))
++      {
++      int initialized = ((pk11_dso == NULL) ? 0 : 1);
++
++      switch (cmd)
 +              {
-+              rv = pFuncList->C_CreateObject(session,
-+                      a_key_template, ul_key_attr_count, &h_key);
-+              if (rv != CKR_OK)
++      case PK11_CMD_SO_PATH:
++              if (p == NULL)
 +                      {
-+                      PK11err_add_data(PK11_F_GET_PRIV_RSA_KEY,
-+                              PK11_R_CREATEOBJECT, rv);
-+                      goto err;
++                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
++                      return (0);
 +                      }
-+              }
 +
-+set:
-+      if (rsa_d_num != NULL)
-+              {
-+              if (rsa->d == NULL)
-+                      *rsa_d_num = NULL;
-+              else if ((*rsa_d_num = BN_dup(rsa->d)) == NULL)
++              if (initialized)
 +                      {
-+                      PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
-+                      rollback = TRUE;
-+                      goto err;
++                      PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
++                      return (0);
 +                      }
-+              }
 +
-+      /* LINTED: E_CONSTANT_CONDITION */
-+      KEY_HANDLE_REFHOLD(h_key, OP_RSA, FALSE, rollback, err);
-+      if (key_ptr != NULL)
-+              *key_ptr = rsa;
-+
-+err:
-+      if (rollback)
-+              {
-+              /*
-+               * We do not care about the return value from C_DestroyObject()
-+               * since we are doing rollback.
-+               */
-+              if (found == 0 &&
-+                  (rsa->flags & RSA_FLAG_EXT_PKEY) == 0)
-+                      (void) pFuncList->C_DestroyObject(session, h_key);
-+              h_key = CK_INVALID_HANDLE;
++              return (set_PK11_LIBNAME((const char *)p));
++      case PK11_CMD_PIN:
++              if (pk11_pin) {
++                      memset(pk11_pin, 0, strlen(pk11_pin));
++                      OPENSSL_free((void*)pk11_pin);
 +              }
++              pk11_pin = NULL;
 +
-+      UNLOCK_OBJSTORE(OP_RSA);
++              if (p == NULL)
++                      {
++                      PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
++                      return (0);
++                      }
 +
-+malloc_err:
-+      /*
-+       * 6 to 13 entries in the key template are key components.
-+       * They need to be freed apon exit or error.
-+       */
-+      for (i = 6; i <= 13; i++)
-+              {
-+              if (a_key_template[i].pValue != NULL)
++              pk11_pin = BUF_strdup(p);
++              if (pk11_pin == NULL)
 +                      {
-+                      (void) memset(a_key_template[i].pValue, 0,
-+                              a_key_template[i].ulValueLen);
-+                      OPENSSL_free(a_key_template[i].pValue);
-+                      a_key_template[i].pValue = NULL;
++                      PK11err(PK11_F_GET_SESSION, PK11_R_MALLOC_FAILURE);
++                      return (0);
 +                      }
++              return (1);
++      case PK11_CMD_SLOT:
++              SLOTID = (CK_SLOT_ID)i;
++#ifdef DEBUG_SLOT_SELECTION
++              fprintf(stderr, "%s: slot set\n", PK11_DBG);
++#endif
++              return (1);
++      default:
++              break;
 +              }
 +
-+      return (h_key);
++      PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
++
++      return (0);
 +      }
 +
-+/*
-+ * Check for cache miss and clean the object pointer and handle
-+ * in such case. Return 1 for cache hit, 0 for cache miss.
-+ */
-+static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa)
++
++/* Required function by the engine random interface. It does nothing here */
++static void pk11_rand_cleanup(void)
 +      {
-+      /*
-+       * Provide protection against RSA structure reuse by making the
-+       * check for cache hit stronger. Only public components of RSA
-+       * key matter here so it is sufficient to compare them with values
-+       * cached in PK11_SESSION structure.
-+       */
-+      if ((sp->opdata_rsa_pub != rsa) ||
-+          (BN_cmp(sp->opdata_rsa_n_num, rsa->n) != 0) ||
-+          (BN_cmp(sp->opdata_rsa_e_num, rsa->e) != 0))
-+              {
-+              /*
-+               * We do not check the return value because even in case of
-+               * failure the sp structure will have both key pointer
-+               * and object handle cleaned and pk11_destroy_object()
-+               * reports the failure to the OpenSSL error message buffer.
-+               */
-+              (void) pk11_destroy_rsa_object_pub(sp, TRUE);
-+              return (0);
-+              }
-+      return (1);
++      return;
 +      }
 +
-+/*
-+ * Check for cache miss and clean the object pointer and handle
-+ * in such case. Return 1 for cache hit, 0 for cache miss.
-+ */
-+static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa)
++/* 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;
++
 +      /*
-+       * Provide protection against RSA structure reuse by making the
-+       * check for cache hit stronger. Comparing private exponent of RSA
-+       * key with value cached in PK11_SESSION structure should
-+       * be sufficient.
++       * Ignore any errors (e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
++       * the calling functions do not care anyway
 +       */
-+      if ((sp->opdata_rsa_priv != rsa) ||
-+          (BN_cmp(sp->opdata_rsa_d_num, rsa->d) != 0) ||
-+          ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0))
++      pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
++      pk11_return_session(sp, OP_RAND);
++
++      return;
++      }
++
++static void pk11_rand_seed(const void *buf, int num)
++      {
++      pk11_rand_add(buf, num, 0);
++      }
++
++static int pk11_rand_bytes(unsigned char *buf, int num)
++      {
++      CK_RV rv;
++      PK11_SESSION *sp;
++
++      if ((sp = pk11_get_session(OP_RAND)) == NULL)
++              return (0);
++
++      rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
++      if (rv != CKR_OK)
 +              {
-+              /*
-+               * We do not check the return value because even in case of
-+               * failure the sp structure will have both key pointer
-+               * and object handle cleaned and pk11_destroy_object()
-+               * reports the failure to the OpenSSL error message buffer.
-+               */
-+              (void) pk11_destroy_rsa_object_priv(sp, TRUE);
++              PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
++              pk11_return_session(sp, OP_RAND);
 +              return (0);
 +              }
++
++      pk11_return_session(sp, OP_RAND);
 +      return (1);
 +      }
-+#endif
 +
-+#ifndef OPENSSL_NO_DSA
-+/* The DSA function implementation */
-+/* ARGSUSED */
-+static int pk11_DSA_init(DSA *dsa)
++/* Required function by the engine random interface. It does nothing here */
++static int pk11_rand_status(void)
 +      {
 +      return (1);
 +      }
 +
-+/* ARGSUSED */
-+static int pk11_DSA_finish(DSA *dsa)
++/* Free all BIGNUM structures from PK11_SESSION. */
++static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
 +      {
-+      return (1);
++      switch (optype)
++              {
++              case OP_RSA:
++                      if (sp->opdata_rsa_n_num != NULL)
++                              {
++                              BN_free(sp->opdata_rsa_n_num);
++                              sp->opdata_rsa_n_num = NULL;
++                              }
++                      if (sp->opdata_rsa_e_num != NULL)
++                              {
++                              BN_free(sp->opdata_rsa_e_num);
++                              sp->opdata_rsa_e_num = NULL;
++                              }
++                      if (sp->opdata_rsa_d_num != NULL)
++                              {
++                              BN_free(sp->opdata_rsa_d_num);
++                              sp->opdata_rsa_d_num = NULL;
++                              }
++                      break;
++              default:
++                      break;
++              }
 +      }
 +
-+
-+static DSA_SIG *
-+pk11_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
++/*
++ * Get new PK11_SESSION structure ready for use. Every process must have
++ * its own freelist of PK11_SESSION structures so handle fork() here
++ * by destroying the old and creating new freelist.
++ * The returned PK11_SESSION structure is disconnected from the freelist.
++ */
++PK11_SESSION *
++pk11_get_session(PK11_OPTYPE optype)
 +      {
-+      BIGNUM *r = NULL, *s = NULL;
-+      int i;
-+      DSA_SIG *dsa_sig = NULL;
-+
++      PK11_SESSION *sp = NULL, *sp1, *freelist;
++#ifndef NOPTHREADS
++      pthread_mutex_t *freelist_lock = NULL;
++#endif
 +      CK_RV rv;
-+      CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
-+      CK_MECHANISM *p_mech = &Mechanism_dsa;
-+      CK_OBJECT_HANDLE h_priv_key;
++
++      switch (optype)
++              {
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++              case OP_RAND:
++              case OP_DIGEST:
++              case OP_CIPHER:
++#ifndef NOPTHREADS
++                      freelist_lock = session_cache[optype].lock;
++#endif
++                      break;
++              default:
++                      PK11err(PK11_F_GET_SESSION,
++                              PK11_R_INVALID_OPERATION_TYPE);
++                      return (NULL);
++              }
++#ifndef NOPTHREADS
++      (void) pthread_mutex_lock(freelist_lock);
++#else
++      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      freelist = session_cache[optype].head;
++      sp = freelist;
 +
 +      /*
-+       * The signature is the concatenation of r and s,
-+       * each is 20 bytes long
++       * If the free list is empty, allocate new unitialized (filled
++       * with zeroes) PK11_SESSION structure otherwise return first
++       * structure from the freelist.
 +       */
-+      unsigned char sigret[DSA_SIGNATURE_LEN];
-+      unsigned long siglen = DSA_SIGNATURE_LEN;
-+      unsigned int siglen2 = DSA_SIGNATURE_LEN / 2;
-+
-+      PK11_SESSION *sp = NULL;
-+
-+      if ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))
++      if (sp == NULL)
 +              {
-+              PK11err(PK11_F_DSA_SIGN, PK11_R_MISSING_KEY_COMPONENT);
-+              goto ret;
++              if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
++                      {
++                      PK11err(PK11_F_GET_SESSION,
++                              PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
++              (void) memset(sp, 0, sizeof (PK11_SESSION));
 +              }
-+
-+      i = BN_num_bytes(dsa->q); /* should be 20 */
-+      if (dlen > i)
++      else
 +              {
-+              PK11err(PK11_F_DSA_SIGN, PK11_R_INVALID_SIGNATURE_LENGTH);
-+              goto ret;
++              freelist = sp->next;
 +              }
 +
-+      if ((sp = pk11_get_session(OP_DSA)) == NULL)
-+              goto ret;
++      if (sp->pid != 0 && sp->pid != getpid())
++              {
++              /*
++               * We are a new process and thus need to free any inherited
++               * PK11_SESSION objects.
++               */
++              while ((sp1 = freelist) != NULL)
++                      {
++                      freelist = sp1->next;
++                      /*
++                       * NOTE: we do not want to call pk11_free_all_sessions()
++                       * here because it would close underlying PKCS#11
++                       * sessions and destroy all objects.
++                       */
++                      pk11_free_nums(sp1, optype);
++                      OPENSSL_free(sp1);
++                      }
 +
-+      (void) check_new_dsa_key_priv(sp, dsa);
++              /* we have to free the active list as well. */
++              pk11_free_active_list(optype);
 +
-+      h_priv_key = sp->opdata_dsa_priv_key;
-+      if (h_priv_key == CK_INVALID_HANDLE)
-+              h_priv_key = sp->opdata_dsa_priv_key =
-+                      pk11_get_private_dsa_key((DSA *)dsa,
-+                          &sp->opdata_dsa_priv,
-+                          &sp->opdata_dsa_priv_num, sp->session);
++              /* Initialize the process */
++              rv = pFuncList->C_Initialize(NULL_PTR);
++              if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
++                      {
++                      PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
++                          rv);
++                      OPENSSL_free(sp);
++                      sp = NULL;
++                      goto err;
++                      }
 +
-+      if (h_priv_key != CK_INVALID_HANDLE)
-+              {
-+              rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
++              /*
++               * Choose slot here since the slot table is different on this
++               * process. If we are here then we must have found at least one
++               * usable slot before so we don't need to check any_slot_found.
++               * See pk11_library_init()'s usage of this function for more
++               * information.
++               */
++              if (pk11_choose_slots(NULL) == 0)
++                      goto err;
 +
++              /* 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_DSA_SIGN, PK11_R_SIGNINIT, rv);
-+                      goto ret;
++                      PK11err_add_data(PK11_F_GET_SESSION, PK11_R_OPENSESSION,
++                          rv);
++                      OPENSSL_free(sp);
++                      sp = NULL;
++                      goto err;
 +                      }
 +
-+              (void) memset(sigret, 0, siglen);
-+              rv = pFuncList->C_Sign(sp->session,
-+                      (unsigned char*) dgst, dlen, sigret,
-+                      (CK_ULONG_PTR) &siglen);
-+
-+              if (rv != CKR_OK)
++              /* It is an inherited session and needs re-initialization. */
++              if (pk11_setup_session(sp, optype) == 0)
 +                      {
-+                      PK11err_add_data(PK11_F_DSA_SIGN, PK11_R_SIGN, rv);
-+                      goto ret;
++                      OPENSSL_free(sp);
++                      sp = NULL;
 +                      }
 +              }
-+
-+
-+      if ((s = BN_new()) == NULL)
++      if (sp->pid == 0)
 +              {
-+              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
-+              goto ret;
++              /* It is a new session and needs initialization. */
++              if (pk11_setup_session(sp, optype) == 0)
++                      {
++                      OPENSSL_free(sp);
++                      sp = NULL;
++                      }
 +              }
 +
-+      if ((r = BN_new()) == NULL)
++      /* set new head for the list of PK11_SESSION objects */
++      session_cache[optype].head = freelist;
++
++err:
++      if (sp != NULL)
++              sp->next = NULL;
++
++#ifndef NOPTHREADS
++      (void) pthread_mutex_unlock(freelist_lock);
++#else
++      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++
++      return (sp);
++      }
++
++
++void
++pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
++      {
++#ifndef NOPTHREADS
++      pthread_mutex_t *freelist_lock;
++#endif
++      PK11_SESSION *freelist;
++
++      if (sp == NULL || sp->pid != getpid())
++              return;
++
++      switch (optype)
 +              {
-+              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
-+              goto ret;
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++              case OP_RAND:
++              case OP_DIGEST:
++              case OP_CIPHER:
++#ifndef NOPTHREADS
++                      freelist_lock = session_cache[optype].lock;
++#endif
++                      break;
++              default:
++                      PK11err(PK11_F_RETURN_SESSION,
++                              PK11_R_INVALID_OPERATION_TYPE);
++                      return;
 +              }
 +
-+      if ((dsa_sig = DSA_SIG_new()) == NULL)
++#ifndef NOPTHREADS
++      (void) pthread_mutex_lock(freelist_lock);
++#else
++      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      freelist = session_cache[optype].head;
++      sp->next = freelist;
++      session_cache[optype].head = sp;
++#ifndef NOPTHREADS
++      (void) pthread_mutex_unlock(freelist_lock);
++#else
++      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      }
++
++
++/* Destroy all objects. This function is called when the engine is finished */
++static int pk11_free_all_sessions()
++      {
++      int ret = 1;
++      int type;
++
++      (void) pk11_destroy_rsa_key_objects(NULL);
++
++      /*
++       * We try to release as much as we can but any error means that we will
++       * return 0 on exit.
++       */
++      for (type = 0; type < OP_MAX; type++)
 +              {
-+              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
-+              goto ret;
++              if (pk11_free_session_list(type) == 0)
++                      ret = 0;
 +              }
 +
-+      if (BN_bin2bn(sigret, siglen2, r) == NULL ||
-+          BN_bin2bn(&sigret[siglen2], siglen2, s) == NULL)
++      return (ret);
++      }
++
++/*
++ * Destroy session structures from the linked list specified. Free as many
++ * sessions as possible but any failure in C_CloseSession() means that we
++ * return an error on return.
++ */
++static int pk11_free_session_list(PK11_OPTYPE optype)
++      {
++      CK_RV rv;
++      PK11_SESSION *sp = NULL;
++      PK11_SESSION *freelist = NULL;
++      pid_t mypid = getpid();
++#ifndef NOPTHREADS
++      pthread_mutex_t *freelist_lock;
++#endif
++      int ret = 1;
++
++      switch (optype)
 +              {
-+              PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
-+              goto ret;
++              case OP_RSA:
++              case OP_DSA:
++              case OP_DH:
++              case OP_RAND:
++              case OP_DIGEST:
++              case OP_CIPHER:
++#ifndef NOPTHREADS
++                      freelist_lock = session_cache[optype].lock;
++#endif
++                      break;
++              default:
++                      PK11err(PK11_F_FREE_ALL_SESSIONS,
++                              PK11_R_INVALID_OPERATION_TYPE);
++                      return (0);
 +              }
 +
-+      dsa_sig->r = r;
-+      dsa_sig->s = s;
-+
-+ret:
-+      if (dsa_sig == NULL)
++#ifndef NOPTHREADS
++      (void) pthread_mutex_lock(freelist_lock);
++#else
++      CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      freelist = session_cache[optype].head;
++      while ((sp = freelist) != NULL)
 +              {
-+              if (r != NULL)
-+                      BN_free(r);
-+              if (s != NULL)
-+                      BN_free(s);
++              if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
++                      {
++                      rv = pFuncList->C_CloseSession(sp->session);
++                      if (rv != CKR_OK)
++                              {
++                              PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
++                                      PK11_R_CLOSESESSION, rv);
++                              ret = 0;
++                              }
++                      }
++              freelist = sp->next;
++              pk11_free_nums(sp, optype);
++              OPENSSL_free(sp);
 +              }
 +
-+      pk11_return_session(sp, OP_DSA);
-+      return (dsa_sig);
++#ifndef NOPTHREADS
++      (void) pthread_mutex_unlock(freelist_lock);
++#else
++      CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++      return (ret);
 +      }
 +
-+static int
-+pk11_dsa_do_verify(const unsigned char *dgst, int dlen, DSA_SIG *sig,
-+      DSA *dsa)
++
++static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
 +      {
-+      int i;
 +      CK_RV rv;
-+      int retval = 0;
-+      CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
-+      CK_MECHANISM *p_mech = &Mechanism_dsa;
-+      CK_OBJECT_HANDLE h_pub_key;
-+
-+      unsigned char sigbuf[DSA_SIGNATURE_LEN];
-+      unsigned long siglen = DSA_SIGNATURE_LEN;
-+      unsigned long siglen2 = DSA_SIGNATURE_LEN/2;
-+
-+      PK11_SESSION *sp = NULL;
++      CK_SLOT_ID myslot;
 +
-+      if (BN_is_zero(sig->r) || sig->r->neg || BN_ucmp(sig->r, dsa->q) >= 0)
++      switch (optype)
 +              {
-+              PK11err(PK11_F_DSA_VERIFY,
-+                      PK11_R_INVALID_DSA_SIGNATURE_R);
-+              goto ret;
++              case OP_RSA:
++                      myslot = pubkey_SLOTID;
++                      break;
++              case OP_RAND:
++                      myslot = rand_SLOTID;
++                      break;
++              default:
++                      PK11err(PK11_F_SETUP_SESSION,
++                          PK11_R_INVALID_OPERATION_TYPE);
++                      return (0);
 +              }
 +
-+      if (BN_is_zero(sig->s) || sig->s->neg || BN_ucmp(sig->s, dsa->q) >= 0)
++      sp->session = CK_INVALID_HANDLE;
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
++#endif        /* DEBUG_SLOT_SELECTION */
++      rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
++              NULL_PTR, NULL_PTR, &sp->session);
++      if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
 +              {
-+              PK11err(PK11_F_DSA_VERIFY,
-+                      PK11_R_INVALID_DSA_SIGNATURE_S);
-+              goto ret;
++              /*
++               * We are probably a child process so force the
++               * reinitialize of the session
++               */
++              pk11_library_initialized = FALSE;
++              if (!pk11_library_init(NULL))
++                      return (0);
++              rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
++                      NULL_PTR, NULL_PTR, &sp->session);
++              }
++      if (rv != CKR_OK)
++              {
++              PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
++              return (0);
 +              }
 +
-+      i = BN_num_bytes(dsa->q); /* should be 20 */
++      sp->pid = getpid();
 +
-+      if (dlen > i)
++      if (optype == OP_RSA)
 +              {
-+              PK11err(PK11_F_DSA_VERIFY,
-+                      PK11_R_INVALID_SIGNATURE_LENGTH);
-+              goto ret;
++              sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
++              sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
++              sp->opdata_rsa_pub = NULL;
++              sp->opdata_rsa_n_num = NULL;
++              sp->opdata_rsa_e_num = NULL;
++              sp->opdata_rsa_priv = NULL;
++              sp->opdata_rsa_d_num = NULL;
 +              }
 +
-+      if ((sp = pk11_get_session(OP_DSA)) == NULL)
-+              goto ret;
-+
-+      (void) check_new_dsa_key_pub(sp, dsa);
++      return (1);
++      }
 +
-+      h_pub_key = sp->opdata_dsa_pub_key;
-+      if (h_pub_key == CK_INVALID_HANDLE)
-+              h_pub_key = sp->opdata_dsa_pub_key =
-+                      pk11_get_public_dsa_key((DSA *)dsa, &sp->opdata_dsa_pub,
-+                          &sp->opdata_dsa_pub_num, sp->session);
++/* Destroy RSA public key from single session. */
++int
++pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
++      {
++      int ret = 0;
 +
-+      if (h_pub_key != CK_INVALID_HANDLE)
++      if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
 +              {
-+              rv = pFuncList->C_VerifyInit(sp->session, p_mech,
-+                      h_pub_key);
-+
-+              if (rv != CKR_OK)
++              TRY_OBJ_DESTROY(sp->session, sp->opdata_rsa_pub_key,
++                  ret, uselock, OP_RSA);
++              sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
++              sp->opdata_rsa_pub = NULL;
++              if (sp->opdata_rsa_n_num != NULL)
 +                      {
-+                      PK11err_add_data(PK11_F_DSA_VERIFY, PK11_R_VERIFYINIT,
-+                          rv);
-+                      goto ret;
++                      BN_free(sp->opdata_rsa_n_num);
++                      sp->opdata_rsa_n_num = NULL;
 +                      }
-+
-+              /*
-+               * The representation of each of the two big numbers could
-+               * be shorter than DSA_SIGNATURE_LEN/2 bytes so we need
-+               * to act accordingly and shift if necessary.
-+               */
-+              (void) memset(sigbuf, 0, siglen);
-+              BN_bn2bin(sig->r, sigbuf + siglen2 - BN_num_bytes(sig->r));
-+              BN_bn2bin(sig->s, &sigbuf[siglen2] + siglen2 -
-+                  BN_num_bytes(sig->s));
-+
-+              rv = pFuncList->C_Verify(sp->session,
-+                      (unsigned char *) dgst, dlen, sigbuf, (CK_ULONG)siglen);
-+
-+              if (rv != CKR_OK)
++              if (sp->opdata_rsa_e_num != NULL)
 +                      {
-+                      PK11err_add_data(PK11_F_DSA_VERIFY, PK11_R_VERIFY, rv);
-+                      goto ret;
++                      BN_free(sp->opdata_rsa_e_num);
++                      sp->opdata_rsa_e_num = NULL;
 +                      }
 +              }
 +
-+      retval = 1;
-+ret:
-+
-+      pk11_return_session(sp, OP_DSA);
-+      return (retval);
++      return (ret);
 +      }
 +
-+
-+/*
-+ * Create a public key object in a session from a given dsa structure.
-+ * The *dsa_pub_num pointer is non-NULL for DSA public keys.
-+ */
-+static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa,
-+    DSA **key_ptr, BIGNUM **dsa_pub_num, CK_SESSION_HANDLE session)
++/* Destroy RSA private key from single session. */
++int
++pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
 +      {
-+      CK_RV rv;
-+      CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
-+      CK_ULONG found;
-+      CK_KEY_TYPE k_type = CKK_DSA;
-+      CK_ULONG ul_key_attr_count = 8;
-+      CK_BBOOL rollback = FALSE;
-+      int i;
-+
-+      CK_ATTRIBUTE  a_key_template[] =
-+              {
-+              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
-+              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
-+              {CKA_TOKEN, &false, sizeof (true)},
-+              {CKA_VERIFY, &true, sizeof (true)},
-+              {CKA_PRIME, (void *)NULL, 0},           /* p */
-+              {CKA_SUBPRIME, (void *)NULL, 0},        /* q */
-+              {CKA_BASE, (void *)NULL, 0},            /* g */
-+              {CKA_VALUE, (void *)NULL, 0}            /* pub_key - y */
-+              };
-+
-+      a_key_template[0].pValue = &o_key;
-+      a_key_template[1].pValue = &k_type;
++      int ret = 0;
 +
-+      if (init_template_value(dsa->p, &a_key_template[4].pValue,
-+              &a_key_template[4].ulValueLen) == 0 ||
-+          init_template_value(dsa->q, &a_key_template[5].pValue,
-+              &a_key_template[5].ulValueLen) == 0 ||
-+          init_template_value(dsa->g, &a_key_template[6].pValue,
-+              &a_key_template[6].ulValueLen) == 0 ||
-+          init_template_value(dsa->pub_key, &a_key_template[7].pValue,
-+              &a_key_template[7].ulValueLen) == 0)
++      if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
 +              {
-+              PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
++              TRY_OBJ_DELETE(sp->session,
++                             sp->opdata_rsa_priv_key,
++                             ret, uselock, OP_RSA);
++              sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
++              sp->opdata_rsa_priv = NULL;
++              if (sp->opdata_rsa_d_num != NULL)
++                      {
++                      BN_free(sp->opdata_rsa_d_num);
++                      sp->opdata_rsa_d_num = NULL;
++                      }
 +              }
 +
-+      /* see find_lock array definition for more info on object locking */
-+      LOCK_OBJSTORE(OP_DSA);
-+      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
-+              ul_key_attr_count);
-+
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_GET_PUB_DSA_KEY, PK11_R_FINDOBJECTSINIT,
-+                  rv);
-+              goto err;
-+              }
++      return (ret);
++      }
 +
-+      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
++/*
++ * Destroy RSA key object wrapper. If session is NULL, try to destroy all
++ * objects in the free list.
++ */
++int
++pk11_destroy_rsa_key_objects(PK11_SESSION *session)
++      {
++      int ret = 1;
++      PK11_SESSION *sp = NULL;
++      PK11_SESSION *local_free_session;
++      CK_BBOOL uselock = TRUE;
 +
-+      if (rv != CKR_OK)
++      if (session != NULL)
++              local_free_session = session;
++      else
 +              {
-+              PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
-+                  PK11_R_FINDOBJECTS, rv);
-+              goto err;
++#ifndef NOPTHREADS
++              (void) pthread_mutex_lock(session_cache[OP_RSA].lock);
++#else
++              CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
++              local_free_session = session_cache[OP_RSA].head;
++              uselock = FALSE;
 +              }
 +
-+      rv = pFuncList->C_FindObjectsFinal(session);
-+
-+      if (rv != CKR_OK)
++      /*
++       * go through the list of sessions and delete key objects
++       */
++      while ((sp = local_free_session) != NULL)
 +              {
-+              PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
-+                  PK11_R_FINDOBJECTSFINAL, rv);
-+              goto err;
-+              }
++              local_free_session = sp->next;
 +
-+      if (found == 0)
-+              {
-+              rv = pFuncList->C_CreateObject(session,
-+                      a_key_template, ul_key_attr_count, &h_key);
-+              if (rv != CKR_OK)
++              /*
++               * Do not terminate list traversal if one of the
++               * destroy operations fails.
++               */
++              if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
 +                      {
-+                      PK11err_add_data(PK11_F_GET_PUB_DSA_KEY,
-+                          PK11_R_CREATEOBJECT, rv);
-+                      goto err;
++                      ret = 0;
++                      continue;
 +                      }
-+              }
-+
-+      if (dsa_pub_num != NULL)
-+              if ((*dsa_pub_num = BN_dup(dsa->pub_key)) == NULL)
++              if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
 +                      {
-+                      PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_MALLOC_FAILURE);
-+                      rollback = TRUE;
-+                      goto err;
++                      ret = 0;
++                      continue;
 +                      }
-+
-+      /* LINTED: E_CONSTANT_CONDITION */
-+      KEY_HANDLE_REFHOLD(h_key, OP_DSA, FALSE, rollback, err);
-+      if (key_ptr != NULL)
-+              *key_ptr = dsa;
-+
-+err:
-+      if (rollback)
-+              {
-+              /*
-+               * We do not care about the return value from C_DestroyObject()
-+               * since we are doing rollback.
-+               */
-+              if (found == 0)
-+                      (void) pFuncList->C_DestroyObject(session, h_key);
-+              h_key = CK_INVALID_HANDLE;
 +              }
 +
-+      UNLOCK_OBJSTORE(OP_DSA);
++#ifndef NOPTHREADS
++      if (session == NULL)
++              (void) pthread_mutex_unlock(session_cache[OP_RSA].lock);
++#else
++      if (session == NULL)
++              CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
++#endif
 +
-+malloc_err:
-+      for (i = 4; i <= 7; i++)
++      return (ret);
++      }
++
++static int pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh)
++      {
++      CK_RV rv;
++      rv = pFuncList->C_DestroyObject(session, oh);
++      if (rv != CKR_OK)
 +              {
-+              if (a_key_template[i].pValue != NULL)
-+                      {
-+                      OPENSSL_free(a_key_template[i].pValue);
-+                      a_key_template[i].pValue = NULL;
-+                      }
++              PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
++                  rv);
++              return (0);
 +              }
 +
-+      return (h_key);
++      return (1);
 +      }
 +
++
 +/*
-+ * Create a private key object in the session from a given dsa structure
-+ * The *dsa_priv_num pointer is non-NULL for DSA private keys.
++ * Public key mechanisms optionally supported
++ *
++ * CKM_RSA_X_509
++ * CKM_RSA_PKCS
++ *
++ * The first slot that supports at least one of those mechanisms is chosen as a
++ * public key slot.
++ *
++ * The output of this function is a set of global variables indicating which
++ * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
++ * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
++ * variables carry information about which slot was chosen for (a) public key
++ * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
 + */
-+static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa,
-+    DSA **key_ptr, BIGNUM **dsa_priv_num, CK_SESSION_HANDLE session)
++static int
++pk11_choose_slots(int *any_slot_found)
 +      {
++      CK_SLOT_ID_PTR pSlotList = NULL_PTR;
++      CK_ULONG ulSlotCount = 0;
++      CK_MECHANISM_INFO mech_info;
++      CK_TOKEN_INFO token_info;
++      unsigned int i;
 +      CK_RV rv;
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
-+      CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
-+      int i;
-+      CK_ULONG found;
-+      CK_KEY_TYPE k_type = CKK_DSA;
-+      CK_ULONG ul_key_attr_count = 9;
-+      CK_BBOOL rollback = FALSE;
++      CK_SLOT_ID best_slot_sofar = 0;
++      CK_BBOOL found_candidate_slot = CK_FALSE;
++      CK_SLOT_ID current_slot = 0;
 +
-+      /* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys */
-+      CK_ATTRIBUTE  a_key_template[] =
-+              {
-+              {CKA_CLASS, (void *) NULL, sizeof (CK_OBJECT_CLASS)},
-+              {CKA_KEY_TYPE, (void *) NULL, sizeof (CK_KEY_TYPE)},
-+              {CKA_TOKEN, &false, sizeof (true)},
-+              {CKA_SENSITIVE, &false, sizeof (true)},
-+              {CKA_SIGN, &true, sizeof (true)},
-+              {CKA_PRIME, (void *)NULL, 0},           /* p */
-+              {CKA_SUBPRIME, (void *)NULL, 0},        /* q */
-+              {CKA_BASE, (void *)NULL, 0},            /* g */
-+              {CKA_VALUE, (void *)NULL, 0}            /* priv_key - x */
-+              };
++      /* let's initialize the output parameter */
++      if (any_slot_found != NULL)
++              *any_slot_found = 0;
 +
-+      a_key_template[0].pValue = &o_key;
-+      a_key_template[1].pValue = &k_type;
++      /* Get slot list for memory allocation */
++      rv = pFuncList->C_GetSlotList(0, NULL_PTR, &ulSlotCount);
 +
-+      /* Put the private key components into the template */
-+      if (init_template_value(dsa->p, &a_key_template[5].pValue,
-+              &a_key_template[5].ulValueLen) == 0 ||
-+          init_template_value(dsa->q, &a_key_template[6].pValue,
-+              &a_key_template[6].ulValueLen) == 0 ||
-+          init_template_value(dsa->g, &a_key_template[7].pValue,
-+              &a_key_template[7].ulValueLen) == 0 ||
-+          init_template_value(dsa->priv_key, &a_key_template[8].pValue,
-+              &a_key_template[8].ulValueLen) == 0)
++      if (rv != CKR_OK)
 +              {
-+              PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
++              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
++              return (0);
 +              }
 +
-+      /* see find_lock array definition for more info on object locking */
-+      LOCK_OBJSTORE(OP_DSA);
-+      rv = pFuncList->C_FindObjectsInit(session, a_key_template,
-+              ul_key_attr_count);
-+
-+      if (rv != CKR_OK)
++      /* it's not an error if we didn't find any providers */
++      if (ulSlotCount == 0)
 +              {
-+              PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
-+                  PK11_R_FINDOBJECTSINIT, rv);
-+              goto err;
++#ifdef        DEBUG_SLOT_SELECTION
++              fprintf(stderr, "%s: no crypto providers found\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
++              return (1);
 +              }
 +
-+      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
++      pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
++
++      if (pSlotList == NULL)
++              {
++              PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
++              return (0);
++              }
 +
++      /* Get the slot list for processing */
++      rv = pFuncList->C_GetSlotList(0, pSlotList, &ulSlotCount);
 +      if (rv != CKR_OK)
 +              {
-+              PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
-+                  PK11_R_FINDOBJECTS, rv);
-+              goto err;
++              PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
++              OPENSSL_free(pSlotList);
++              return (0);
 +              }
 +
-+      rv = pFuncList->C_FindObjectsFinal(session);
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
++      fprintf(stderr, "%s: number of slots: %d\n", PK11_DBG, ulSlotCount);
 +
-+      if (rv != CKR_OK)
++      fprintf(stderr, "%s: == checking rand slots ==\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
++      for (i = 0; i < ulSlotCount; i++)
 +              {
-+              PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
-+                  PK11_R_FINDOBJECTSFINAL, rv);
-+              goto err;
++              current_slot = pSlotList[i];
++
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
++#endif        /* DEBUG_SLOT_SELECTION */
++              /* Check if slot has random support. */
++              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
++              if (rv != CKR_OK)
++                      continue;
++
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
++#endif        /* DEBUG_SLOT_SELECTION */
++
++              if (token_info.flags & CKF_RNG)
++                      {
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: this token has CKF_RNG flag\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
++                      pk11_have_random = CK_TRUE;
++                      rand_SLOTID = current_slot;
++                      break;
++                      }
 +              }
 +
-+      if (found == 0)
-+              {
-+              rv = pFuncList->C_CreateObject(session,
-+                      a_key_template, ul_key_attr_count, &h_key);
-+              if (rv != CKR_OK)
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: == checking pubkey slots ==\n", PK11_DBG);
++#endif        /* DEBUG_SLOT_SELECTION */
++
++      pubkey_SLOTID = pSlotList[0];
++      for (i = 0; i < ulSlotCount; i++)
++              {
++              CK_BBOOL slot_has_rsa = CK_FALSE;
++              current_slot = pSlotList[i];
++
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: checking slot: %d\n", PK11_DBG, i);
++#endif        /* DEBUG_SLOT_SELECTION */
++              rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
++              if (rv != CKR_OK)
++                      continue;
++
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr, "%s: token label: %.32s\n", PK11_DBG, token_info.label);
++#endif        /* DEBUG_SLOT_SELECTION */
++
++              /*
++               * Check if this slot is capable of signing with CKM_RSA_PKCS.
++               */
++              rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
++                      &mech_info);
++
++              if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN)))
 +                      {
-+                      PK11err_add_data(PK11_F_GET_PRIV_DSA_KEY,
-+                          PK11_R_CREATEOBJECT, rv);
-+                      goto err;
++                      slot_has_rsa = CK_TRUE;
 +                      }
-+              }
 +
-+      if (dsa_priv_num != NULL)
-+              if ((*dsa_priv_num = BN_dup(dsa->priv_key)) == NULL)
++              if (!found_candidate_slot && slot_has_rsa)
 +                      {
-+                      PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_MALLOC_FAILURE);
-+                      rollback = TRUE;
-+                      goto err;
++#ifdef        DEBUG_SLOT_SELECTION
++                      fprintf(stderr,
++                          "%s: potential slot: %d\n", PK11_DBG, current_slot);
++#endif        /* DEBUG_SLOT_SELECTION */
++                      best_slot_sofar = current_slot;
++                      pk11_have_rsa = slot_has_rsa;
++                      found_candidate_slot = CK_TRUE;
++#ifdef        DEBUG_SLOT_SELECTION
++                      fprintf(stderr,
++                          "%s: setting found_candidate_slot to CK_TRUE\n",
++                          PK11_DBG);
++                      fprintf(stderr,
++                          "%s: best so far slot: %d\n", PK11_DBG,
++                          best_slot_sofar);
 +                      }
++              else
++                      {
++                      fprintf(stderr,
++                          "%s: no rsa\n", PK11_DBG);
++                      }
++#else
++                      } /* if */
++#endif        /* DEBUG_SLOT_SELECTION */
++              } /* for */
 +
-+      /* LINTED: E_CONSTANT_CONDITION */
-+      KEY_HANDLE_REFHOLD(h_key, OP_DSA, FALSE, rollback, err);
-+      if (key_ptr != NULL)
-+              *key_ptr = dsa;
-+
-+err:
-+      if (rollback)
++      if (found_candidate_slot)
 +              {
-+              /*
-+               * We do not care about the return value from C_DestroyObject()
-+               * since we are doing rollback.
-+               */
-+              if (found == 0)
-+                      (void) pFuncList->C_DestroyObject(session, h_key);
-+              h_key = CK_INVALID_HANDLE;
++              pubkey_SLOTID = best_slot_sofar;
 +              }
 +
-+      UNLOCK_OBJSTORE(OP_DSA);
++      /*SLOTID = pSlotList[0];*/
 +
-+malloc_err:
-+      /*
-+       * 5 to 8 entries in the key template are key components.
-+       * They need to be freed apon exit or error.
-+       */
-+      for (i = 5; i <= 8; i++)
-+              {
-+              if (a_key_template[i].pValue != NULL)
-+                      {
-+                      (void) memset(a_key_template[i].pValue, 0,
-+                              a_key_template[i].ulValueLen);
-+                      OPENSSL_free(a_key_template[i].pValue);
-+                      a_key_template[i].pValue = NULL;
-+                      }
-+              }
++#ifdef        DEBUG_SLOT_SELECTION
++      fprintf(stderr,
++          "%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
++      fprintf(stderr,
++          "%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
++      fprintf(stderr,
++          "%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
++      fprintf(stderr,
++          "%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
++#endif        /* DEBUG_SLOT_SELECTION */
 +
-+      return (h_key);
-+      }
++      if (pSlotList != NULL)
++              OPENSSL_free(pSlotList);
 +
-+/*
-+ * Check for cache miss and clean the object pointer and handle
-+ * in such case. Return 1 for cache hit, 0 for cache miss.
-+ */
-+static int check_new_dsa_key_pub(PK11_SESSION *sp, DSA *dsa)
-+      {
-+      /*
-+       * Provide protection against DSA structure reuse by making the
-+       * check for cache hit stronger. Only public key component of DSA
-+       * key matters here so it is sufficient to compare it with value
-+       * cached in PK11_SESSION structure.
-+       */
-+      if ((sp->opdata_dsa_pub != dsa) ||
-+          (BN_cmp(sp->opdata_dsa_pub_num, dsa->pub_key) != 0))
-+              {
-+              /*
-+               * We do not check the return value because even in case of
-+               * failure the sp structure will have both key pointer
-+               * and object handle cleaned and pk11_destroy_object()
-+               * reports the failure to the OpenSSL error message buffer.
-+               */
-+              (void) pk11_destroy_dsa_object_pub(sp, TRUE);
-+              return (0);
-+              }
++      if (any_slot_found != NULL)
++              *any_slot_found = 1;
 +      return (1);
 +      }
 +
++#endif        /* OPENSSL_NO_HW_PK11SO */
++#endif        /* OPENSSL_NO_HW_PK11 */
++#endif        /* OPENSSL_NO_HW */
+Index: openssl/crypto/engine/hw_pk11so.h
+diff -u /dev/null openssl/crypto/engine/hw_pk11so.h:1.2
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11so.h  Mon Oct  5 13:17:03 2009
+@@ -0,0 +1,28 @@
++/* Redefine all pk11/PK11 external symbols to pk11so/PK11SO */
++
++#define find_lock                     pk11so_find_lock
++#define active_list                   pk11so_active_list
++#define ERR_pk11_error                        ERR_pk11so_error
++#define PK11err_add_data              PK11SOerr_add_data
++#define pk11_get_session              pk11so_get_session
++#define pk11_return_session           pk11so_return_session
++#define pk11_active_add                       pk11so_active_add
++#define pk11_active_delete            pk11so_active_delete
++#define pk11_active_remove            pk11so_active_remove
++#define pk11_free_active_list         pk11so_free_active_list
++#define pk11_destroy_rsa_key_objects  pk11so_destroy_rsa_key_objects
++#define pk11_destroy_rsa_object_pub   pk11so_destroy_rsa_object_pub
++#define pk11_destroy_rsa_object_priv  pk11so_destroy_rsa_object_priv
++#define pk11_load_privkey             pk11so_load_privkey
++#define pk11_load_pubkey              pk11so_load_pubkey
++#define PK11_RSA                      PK11SO_RSA
++#define pk11_destroy_dsa_key_objects  pk11so_destroy_dsa_key_objects
++#define pk11_destroy_dsa_object_pub   pk11so_destroy_dsa_object_pub
++#define pk11_destroy_dsa_object_priv  pk11so_destroy_dsa_object_priv
++#define PK11_DSA                      PK11SO_DSA
++#define pk11_destroy_dh_key_objects   pk11so_destroy_dh_key_objects
++#define pk11_destroy_dh_object                pk11so_destroy_dh_object
++#define PK11_DH                               PK11SO_DH
++#define pFuncList                     pk11so_pFuncList
++#define pk11_pin                      pk11so_pin
++#define ENGINE_load_pk11              ENGINE_load_pk11so
+Index: openssl/crypto/engine/hw_pk11so_pub.c
+diff -u /dev/null openssl/crypto/engine/hw_pk11so_pub.c:1.2
+--- /dev/null  Mon Oct  5 13:17:24 2009
++++ openssl/crypto/engine/hw_pk11so_pub.c      Mon Oct  5 13:17:03 2009
+@@ -0,0 +1,899 @@
 +/*
-+ * Check for cache miss and clean the object pointer and handle
-+ * in such case. Return 1 for cache hit, 0 for cache miss.
++ * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
++ * Use is subject to license terms.
 + */
-+static int check_new_dsa_key_priv(PK11_SESSION *sp, DSA *dsa)
-+      {
-+      /*
-+       * Provide protection against DSA structure reuse by making the
-+       * check for cache hit stronger. Only private key component of DSA
-+       * key matters here so it is sufficient to compare it with value
-+       * cached in PK11_SESSION structure.
-+       */
-+      if ((sp->opdata_dsa_priv != dsa) ||
-+          (BN_cmp(sp->opdata_dsa_priv_num, dsa->priv_key) != 0))
-+              {
-+              /*
-+               * We do not check the return value because even in case of
-+               * failure the sp structure will have both key pointer
-+               * and object handle cleaned and pk11_destroy_object()
-+               * reports the failure to the OpenSSL error message buffer.
-+               */
-+              (void) pk11_destroy_dsa_object_priv(sp, TRUE);
-+              return (0);
-+              }
-+      return (1);
-+      }
-+#endif
-+
-+
-+#ifndef OPENSSL_NO_DH
-+/* The DH function implementation */
-+/* ARGSUSED */
-+static int pk11_DH_init(DH *dh)
-+      {
-+      return (1);
-+      }
-+
-+/* ARGSUSED */
-+static int pk11_DH_finish(DH *dh)
-+      {
-+      return (1);
-+      }
 +
++/* crypto/engine/hw_pk11_pub.c */
 +/*
-+ * Generate DH key-pair.
++ * 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).
 + *
-+ * Warning: Unlike OpenSSL's DH_generate_key(3) we ignore dh->priv_key
-+ * and override it even if it is set. OpenSSL does not touch dh->priv_key
-+ * if set and just computes dh->pub_key. It looks like PKCS#11 standard
-+ * is not capable of providing this functionality. This could be a problem
-+ * for applications relying on OpenSSL's semantics.
 + */
-+static int pk11_DH_generate_key(DH *dh)
-+      {
-+      CK_ULONG i;
-+      CK_RV rv, rv1;
-+      int reuse_mem_len = 0, ret = 0;
-+      PK11_SESSION *sp = NULL;
-+      CK_BYTE_PTR reuse_mem;
 +
-+      CK_MECHANISM mechanism = {CKM_DH_PKCS_KEY_PAIR_GEN, NULL_PTR, 0};
-+      CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
-+      CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
++/* Modified to keep only RNG and RSA Sign */
++
++#ifdef OPENSSL_NO_RSA
++#error RSA is disabled
++#endif
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++#include <sys/types.h>
++
++#include <openssl/e_os2.h>
++#include <openssl/crypto.h>
++#include <cryptlib.h>
++#include <openssl/engine.h>
++#include <openssl/dso.h>
++#include <openssl/err.h>
++#include <openssl/bn.h>
++#include <openssl/pem.h>
++#include <openssl/rsa.h>
++#include <openssl/rand.h>
++#include <openssl/objects.h>
++#include <openssl/x509.h>
 +
-+      CK_ULONG ul_pub_key_attr_count = 3;
-+      CK_ATTRIBUTE pub_key_template[] =
-+              {
-+              {CKA_PRIVATE, &false, sizeof (false)},
-+              {CKA_PRIME, (void *)NULL, 0},
-+              {CKA_BASE, (void *)NULL, 0}
-+              };
++#ifdef OPENSSL_SYS_WIN32
++#define NOPTHREADS
++typedef int pid_t;
++#define HAVE_GETPASSPHRASE
++static char *getpassphrase(const char *prompt);
++#ifndef NULL_PTR
++#define NULL_PTR NULL
++#endif
++#define CK_DEFINE_FUNCTION(returnType, name) \
++      returnType __declspec(dllexport) name
++#define CK_DECLARE_FUNCTION(returnType, name) \
++      returnType __declspec(dllimport) name
++#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
++      returnType __declspec(dllimport) (* name)
++#else
++#include <unistd.h>
++#endif
 +
-+      CK_ULONG ul_priv_key_attr_count = 3;
-+      CK_ATTRIBUTE priv_key_template[] =
-+              {
-+              {CKA_PRIVATE, &false, sizeof (false)},
-+              {CKA_SENSITIVE, &false, sizeof (false)},
-+              {CKA_DERIVE, &true, sizeof (true)}
-+              };
++#ifndef NOPTHREADS
++#include <pthread.h>
++#endif
 +
-+      CK_ULONG pub_key_attr_result_count = 1;
-+      CK_ATTRIBUTE pub_key_result[] =
-+              {
-+              {CKA_VALUE, (void *)NULL, 0}
-+              };
++#ifndef OPENSSL_NO_HW
++#ifndef OPENSSL_NO_HW_PK11
++#ifndef OPENSSL_NO_HW_PK11SO
 +
-+      CK_ULONG priv_key_attr_result_count = 1;
-+      CK_ATTRIBUTE priv_key_result[] =
-+              {
-+              {CKA_VALUE, (void *)NULL, 0}
-+              };
++#ifndef OPENSSL_NO_DSA
++#define OPENSSL_NO_DSA
++#endif
++#ifndef OPENSSL_NO_DH
++#define OPENSSL_NO_DH
++#endif
 +
-+      pub_key_template[1].ulValueLen = BN_num_bytes(dh->p);
-+      if (pub_key_template[1].ulValueLen > 0)
-+              {
-+              /*
-+               * We must not increase ulValueLen by DH_BUF_RESERVE since that
-+               * could cause the same rounding problem. See definition of
-+               * DH_BUF_RESERVE above.
-+               */
-+              pub_key_template[1].pValue =
-+                      OPENSSL_malloc(pub_key_template[1].ulValueLen +
-+                      DH_BUF_RESERVE);
-+              if (pub_key_template[1].pValue == NULL)
-+                      {
-+                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
++#ifdef OPENSSL_SYS_WIN32
++#pragma pack(push, cryptoki, 1)
++#include "cryptoki.h"
++#include "pkcs11.h"
++#pragma pack(pop, cryptoki)
++#else
++#include "cryptoki.h"
++#include "pkcs11.h"
++#endif
++#include "hw_pk11so.h"
++#include "hw_pk11_err.h"
 +
-+              i = BN_bn2bin(dh->p, pub_key_template[1].pValue);
-+              }
-+      else
-+              goto err;
++#if !(defined(HAVE_GETPASSPHRASE) || (defined (__SVR4) && defined (__sun)))
++#define getpassphrase(x)      getpass(x)
++#endif
 +
-+      pub_key_template[2].ulValueLen = BN_num_bytes(dh->g);
-+      if (pub_key_template[2].ulValueLen > 0)
-+              {
-+              pub_key_template[2].pValue =
-+                      OPENSSL_malloc(pub_key_template[2].ulValueLen +
-+                      DH_BUF_RESERVE);
-+              if (pub_key_template[2].pValue == NULL)
-+                      {
-+                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
++/* RSA stuff */
++static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
++      unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
++EVP_PKEY *pk11_load_privkey(ENGINE*, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data);
++EVP_PKEY *pk11_load_pubkey(ENGINE*, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data);
 +
-+              i = BN_bn2bin(dh->g, pub_key_template[2].pValue);
-+              }
-+      else
-+              goto err;
++static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, RSA** key_ptr,
++      BIGNUM **rsa_d_num, CK_SESSION_HANDLE session);
 +
-+      /*
-+       * Note: we are only using PK11_SESSION structure for getting
-+       *       a session handle. The objects created in this function are
-+       *       destroyed before return and thus not cached.
-+       */
-+      if ((sp = pk11_get_session(OP_DH)) == NULL)
-+              goto err;
++static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa);
++static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa);
 +
-+      rv = pFuncList->C_GenerateKeyPair(sp->session,
-+          &mechanism,
-+          pub_key_template,
-+          ul_pub_key_attr_count,
-+          priv_key_template,
-+          ul_priv_key_attr_count,
-+          &h_pub_key,
-+          &h_priv_key);
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DH_GEN_KEY, PK11_R_GEN_KEY, rv);
-+              goto err;
-+              }
++static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn);
 +
-+      /*
-+       * Reuse the larger memory allocated. We know the larger memory
-+       * should be sufficient for reuse.
-+       */
-+      if (pub_key_template[1].ulValueLen > pub_key_template[2].ulValueLen)
-+              {
-+              reuse_mem = pub_key_template[1].pValue;
-+              reuse_mem_len = pub_key_template[1].ulValueLen + DH_BUF_RESERVE;
-+              }
-+      else
-+              {
-+              reuse_mem = pub_key_template[2].pValue;
-+              reuse_mem_len = pub_key_template[2].ulValueLen + DH_BUF_RESERVE;
-+              }
++/* Read mode string to be used for fopen() */
++#if SOLARIS_OPENSSL
++static char *read_mode_flags = "rF";
++#else
++static char *read_mode_flags = "r";
++#endif
 +
-+      rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key,
-+              pub_key_result, pub_key_attr_result_count);
-+      rv1 = pFuncList->C_GetAttributeValue(sp->session, h_priv_key,
-+              priv_key_result, priv_key_attr_result_count);
++/*
++ * increment/create reference for an asymmetric key handle via active list
++ * manipulation. If active list operation fails, unlock (if locked), set error
++ * variable and jump to the specified label.
++ */
++#define       KEY_HANDLE_REFHOLD(key_handle, alg_type, unlock, var, label)    \
++      {                                                               \
++      if (pk11_active_add(key_handle, alg_type) < 0)                  \
++              {                                                       \
++              var = TRUE;                                             \
++              if (unlock)                                             \
++                      UNLOCK_OBJSTORE(alg_type);                      \
++              goto label;                                             \
++              }                                                       \
++      }
 +
-+      if (rv != CKR_OK || rv1 != CKR_OK)
-+              {
-+              rv = (rv != CKR_OK) ? rv : rv1;
-+              PK11err_add_data(PK11_F_DH_GEN_KEY,
-+                  PK11_R_GETATTRIBUTVALUE, rv);
-+              goto err;
-+              }
++/*
++ * Find active list entry according to object handle and return pointer to the
++ * entry otherwise return NULL.
++ *
++ * This function presumes it is called with lock protecting the active list
++ * held.
++ */
++static PK11_active *pk11_active_find(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
++      {
++      PK11_active *entry;
 +
-+      if (((CK_LONG) pub_key_result[0].ulValueLen) <= 0 ||
-+              ((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
-+              {
-+              PK11err(PK11_F_DH_GEN_KEY, PK11_R_GETATTRIBUTVALUE);
-+              goto err;
-+              }
++      for (entry = active_list[type]; entry != NULL; entry = entry->next)
++              if (entry->h == h)
++                      return (entry);
 +
-+      /* Reuse the memory allocated */
-+      pub_key_result[0].pValue = reuse_mem;
-+      pub_key_result[0].ulValueLen = reuse_mem_len;
++      return (NULL);
++      }
 +
-+      rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key,
-+              pub_key_result, pub_key_attr_result_count);
++/*
++ * Search for an entry in the active list using PKCS#11 object handle as a
++ * search key and return refcnt of the found/created entry or -1 in case of
++ * failure.
++ *
++ * This function presumes it is called with lock protecting the active list
++ * held.
++ */
++int
++pk11_active_add(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
++      {
++      PK11_active *entry = NULL;
 +
-+      if (rv != CKR_OK)
++      if (h == CK_INVALID_HANDLE)
 +              {
-+              PK11err_add_data(PK11_F_DH_GEN_KEY,
-+                  PK11_R_GETATTRIBUTVALUE, rv);
-+              goto err;
++              PK11err(PK11_F_ACTIVE_ADD, PK11_R_INVALID_HANDLE);
++              return (-1);
 +              }
 +
-+      if (pub_key_result[0].type == CKA_VALUE)
++      /* search for entry in the active list */
++      if ((entry = pk11_active_find(h, type)) != NULL)
++              entry->refcnt++;
++      else
 +              {
-+              if (dh->pub_key == NULL)
-+                      if ((dh->pub_key = BN_new()) == NULL)
-+                              {
-+                              PK11err(PK11_F_DH_GEN_KEY,
-+                                      PK11_R_MALLOC_FAILURE);
-+                              goto err;
-+                              }
-+              dh->pub_key = BN_bin2bn(pub_key_result[0].pValue,
-+                      pub_key_result[0].ulValueLen, dh->pub_key);
-+              if (dh->pub_key == NULL)
++              /* not found, create new entry and add it to the list */
++              entry = OPENSSL_malloc(sizeof (PK11_active));
++              if (entry == NULL)
 +                      {
-+                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
-+                      goto err;
++                      PK11err(PK11_F_ACTIVE_ADD, PK11_R_MALLOC_FAILURE);
++                      return (-1);
++                      }
++              entry->h = h;
++              entry->refcnt = 1;
++              entry->prev = NULL;
++              entry->next = NULL;
++              /* connect the newly created entry to the list */
++              if (active_list[type] == NULL)
++                      active_list[type] = entry;
++              else /* make the entry first in the list */
++                      {
++                      entry->next = active_list[type];
++                      active_list[type]->prev = entry;
++                      active_list[type] = entry;
 +                      }
 +              }
 +
-+      /* Reuse the memory allocated */
-+      priv_key_result[0].pValue = reuse_mem;
-+      priv_key_result[0].ulValueLen = reuse_mem_len;
++      return (entry->refcnt);
++      }
 +
-+      rv = pFuncList->C_GetAttributeValue(sp->session, h_priv_key,
-+              priv_key_result, priv_key_attr_result_count);
++/*
++ * Remove active list entry from the list and free it.
++ *
++ * This function presumes it is called with lock protecting the active list
++ * held.
++ */
++void
++pk11_active_remove(PK11_active *entry, PK11_OPTYPE type)
++      {
++      PK11_active *prev_entry;
 +
-+      if (rv != CKR_OK)
++      /* remove the entry from the list and free it */
++      if ((prev_entry = entry->prev) != NULL)
 +              {
-+              PK11err_add_data(PK11_F_DH_GEN_KEY,
-+                  PK11_R_GETATTRIBUTVALUE, rv);
-+              goto err;
++              prev_entry->next = entry->next;
++              if (entry->next != NULL)
++                      entry->next->prev = prev_entry;
 +              }
-+
-+      if (priv_key_result[0].type == CKA_VALUE)
++      else
 +              {
-+              if (dh->priv_key == NULL)
-+                      if ((dh->priv_key = BN_new()) == NULL)
-+                              {
-+                              PK11err(PK11_F_DH_GEN_KEY,
-+                                      PK11_R_MALLOC_FAILURE);
-+                              goto err;
-+                              }
-+              dh->priv_key = BN_bin2bn(priv_key_result[0].pValue,
-+                      priv_key_result[0].ulValueLen, dh->priv_key);
-+              if (dh->priv_key == NULL)
-+                      {
-+                      PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
-+                      goto err;
-+                      }
++              active_list[type] = entry->next;
++              /* we were the first but not the only one */
++              if (entry->next != NULL)
++                      entry->next->prev = NULL;
 +              }
 +
-+      ret = 1;
++      /* sanitization */
++      entry->h = CK_INVALID_HANDLE;
++      entry->prev = NULL;
++      entry->next = NULL;
++      OPENSSL_free(entry);
++      }
 +
-+err:
++/* Free all entries from the active list. */
++void
++pk11_free_active_list(PK11_OPTYPE type)
++      {
++      PK11_active *entry;
 +
-+      if (h_pub_key != CK_INVALID_HANDLE)
++      /* only for asymmetric types since only they have C_Find* locks. */
++      switch (type)
 +              {
-+              rv = pFuncList->C_DestroyObject(sp->session, h_pub_key);
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_DH_GEN_KEY,
-+                          PK11_R_DESTROYOBJECT, rv);
-+                      }
++              case OP_RSA:
++                      break;
++              default:
++                      return;
 +              }
 +
-+      if (h_priv_key != CK_INVALID_HANDLE)
++      /* see find_lock array definition for more info on object locking */
++      LOCK_OBJSTORE(type);
++      while ((entry = active_list[type]) != NULL)
++              pk11_active_remove(entry, type);
++      UNLOCK_OBJSTORE(type);
++      }
++
++/*
++ * Search for active list entry associated with given PKCS#11 object handle,
++ * decrement its refcnt and if it drops to 0, disconnect the entry and free it.
++ *
++ * Return 1 if the PKCS#11 object associated with the entry has no references,
++ * return 0 if there is at least one reference, -1 on error.
++ *
++ * This function presumes it is called with lock protecting the active list
++ * held.
++ */
++int
++pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type)
++      {
++      PK11_active *entry = NULL;
++
++      if ((entry = pk11_active_find(h, type)) == NULL)
 +              {
-+              rv = pFuncList->C_DestroyObject(sp->session, h_priv_key);
-+              if (rv != CKR_OK)
-+                      {
-+                      PK11err_add_data(PK11_F_DH_GEN_KEY,
-+                          PK11_R_DESTROYOBJECT, rv);
-+                      }
++              PK11err(PK11_F_ACTIVE_DELETE, PK11_R_INVALID_HANDLE);
++              return (-1);
 +              }
 +
-+      for (i = 1; i <= 2; i++)
++      OPENSSL_assert(entry->refcnt > 0);
++      entry->refcnt--;
++      if (entry->refcnt == 0)
 +              {
-+              if (pub_key_template[i].pValue != NULL)
-+                      {
-+                      OPENSSL_free(pub_key_template[i].pValue);
-+                      pub_key_template[i].pValue = NULL;
-+                      }
++              pk11_active_remove(entry, type);
++              return (1);
 +              }
 +
-+      pk11_return_session(sp, OP_DH);
-+      return (ret);
++      return (0);
 +      }
 +
-+static int pk11_DH_compute_key(unsigned char *key, const BIGNUM *pub_key,
-+      DH *dh)
++/* Our internal RSA_METHOD that we provide pointers to */
++static RSA_METHOD pk11_rsa;
++
++RSA_METHOD *
++PK11_RSA(void)
 +      {
-+      unsigned int i;
-+      CK_MECHANISM mechanism = {CKM_DH_PKCS_DERIVE, NULL_PTR, 0};
-+      CK_OBJECT_CLASS key_class = CKO_SECRET_KEY;
-+      CK_KEY_TYPE key_type = CKK_GENERIC_SECRET;
-+      CK_OBJECT_HANDLE h_derived_key = CK_INVALID_HANDLE;
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++      const RSA_METHOD *rsa;
 +
-+      CK_ULONG ul_priv_key_attr_count = 2;
-+      CK_ATTRIBUTE priv_key_template[] =
++      if (pk11_rsa.name == NULL)
 +              {
-+              {CKA_CLASS, (void*) NULL, sizeof (key_class)},
-+              {CKA_KEY_TYPE, (void*) NULL, sizeof (key_type)},
-+              };
++              rsa = RSA_PKCS1_SSLeay();
++              memcpy(&pk11_rsa, rsa, sizeof(*rsa));
++              pk11_rsa.name = "PKCS#11 RSA method";
++              pk11_rsa.rsa_sign = pk11_RSA_sign;
++              }
++      return (&pk11_rsa);
++      }
 +
-+      CK_ULONG priv_key_attr_result_count = 1;
-+      CK_ATTRIBUTE priv_key_result[] =
-+              {
-+              {CKA_VALUE, (void *)NULL, 0}
-+              };
++/* Size of an SSL signature: MD5+SHA1 */
++#define       SSL_SIG_LENGTH          36
 +
++/*
++ * Standard engine interface function. Majority codes here are from
++ * rsa/rsa_sign.c. We replaced the decrypt function call by C_Sign of PKCS#11.
++ * See more details in rsa/rsa_sign.c
++ */
++static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
++      unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
++      {
++      X509_SIG sig;
++      ASN1_TYPE parameter;
++      int i, j = 0;
++      unsigned char *p, *s = NULL;
++      X509_ALGOR algor;
++      ASN1_OCTET_STRING digest;
 +      CK_RV rv;
-+      int ret = -1;
++      CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
++      CK_MECHANISM *p_mech = &mech_rsa;
++      CK_OBJECT_HANDLE h_priv_key;
 +      PK11_SESSION *sp = NULL;
++      int ret = 0;
++      unsigned long ulsiglen;
 +
-+      if (dh->priv_key == NULL)
-+              goto err;
-+
-+      priv_key_template[0].pValue = &key_class;
-+      priv_key_template[1].pValue = &key_type;
-+
-+      if ((sp = pk11_get_session(OP_DH)) == NULL)
-+              goto err;
-+
-+      mechanism.ulParameterLen = BN_num_bytes(pub_key);
-+      mechanism.pParameter = OPENSSL_malloc(mechanism.ulParameterLen);
-+      if (mechanism.pParameter == NULL)
++      /* Encode the digest */
++      /* Special case: SSL signature, just check the length */
++      if (type == NID_md5_sha1)
 +              {
-+              PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
-+              goto err;
++              if (m_len != SSL_SIG_LENGTH)
++                      {
++                      PK11err(PK11_F_RSA_SIGN,
++                              PK11_R_INVALID_MESSAGE_LENGTH);
++                      goto err;
++                      }
++              i = SSL_SIG_LENGTH;
++              s = (unsigned char *)m;
 +              }
-+      BN_bn2bin(pub_key, mechanism.pParameter);
-+
-+      (void) check_new_dh_key(sp, dh);
-+
-+      h_key = sp->opdata_dh_key;
-+      if (h_key == CK_INVALID_HANDLE)
-+              h_key = sp->opdata_dh_key =
-+                      pk11_get_dh_key((DH*) dh, &sp->opdata_dh,
-+                          &sp->opdata_dh_priv_num, sp->session);
-+
-+      if (h_key == CK_INVALID_HANDLE)
++      else
 +              {
-+              PK11err(PK11_F_DH_COMP_KEY, PK11_R_CREATEOBJECT);
-+              goto err;
-+              }
++              sig.algor = &algor;
++              sig.algor->algorithm = OBJ_nid2obj(type);
++              if (sig.algor->algorithm == NULL)
++                      {
++                      PK11err(PK11_F_RSA_SIGN,
++                              PK11_R_UNKNOWN_ALGORITHM_TYPE);
++                      goto err;
++                      }
++              if (sig.algor->algorithm->length == 0)
++                      {
++                      PK11err(PK11_F_RSA_SIGN,
++                              PK11_R_UNKNOWN_ASN1_OBJECT_ID);
++                      goto err;
++                      }
++              parameter.type = V_ASN1_NULL;
++              parameter.value.ptr = NULL;
++              sig.algor->parameter = &parameter;
 +
-+      rv = pFuncList->C_DeriveKey(sp->session,
-+          &mechanism,
-+          h_key,
-+          priv_key_template,
-+          ul_priv_key_attr_count,
-+          &h_derived_key);
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_DERIVEKEY, rv);
-+              goto err;
-+              }
++              sig.digest = &digest;
++              sig.digest->data = (unsigned char *)m;
++              sig.digest->length = m_len;
 +
-+      rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key,
-+          priv_key_result, priv_key_attr_result_count);
++              i = i2d_X509_SIG(&sig, NULL);
++              }
 +
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE,
-+                  rv);
++      j = RSA_size(rsa);
++      if ((i - RSA_PKCS1_PADDING) > j)
++              {
++              PK11err(PK11_F_RSA_SIGN, PK11_R_DIGEST_TOO_BIG);
 +              goto err;
 +              }
 +
-+      if (((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
++      if (type != NID_md5_sha1)
 +              {
-+              PK11err(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE);
-+              goto err;
++              s = (unsigned char *)OPENSSL_malloc((unsigned int)(j + 1));
++              if (s == NULL)
++                      {
++                      PK11err(PK11_F_RSA_SIGN, PK11_R_MALLOC_FAILURE);
++                      goto err;
++                      }
++              p = s;
++              (void) i2d_X509_SIG(&sig, &p);
 +              }
-+      priv_key_result[0].pValue =
-+              OPENSSL_malloc(priv_key_result[0].ulValueLen);
-+      if (!priv_key_result[0].pValue)
-+              {
-+              PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
++
++      if ((sp = pk11_get_session(OP_RSA)) == NULL)
 +              goto err;
-+              }
 +
-+      rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key,
-+              priv_key_result, priv_key_attr_result_count);
++      (void) check_new_rsa_key_priv(sp, rsa);
 +
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE,
-+                  rv);
-+              goto err;
-+              }
++      h_priv_key = sp->opdata_rsa_priv_key;
++      if (h_priv_key == CK_INVALID_HANDLE)
++              h_priv_key = sp->opdata_rsa_priv_key =
++                      pk11_get_private_rsa_key((RSA *)rsa,
++                          &sp->opdata_rsa_priv,
++                          &sp->opdata_rsa_d_num, sp->session);
 +
-+      /*
-+       * OpenSSL allocates the output buffer 'key' which is the same
-+       * length of the public key. It is long enough for the derived key
-+       */
-+      if (priv_key_result[0].type == CKA_VALUE)
++      if (h_priv_key != CK_INVALID_HANDLE)
 +              {
-+              /*
-+               * CKM_DH_PKCS_DERIVE mechanism is not supposed to strip
-+               * leading zeros from a computed shared secret. However,
-+               * OpenSSL always did it so we must do the same here. The
-+               * vagueness of the spec regarding leading zero bytes was
-+               * finally cleared with TLS 1.1 (RFC 4346) saying that leading
-+               * zeros are stripped before the computed data is used as the
-+               * pre-master secret.
-+               */
-+              for (i = 0; i < priv_key_result[0].ulValueLen; ++i)
++              rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
++
++              if (rv != CKR_OK)
 +                      {
-+                      if (((char *)priv_key_result[0].pValue)[i] != 0)
-+                              break;
++                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGNINIT, rv);
++                      goto err;
 +                      }
 +
-+              (void) memcpy(key, ((char *)priv_key_result[0].pValue) + i,
-+                      priv_key_result[0].ulValueLen - i);
-+              ret = priv_key_result[0].ulValueLen - i;
-+              }
-+
-+err:
++              ulsiglen = j;
++              rv = pFuncList->C_Sign(sp->session, s, i, sigret,
++                      (CK_ULONG_PTR) &ulsiglen);
++              *siglen = ulsiglen;
 +
-+      if (h_derived_key != CK_INVALID_HANDLE)
-+              {
-+              rv = pFuncList->C_DestroyObject(sp->session, h_derived_key);
 +              if (rv != CKR_OK)
 +                      {
-+                      PK11err_add_data(PK11_F_DH_COMP_KEY,
-+                          PK11_R_DESTROYOBJECT, rv);
++                      PK11err_add_data(PK11_F_RSA_SIGN, PK11_R_SIGN, rv);
++                      goto err;
 +                      }
-+              }
-+      if (priv_key_result[0].pValue)
-+              {
-+              OPENSSL_free(priv_key_result[0].pValue);
-+              priv_key_result[0].pValue = NULL;
++              ret = 1;
 +              }
 +
-+      if (mechanism.pParameter)
++err:
++      if ((type != NID_md5_sha1) && (s != NULL))
 +              {
-+              OPENSSL_free(mechanism.pParameter);
-+              mechanism.pParameter = NULL;
++              (void) memset(s, 0, (unsigned int)(j + 1));
++              OPENSSL_free(s);
 +              }
 +
-+      pk11_return_session(sp, OP_DH);
++      pk11_return_session(sp, OP_RSA);
 +      return (ret);
 +      }
 +
++static int hndidx_rsa = -1;
 +
-+static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh,
-+      DH **key_ptr, BIGNUM **dh_priv_num, CK_SESSION_HANDLE session)
++/* load RSA private key from a file */
++/* ARGSUSED */
++EVP_PKEY *pk11_load_privkey(ENGINE *e, const char *privkey_file,
++      UI_METHOD *ui_method, void *callback_data)
 +      {
++      EVP_PKEY *pkey = NULL;
++      FILE *privkey;
++      RSA *rsa;
++      PK11_SESSION *sp = NULL;
++      /* everything else below needed for key by reference extension */
 +      CK_RV rv;
-+      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
-+      CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
-+      CK_KEY_TYPE key_type = CKK_DH;
-+      CK_ULONG found;
-+      CK_BBOOL rollback = FALSE;
-+      int i;
++      CK_ULONG objcnt = 0;
++      CK_BBOOL is_token = TRUE;
++      CK_BYTE attr_data[2][1024];
++      CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY;
++      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
++      extern char *pk11_pin;
 +
-+      CK_ULONG ul_key_attr_count = 7;
-+      CK_ATTRIBUTE key_template[] =
++      /* we look for private keys only */
++      CK_ATTRIBUTE search_templ[] =
 +              {
-+              {CKA_CLASS, (void*) NULL, sizeof (class)},
-+              {CKA_KEY_TYPE, (void*) NULL, sizeof (key_type)},
-+              {CKA_DERIVE, &true, sizeof (true)},
-+              {CKA_PRIVATE, &false, sizeof (false)},
-+              {CKA_PRIME, (void *) NULL, 0},
-+              {CKA_BASE, (void *) NULL, 0},
-+              {CKA_VALUE, (void *) NULL, 0},
++              {CKA_TOKEN, &is_token, sizeof(is_token)},
++              {CKA_CLASS, &key_class, sizeof(key_class)},
++              {CKA_LABEL, NULL, 0}
 +              };
 +
-+      key_template[0].pValue = &class;
-+      key_template[1].pValue = &key_type;
++      /* these attributes are needed to initialize OpenSSL RSA structure */
++      CK_ATTRIBUTE get_templ[] =
++              {
++              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
++              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
++              };
 +
-+      key_template[4].ulValueLen = BN_num_bytes(dh->p);
-+      key_template[4].pValue = (CK_VOID_PTR)OPENSSL_malloc(
-+              (size_t)key_template[4].ulValueLen);
-+      if (key_template[4].pValue == NULL)
++      /*
++       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
++       */
++      if (strstr(privkey_file, "pkcs11:") == privkey_file)
 +              {
-+              PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
-+              }
++              if ((sp = pk11_get_session(OP_RSA)) == NULL)
++                      return (NULL);
 +
-+      BN_bn2bin(dh->p, key_template[4].pValue);
++              search_templ[2].pValue = strstr(privkey_file, ":") + 1;
++              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
 +
-+      key_template[5].ulValueLen = BN_num_bytes(dh->g);
-+      key_template[5].pValue = (CK_VOID_PTR)OPENSSL_malloc(
-+              (size_t)key_template[5].ulValueLen);
-+      if (key_template[5].pValue == NULL)
-+              {
-+              PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
++              if (pk11_pin == NULL)
++                      {
++                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
++
++                      if (pk11_pin == NULL)
++                              {
++                              PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MALLOC_FAILURE);
++                              goto err;
++                              }
++                      }
++              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
++                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
++                      {
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_INVALID_PIN, rv);
++                      goto err;
++                      }
++
++              LOCK_OBJSTORE(OP_RSA);
++              if ((rv = pFuncList->C_FindObjectsInit(sp->session,
++                  search_templ, 3)) != CKR_OK)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_FINDOBJECTSINIT, rv);
++                      goto err;
++                      }
++
++              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
++              if (rv != CKR_OK)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_FINDOBJECTS, rv);
++                      goto err;
++                      }
++
++              if (objcnt > 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_TOO_MANY_OBJECTS);
++                      goto err;
++                      }
++
++              if (objcnt != 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_OBJECT_NOT_FOUND);
++                      goto err;
++                      }
++
++              (void) pFuncList->C_FindObjectsFinal(sp->session);
++              UNLOCK_OBJSTORE(OP_RSA);
++
++              if (hndidx_rsa == -1)
++                      hndidx_rsa = RSA_get_ex_new_index(0,
++                                      "pkcs11 RSA HSM key handle",
++                                      NULL, NULL, NULL);
++
++              pkey = EVP_PKEY_new();
++              if (pkey == NULL)
++                      goto err;
++
++              rsa = RSA_new_method(e);
++              if (rsa == NULL) {
++                      EVP_PKEY_free(pkey);
++                      pkey = NULL;
++                      goto err;
 +              }
++              EVP_PKEY_assign_RSA(pkey, rsa);
 +
-+      BN_bn2bin(dh->g, key_template[5].pValue);
++              if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
++                  get_templ, 2)) != CKR_OK)
++                      {
++                      PK11err_add_data(PK11_F_LOAD_PRIVKEY,
++                                       PK11_R_GETATTRIBUTVALUE, rv);
++                      EVP_PKEY_free(pkey);
++                      pkey = NULL;
++                      goto err;
++                      }
 +
-+      key_template[6].ulValueLen = BN_num_bytes(dh->priv_key);
-+      key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
-+              (size_t)key_template[6].ulValueLen);
-+      if (key_template[6].pValue == NULL)
++              /* Note: these flags are critical! */
++              rsa->flags = RSA_FLAG_SIGN_VER | RSA_FLAG_EXT_PKEY;
++              RSA_set_ex_data(rsa, hndidx_rsa, (void *) ks_key);
++              (void) check_new_rsa_key_priv(sp, rsa);
++              sp->opdata_rsa_priv = rsa;
++              sp->opdata_rsa_priv_key = ks_key;
++
++              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
++              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
++              }
++      else if ((privkey = fopen(privkey_file, read_mode_flags)) != NULL)
 +              {
-+              PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
-+              goto malloc_err;
++              pkey = PEM_read_PrivateKey(privkey, NULL, NULL, NULL);
++              (void) fclose(privkey);
 +              }
 +
-+      BN_bn2bin(dh->priv_key, key_template[6].pValue);
++err:
++      if (sp != NULL)
++              pk11_return_session(sp, OP_RSA);
++      return (pkey);
++      }
 +
-+      /* see find_lock array definition for more info on object locking */
-+      LOCK_OBJSTORE(OP_DH);
-+      rv = pFuncList->C_FindObjectsInit(session, key_template,
-+              ul_key_attr_count);
++/* load RSA public key from a file */
++/* ARGSUSED */
++EVP_PKEY *pk11_load_pubkey(ENGINE *e, const char *pubkey_file,
++      UI_METHOD *ui_method, void *callback_data)
++      {
++      EVP_PKEY *pkey = NULL;
++      FILE *pubkey;
++      RSA *rsa;
++      PK11_SESSION *sp = NULL;
++      /* everything else below needed for key by reference extension */
++      CK_RV rv;
++      CK_ULONG objcnt = 0;
++      CK_BBOOL is_token = TRUE;
++      CK_BYTE attr_data[2][1024];
++      CK_OBJECT_CLASS key_class = CKO_PUBLIC_KEY;
++      CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;    /* key in keystore */
++      extern char *pk11_pin;
 +
-+      if (rv != CKR_OK)
++      /* we look for public keys only */
++      CK_ATTRIBUTE search_templ[] =
 +              {
-+              PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSINIT, rv);
-+              goto err;
-+              }
++              {CKA_TOKEN, &is_token, sizeof(is_token)},
++              {CKA_CLASS, &key_class, sizeof(key_class)},
++              {CKA_LABEL, NULL, 0}
++              };
 +
-+      rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
++      /* these attributes are needed to initialize OpenSSL RSA structure */
++      CK_ATTRIBUTE get_templ[] =
++              {
++              {CKA_MODULUS, (void *)attr_data[0], 1024},          /* n */
++              {CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
++              };
 +
-+      if (rv != CKR_OK)
++      /*
++       * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
++       */
++      if (strstr(pubkey_file, "pkcs11:") == pubkey_file)
 +              {
-+              PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTS, rv);
-+              goto err;
-+              }
++              if ((sp = pk11_get_session(OP_RSA)) == NULL)
++                      return (NULL);
 +
-+      rv = pFuncList->C_FindObjectsFinal(session);
++              search_templ[2].pValue = strstr(pubkey_file, ":") + 1;
++              search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
 +
-+      if (rv != CKR_OK)
-+              {
-+              PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSFINAL,
-+                  rv);
-+              goto err;
-+              }
++#define ALLWAYS_LOGIN
++#ifdef ALLWAYS_LOGIN
++              if (pk11_pin == NULL)
++                      {
++                      pk11_pin = BUF_strdup(getpassphrase("Enter PIN: "));
 +
-+      if (found == 0)
-+              {
-+              rv = pFuncList->C_CreateObject(session,
-+                      key_template, ul_key_attr_count, &h_key);
++                      if (pk11_pin == NULL)
++                              {
++                              PK11err(PK11_F_LOAD_PUBKEY, PK11_R_MALLOC_FAILURE);
++                              goto err;
++                              }
++                      }
++              if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
++                  strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
++                      {
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_INVALID_PIN, rv);
++                      goto err;
++                      }
++#endif
++
++              LOCK_OBJSTORE(OP_RSA);
++              if (pFuncList->C_FindObjectsInit(sp->session, search_templ, 3) != CKR_OK)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_FINDOBJECTSINIT, rv);
++                      goto err;
++                      }
++              rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
 +              if (rv != CKR_OK)
 +                      {
-+                      PK11err_add_data(PK11_F_GET_DH_KEY, PK11_R_CREATEOBJECT,
-+                          rv);
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_FINDOBJECTS, rv);
++                      goto err;
++                      }
++
++              if (objcnt > 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_TOO_MANY_OBJECTS);
++                      goto err;
++                      }
++
++              if (objcnt != 1)
++                      {
++                      UNLOCK_OBJSTORE(OP_RSA);
++                      PK11err(PK11_F_LOAD_PUBKEY, PK11_R_OBJECT_NOT_FOUND);
 +                      goto err;
 +                      }
++
++              (void) pFuncList->C_FindObjectsFinal(sp->session);
++              UNLOCK_OBJSTORE(OP_RSA);
++
++              sp->opdata_rsa_pub_key = ks_key;
++              pkey = EVP_PKEY_new();
++              if (pkey == NULL)
++                      goto err;
++
++              rsa = RSA_new_method(e);
++              if (rsa == NULL) {
++                      EVP_PKEY_free(pkey);
++                      pkey = NULL;
++                      goto err;
 +              }
++              EVP_PKEY_assign_RSA(pkey, rsa);
 +
-+      if (dh_priv_num != NULL)
-+              if ((*dh_priv_num = BN_dup(dh->priv_key)) == NULL)
++              if (pFuncList->C_GetAttributeValue(sp->session, ks_key,
++                  get_templ, 2) != CKR_OK)
 +                      {
-+                      PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
-+                      rollback = TRUE;
++                      PK11err_add_data(PK11_F_LOAD_PUBKEY,
++                                       PK11_R_GETATTRIBUTVALUE, rv);
 +                      goto err;
 +                      }
 +
-+      /* LINTED: E_CONSTANT_CONDITION */
-+      KEY_HANDLE_REFHOLD(h_key, OP_DH, FALSE, rollback, err);
-+      if (key_ptr != NULL)
-+              *key_ptr = dh;
++              (void) check_new_rsa_key_pub(sp, rsa);
++              sp->opdata_rsa_pub = rsa;
 +
-+err:
-+      if (rollback)
++              attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
++              attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
++              }
++      else if ((pubkey = fopen(pubkey_file, read_mode_flags)) != NULL)
 +              {
-+              /*
-+               * We do not care about the return value from C_DestroyObject()
-+               * since we are doing rollback.
-+               */
-+              if (found == 0)
-+                      (void) pFuncList->C_DestroyObject(session, h_key);
-+              h_key = CK_INVALID_HANDLE;
++              pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
++              (void) fclose(pubkey);
 +              }
 +
-+      UNLOCK_OBJSTORE(OP_DH);
++err:
++      if (sp != NULL)
++              pk11_return_session(sp, OP_RSA);
++      return (pkey);
++      }
 +
-+malloc_err:
-+      for (i = 4; i <= 6; i++)
++/*
++ * Create a private key object in the session from a given rsa structure.
++ * The *rsa_d_num pointer is non-NULL for RSA private keys.
++ */
++static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA *rsa,
++    RSA **key_ptr, BIGNUM **rsa_d_num, CK_SESSION_HANDLE session)
++      {
++      CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
++
++      if ((rsa->flags & RSA_FLAG_EXT_PKEY) == 0) {
++              PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_INCONSISTENT_KEY);
++              return (h_key);
++      }
++      
++      h_key = (CK_OBJECT_HANDLE)RSA_get_ex_data(rsa, hndidx_rsa);
++      (void) pk11_active_add(h_key, OP_RSA);
++      if (key_ptr != NULL)
++              *key_ptr = rsa;
++      if (rsa_d_num != NULL)
 +              {
-+              if (key_template[i].pValue != NULL)
++              if (rsa->d == NULL)
++                      *rsa_d_num = NULL;
++              else if ((*rsa_d_num = BN_dup(rsa->d)) == NULL)
 +                      {
-+                      OPENSSL_free(key_template[i].pValue);
-+                      key_template[i].pValue = NULL;
++                      PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
++                      return (h_key);
 +                      }
 +              }
-+
 +      return (h_key);
 +      }
 +
 +/*
 + * Check for cache miss and clean the object pointer and handle
 + * in such case. Return 1 for cache hit, 0 for cache miss.
-+ *
-+ * Note: we rely on pk11_destroy_dh_key_objects() to set sp->opdata_dh
-+ *       to CK_INVALID_HANDLE even when it fails to destroy the object.
 + */
-+static int check_new_dh_key(PK11_SESSION *sp, DH *dh)
++static int check_new_rsa_key_pub(PK11_SESSION *sp, const RSA *rsa)
 +      {
 +      /*
-+       * Provide protection against DH structure reuse by making the
-+       * check for cache hit stronger. Private key component of DH key
-+       * is unique so it is sufficient to compare it with value cached
-+       * in PK11_SESSION structure.
++       * Provide protection against RSA structure reuse by making the
++       * check for cache hit stronger. Only public components of RSA
++       * key matter here so it is sufficient to compare them with values
++       * cached in PK11_SESSION structure.
 +       */
-+      if ((sp->opdata_dh != dh) ||
-+          (BN_cmp(sp->opdata_dh_priv_num, dh->priv_key) != 0))
++      if ((sp->opdata_rsa_pub != rsa) ||
++          (BN_cmp(sp->opdata_rsa_n_num, rsa->n) != 0) ||
++          (BN_cmp(sp->opdata_rsa_e_num, rsa->e) != 0))
 +              {
 +              /*
 +               * We do not check the return value because even in case of
@@ -10797,31 +11019,37 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11_pub.c:1.31
 +               * and object handle cleaned and pk11_destroy_object()
 +               * reports the failure to the OpenSSL error message buffer.
 +               */
-+              (void) pk11_destroy_dh_object(sp, TRUE);
++              (void) pk11_destroy_rsa_object_pub(sp, TRUE);
 +              return (0);
 +              }
 +      return (1);
 +      }
-+#endif
 +
 +/*
-+ * Local function to simplify key template population
-+ * Return 0 -- error, 1 -- no error
++ * Check for cache miss and clean the object pointer and handle
++ * in such case. Return 1 for cache hit, 0 for cache miss.
 + */
-+static int init_template_value(BIGNUM *bn, CK_VOID_PTR *p_value,
-+      CK_ULONG *ul_value_len)
++static int check_new_rsa_key_priv(PK11_SESSION *sp, const RSA *rsa)
 +      {
-+      CK_ULONG len = BN_num_bytes(bn);
-+      if (len == 0)
-+              return (1);
-+
-+      *ul_value_len = len;
-+      *p_value = (CK_VOID_PTR)OPENSSL_malloc((size_t)*ul_value_len);
-+      if (*p_value == NULL)
++      /*
++       * Provide protection against RSA structure reuse by making the
++       * check for cache hit stronger. Comparing private exponent of RSA
++       * key with value cached in PK11_SESSION structure should
++       * be sufficient.
++       */
++      if ((sp->opdata_rsa_priv != rsa) ||
++          (BN_cmp(sp->opdata_rsa_d_num, rsa->d) != 0) ||
++          ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0))
++              {
++              /*
++               * We do not check the return value because even in case of
++               * failure the sp structure will have both key pointer
++               * and object handle cleaned and pk11_destroy_object()
++               * reports the failure to the OpenSSL error message buffer.
++               */
++              (void) pk11_destroy_rsa_object_priv(sp, TRUE);
 +              return (0);
-+
-+      BN_bn2bin(bn, *p_value);
-+
++              }
 +      return (1);
 +      }
 +
@@ -10832,6 +11060,7 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11_pub.c:1.31
 +              *bn = BN_bin2bn(attr_data, attr->ulValueLen, NULL);
 +              }
 +      }
++
 +#ifdef        OPENSSL_SYS_WIN32
 +char *getpassphrase(const char *prompt)
 +      {
@@ -10864,15 +11093,16 @@ diff -u /dev/null openssl/crypto/engine/hw_pk11_pub.c:1.31
 +      return buf;
 +      }
 +#endif        /* OPENSSL_SYS_WIN32 */
++#endif        /* OPENSSL_NO_HW_PK11SO */
 +#endif        /* OPENSSL_NO_HW_PK11 */
 +#endif        /* OPENSSL_NO_HW */
 Index: openssl/crypto/engine/pkcs11.h
 diff -u /dev/null openssl/crypto/engine/pkcs11.h:1.1.1.1
---- /dev/null  Mon Oct  5 11:08:14 2009
+--- /dev/null  Mon Oct  5 13:17:24 2009
 +++ openssl/crypto/engine/pkcs11.h     Wed Oct 24 23:27:09 2007
 @@ -0,0 +1,299 @@
 +/* pkcs11.h include file for PKCS #11. */
-+/* $Revision: 1.1 $ */
++/* $Revision: 1.2 $ */
 +
 +/* License to copy and use this software is granted provided that it is
 + * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
@@ -11172,11 +11402,11 @@ diff -u /dev/null openssl/crypto/engine/pkcs11.h:1.1.1.1
 +#endif
 Index: openssl/crypto/engine/pkcs11f.h
 diff -u /dev/null openssl/crypto/engine/pkcs11f.h:1.1.1.1
---- /dev/null  Mon Oct  5 11:08:14 2009
+--- /dev/null  Mon Oct  5 13:17:24 2009
 +++ openssl/crypto/engine/pkcs11f.h    Wed Oct 24 23:27:09 2007
 @@ -0,0 +1,912 @@
 +/* pkcs11f.h include file for PKCS #11. */
-+/* $Revision: 1.1 $ */
++/* $Revision: 1.2 $ */
 +
 +/* License to copy and use this software is granted provided that it is
 + * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
@@ -12089,11 +12319,11 @@ diff -u /dev/null openssl/crypto/engine/pkcs11f.h:1.1.1.1
 +#endif
 Index: openssl/crypto/engine/pkcs11t.h
 diff -u /dev/null openssl/crypto/engine/pkcs11t.h:1.2
---- /dev/null  Mon Oct  5 11:08:14 2009
+--- /dev/null  Mon Oct  5 13:17:24 2009
 +++ openssl/crypto/engine/pkcs11t.h    Sat Aug 30 11:58:07 2008
 @@ -0,0 +1,1885 @@
 +/* pkcs11t.h include file for PKCS #11. */
-+/* $Revision: 1.1 $ */
++/* $Revision: 1.2 $ */
 +
 +/* License to copy and use this software is granted provided that it is
 + * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
@@ -13978,19 +14208,38 @@ diff -u /dev/null openssl/crypto/engine/pkcs11t.h:1.2
 +
 +#endif
 Index: openssl/util/libeay.num
-diff -u openssl/util/libeay.num:1.1.3.1 openssl/util/libeay.num:1.5
+diff -u openssl/util/libeay.num:1.1.3.1 openssl/util/libeay.num:1.6
 --- openssl/util/libeay.num:1.1.3.1    Mon Feb  2 00:27:56 2009
-+++ openssl/util/libeay.num    Fri Sep  4 10:43:22 2009
-@@ -3725,3 +3725,4 @@
++++ openssl/util/libeay.num    Mon Oct  5 13:17:03 2009
+@@ -3725,3 +3725,5 @@
  JPAKE_STEP3A_init                       4111  EXIST::FUNCTION:JPAKE
  ERR_load_JPAKE_strings                  4112  EXIST::FUNCTION:JPAKE
  JPAKE_STEP2_init                        4113  EXIST::FUNCTION:JPAKE
-+ENGINE_load_pk11                        4114  EXIST::FUNCTION:ENGINE
++ENGINE_load_pk11ca                      4114  EXIST::FUNCTION:HW_PKCS11CA,ENGINE
++ENGINE_load_pk11so                      4114  EXIST::FUNCTION:HW_PKCS11SO,ENGINE
 Index: openssl/util/mk1mf.pl
-diff -u openssl/util/mk1mf.pl:1.1.3.1 openssl/util/mk1mf.pl:1.6
+diff -u openssl/util/mk1mf.pl:1.1.3.1 openssl/util/mk1mf.pl:1.7
 --- openssl/util/mk1mf.pl:1.1.3.1      Tue Dec  2 23:50:21 2008
-+++ openssl/util/mk1mf.pl      Fri Sep  4 10:43:23 2009
-@@ -322,6 +322,9 @@
++++ openssl/util/mk1mf.pl      Mon Oct  5 13:17:05 2009
+@@ -87,6 +87,8 @@
+       no-ecdh                                 - No ECDH
+       no-engine                               - No engine
+       no-hw                                   - No hw
++      no-hw-pkcs11ca                          - No hw PKCS#11 CA flavor
++      no-hw-pkcs11so                          - No hw PKCS#11 SO flavor
+       nasm                                    - Use NASM for x86 asm
+       nw-nasm                                 - Use NASM x86 asm for NetWare
+       nw-mwasm                                - Use Metrowerks x86 asm for NetWare
+@@ -242,6 +244,8 @@
+ $cflags.=" -DOPENSSL_NO_ECDH" if $no_ecdh;
+ $cflags.=" -DOPENSSL_NO_ENGINE"   if $no_engine;
+ $cflags.=" -DOPENSSL_NO_HW"   if $no_hw;
++$cflags.=" -DOPENSSL_NO_HW_PKCS11CA"   if $no_hw_pkcs11ca;
++$cflags.=" -DOPENSSL_NO_HW_PKCS11SO"   if $no_hw_pkcs11so;
+ $cflags.=" -DOPENSSL_FIPS"    if $fips;
+ $cflags.= " -DZLIB" if $zlib_opt;
+ $cflags.= " -DZLIB_SHARED" if $zlib_opt == 2;
+@@ -322,6 +326,9 @@
        if ($key eq "ZLIB_INCLUDE")
                { $cflags .= " $val" if $val ne "";}
  
@@ -14000,6 +14249,54 @@ diff -u openssl/util/mk1mf.pl:1.1.3.1 openssl/util/mk1mf.pl:1.6
        if ($key eq "LIBZLIB")
                { $zlib_lib = "$val" if $val ne "";}
  
+@@ -1300,6 +1307,8 @@
+               "no-ecdh" => \$no_ecdh,
+               "no-engine" => \$no_engine,
+               "no-hw" => \$no_hw,
++              "no-hw-pkcs11ca" => \$no_hw_pkcs11ca,
++              "no-hw-pkcs11so" => \$no_hw_pkcs11so,
+               "just-ssl" =>
+                       [\$no_rc2, \$no_idea, \$no_des, \$no_bf, \$no_cast,
+                         \$no_md2, \$no_sha, \$no_mdc2, \$no_dsa, \$no_dh,
+Index: openssl/util/mkdef.pl
+diff -u openssl/util/mkdef.pl:1.1.3.1 openssl/util/mkdef.pl:1.5
+--- openssl/util/mkdef.pl:1.1.3.1      Mon Nov 24 16:14:15 2008
++++ openssl/util/mkdef.pl      Mon Oct  5 13:17:05 2009
+@@ -93,7 +93,7 @@
+                        # External "algorithms"
+                        "FP_API", "STDIO", "SOCK", "KRB5", "DGRAM",
+                        # Engines
+-                       "STATIC_ENGINE", "ENGINE", "HW", "GMP",
++                       "STATIC_ENGINE", "ENGINE", "HW", "GMP", "HW_PKCS11CA", "HW_PKCS11SO",
+                        # RFC3779 support 
+                        "RFC3779",
+                        # TLS extension support
+@@ -122,6 +122,7 @@
+ my $no_md2; my $no_md4; my $no_md5; my $no_sha; my $no_ripemd; my $no_mdc2;
+ my $no_rsa; my $no_dsa; my $no_dh; my $no_hmac=0; my $no_aes; my $no_krb5;
+ my $no_ec; my $no_ecdsa; my $no_ecdh; my $no_engine; my $no_hw; my $no_camellia;
++my $no_pkcs11ca; my $no_pkcs11so;
+ my $no_seed;
+ my $no_fp_api; my $no_static_engine; my $no_gmp; my $no_deprecated;
+ my $no_rfc3779; my $no_tlsext; my $no_cms; my $no_capieng; my $no_jpake;
+@@ -214,6 +215,8 @@
+       elsif (/^no-cms$/)      { $no_cms=1; }
+       elsif (/^no-capieng$/)  { $no_capieng=1; }
+       elsif (/^no-jpake$/)    { $no_jpake=1; }
++      elsif (/^no-hw-pkcs11ca$/) { $no_pkcs11ca=1; }
++      elsif (/^no-hw-pkcs11so$/) { $no_pkcs11so=1; }
+       }
+@@ -1138,6 +1141,8 @@
+                       if ($keyword eq "KRB5" && $no_krb5) { return 0; }
+                       if ($keyword eq "ENGINE" && $no_engine) { return 0; }
+                       if ($keyword eq "HW" && $no_hw) { return 0; }
++                      if ($keyword eq "HW_PKCS11CA" && $no_pkcs11ca) { return 0; }
++                      if ($keyword eq "HW_PKCS11SO" && $no_pkcs11so) { return 0; }
+                       if ($keyword eq "FP_API" && $no_fp_api) { return 0; }
+                       if ($keyword eq "STATIC_ENGINE" && $no_static_engine) { return 0; }
+                       if ($keyword eq "GMP" && $no_gmp) { return 0; }
 Index: openssl/util/pl/VC-32.pl
 diff -u openssl/util/pl/VC-32.pl:1.1.3.1 openssl/util/pl/VC-32.pl:1.5
 --- openssl/util/pl/VC-32.pl:1.1.3.1   Mon Mar  9 12:14:08 2009