1 /*
   2  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.security.pkcs11;
  27 
  28 import java.io.*;
  29 import java.util.*;
  30 
  31 import java.security.*;
  32 import java.security.interfaces.*;
  33 
  34 import javax.crypto.interfaces.*;
  35 
  36 import javax.security.auth.Subject;
  37 import javax.security.auth.login.LoginException;
  38 import javax.security.auth.login.FailedLoginException;
  39 import javax.security.auth.callback.Callback;
  40 import javax.security.auth.callback.CallbackHandler;
  41 import javax.security.auth.callback.ConfirmationCallback;
  42 import javax.security.auth.callback.PasswordCallback;
  43 import javax.security.auth.callback.TextOutputCallback;
  44 
  45 import sun.security.util.Debug;
  46 import sun.security.util.ResourcesMgr;
  47 
  48 import sun.security.pkcs11.Secmod.*;
  49 
  50 import sun.security.pkcs11.wrapper.*;
  51 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
  52 
  53 /**
  54  * PKCS#11 provider main class.
  55  *
  56  * @author  Andreas Sterbenz
  57  * @since   1.5
  58  */
  59 public final class SunPKCS11 extends AuthProvider {
  60 
  61     private static final long serialVersionUID = -1354835039035306505L;
  62 
  63     static final Debug debug = Debug.getInstance("sunpkcs11");
  64 
  65     private static int dummyConfigId;
  66 
  67     // the PKCS11 object through which we make the native calls
  68     final PKCS11 p11;
  69 
  70     // name of the configuration file
  71     private final String configName;
  72 
  73     // configuration information
  74     final Config config;
  75 
  76     // id of the PKCS#11 slot we are using
  77     final long slotID;
  78 
  79     private CallbackHandler pHandler;
  80     private final Object LOCK_HANDLER = new Object();
  81 
  82     final boolean removable;
  83 
  84     final Module nssModule;
  85 
  86     final boolean nssUseSecmodTrust;
  87 
  88     private volatile Token token;
  89 
  90     private TokenPoller poller;
  91 
  92     Token getToken() {
  93         return token;
  94     }
  95 
  96     public SunPKCS11() {
  97         super("SunPKCS11-Dummy", 1.7d, "SunPKCS11-Dummy");
  98         throw new ProviderException
  99             ("SunPKCS11 requires configuration file argument");
 100     }
 101 
 102     public SunPKCS11(String configName) {
 103         this(checkNull(configName), null);
 104     }
 105 
 106     public SunPKCS11(InputStream configStream) {
 107         this(getDummyConfigName(), checkNull(configStream));
 108     }
 109 
 110     private static <T> T checkNull(T obj) {
 111         if (obj == null) {
 112             throw new NullPointerException();
 113         }
 114         return obj;
 115     }
 116 
 117     private static synchronized String getDummyConfigName() {
 118         int id = ++dummyConfigId;
 119         return "---DummyConfig-" + id + "---";
 120     }
 121 
 122     /**
 123      * @deprecated use new SunPKCS11(String) or new SunPKCS11(InputStream)
 124      *         instead
 125      */
 126     @Deprecated
 127     public SunPKCS11(String configName, InputStream configStream) {
 128         super("SunPKCS11-" +
 129             Config.getConfig(configName, configStream).getName(),
 130             1.7d, Config.getConfig(configName, configStream).getDescription());
 131         this.configName = configName;
 132         this.config = Config.removeConfig(configName);
 133 
 134         if (debug != null) {
 135             System.out.println("SunPKCS11 loading " + configName);
 136         }
 137 
 138         String library = config.getLibrary();
 139         String functionList = config.getFunctionList();
 140         long slotID = config.getSlotID();
 141         int slotListIndex = config.getSlotListIndex();
 142 
 143         boolean useSecmod = config.getNssUseSecmod();
 144         boolean nssUseSecmodTrust = config.getNssUseSecmodTrust();
 145         Module nssModule = null;
 146 
 147         //
 148         // Initialization via Secmod. The way this works is as follows:
 149         // SunPKCS11 is either in normal mode or in NSS Secmod mode.
 150         // Secmod is activated by specifying one or more of the following
 151         // options in the config file:
 152         // nssUseSecmod, nssSecmodDirectory, nssLibrary, nssModule
 153         //
 154         // XXX add more explanation here
 155         //
 156         // If we are in Secmod mode and configured to use either the
 157         // nssKeyStore or the nssTrustAnchors module, we automatically
 158         // switch to using the NSS trust attributes for trusted certs
 159         // (KeyStore).
 160         //
 161 
 162         if (useSecmod) {
 163             // note: Config ensures library/slot/slotListIndex not specified
 164             // in secmod mode.
 165             Secmod secmod = Secmod.getInstance();
 166             DbMode nssDbMode = config.getNssDbMode();
 167             try {
 168                 String nssLibraryDirectory = config.getNssLibraryDirectory();
 169                 String nssSecmodDirectory = config.getNssSecmodDirectory();
 170                 boolean nssOptimizeSpace = config.getNssOptimizeSpace();
 171 
 172                 if (secmod.isInitialized()) {
 173                     if (nssSecmodDirectory != null) {
 174                         String s = secmod.getConfigDir();
 175                         if ((s != null) &&
 176                                 (s.equals(nssSecmodDirectory) == false)) {
 177                             throw new ProviderException("Secmod directory "
 178                                 + nssSecmodDirectory
 179                                 + " invalid, NSS already initialized with "
 180                                 + s);
 181                         }
 182                     }
 183                     if (nssLibraryDirectory != null) {
 184                         String s = secmod.getLibDir();
 185                         if ((s != null) &&
 186                                 (s.equals(nssLibraryDirectory) == false)) {
 187                             throw new ProviderException("NSS library directory "
 188                                 + nssLibraryDirectory
 189                                 + " invalid, NSS already initialized with "
 190                                 + s);
 191                         }
 192                     }
 193                 } else {
 194                     if (nssDbMode != DbMode.NO_DB) {
 195                         if (nssSecmodDirectory == null) {
 196                             throw new ProviderException(
 197                                 "Secmod not initialized and "
 198                                  + "nssSecmodDirectory not specified");
 199                         }
 200                     } else {
 201                         if (nssSecmodDirectory != null) {
 202                             throw new ProviderException(
 203                                 "nssSecmodDirectory must not be "
 204                                 + "specified in noDb mode");
 205                         }
 206                     }
 207                     secmod.initialize(nssDbMode, nssSecmodDirectory,
 208                         nssLibraryDirectory, nssOptimizeSpace);
 209                 }
 210             } catch (IOException e) {
 211                 // XXX which exception to throw
 212                 throw new ProviderException("Could not initialize NSS", e);
 213             }
 214             List<Module> modules = secmod.getModules();
 215             if (config.getShowInfo()) {
 216                 System.out.println("NSS modules: " + modules);
 217             }
 218 
 219             String moduleName = config.getNssModule();
 220             if (moduleName == null) {
 221                 nssModule = secmod.getModule(ModuleType.FIPS);
 222                 if (nssModule != null) {
 223                     moduleName = "fips";
 224                 } else {
 225                     moduleName = (nssDbMode == DbMode.NO_DB) ?
 226                         "crypto" : "keystore";
 227                 }
 228             }
 229             if (moduleName.equals("fips")) {
 230                 nssModule = secmod.getModule(ModuleType.FIPS);
 231                 nssUseSecmodTrust = true;
 232                 functionList = "FC_GetFunctionList";
 233             } else if (moduleName.equals("keystore")) {
 234                 nssModule = secmod.getModule(ModuleType.KEYSTORE);
 235                 nssUseSecmodTrust = true;
 236             } else if (moduleName.equals("crypto")) {
 237                 nssModule = secmod.getModule(ModuleType.CRYPTO);
 238             } else if (moduleName.equals("trustanchors")) {
 239                 // XXX should the option be called trustanchor or trustanchors??
 240                 nssModule = secmod.getModule(ModuleType.TRUSTANCHOR);
 241                 nssUseSecmodTrust = true;
 242             } else if (moduleName.startsWith("external-")) {
 243                 int moduleIndex;
 244                 try {
 245                     moduleIndex = Integer.parseInt
 246                             (moduleName.substring("external-".length()));
 247                 } catch (NumberFormatException e) {
 248                     moduleIndex = -1;
 249                 }
 250                 if (moduleIndex < 1) {
 251                     throw new ProviderException
 252                             ("Invalid external module: " + moduleName);
 253                 }
 254                 int k = 0;
 255                 for (Module module : modules) {
 256                     if (module.getType() == ModuleType.EXTERNAL) {
 257                         if (++k == moduleIndex) {
 258                             nssModule = module;
 259                             break;
 260                         }
 261                     }
 262                 }
 263                 if (nssModule == null) {
 264                     throw new ProviderException("Invalid module " + moduleName
 265                         + ": only " + k + " external NSS modules available");
 266                 }
 267             } else {
 268                 throw new ProviderException(
 269                     "Unknown NSS module: " + moduleName);
 270             }
 271             if (nssModule == null) {
 272                 throw new ProviderException(
 273                     "NSS module not available: " + moduleName);
 274             }
 275             if (nssModule.hasInitializedProvider()) {
 276                 throw new ProviderException("Secmod module already configured");
 277             }
 278             library = nssModule.libraryName;
 279             slotListIndex = nssModule.slot;
 280         }
 281         this.nssUseSecmodTrust = nssUseSecmodTrust;
 282         this.nssModule = nssModule;
 283 
 284         File libraryFile = new File(library);
 285         // if the filename is a simple filename without path
 286         // (e.g. "libpkcs11.so"), it may refer to a library somewhere on the
 287         // OS library search path. Omit the test for file existance as that
 288         // only looks in the current directory.
 289         if (libraryFile.getName().equals(library) == false) {
 290             if (new File(library).isFile() == false) {
 291                 String msg = "Library " + library + " does not exist";
 292                 if (config.getHandleStartupErrors() == Config.ERR_HALT) {
 293                     throw new ProviderException(msg);
 294                 } else {
 295                     throw new UnsupportedOperationException(msg);
 296                 }
 297             }
 298         }
 299 
 300         try {
 301             if (debug != null) {
 302                 debug.println("Initializing PKCS#11 library " + library);
 303             }
 304             CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();
 305             String nssArgs = config.getNssArgs();
 306             if (nssArgs != null) {
 307                 initArgs.pReserved = nssArgs;
 308             }
 309             // request multithreaded access first
 310             initArgs.flags = CKF_OS_LOCKING_OK;
 311             PKCS11 tmpPKCS11;
 312             try {
 313                 tmpPKCS11 = PKCS11.getInstance(
 314                     library, functionList, initArgs,
 315                     config.getOmitInitialize());
 316             } catch (PKCS11Exception e) {
 317                 if (debug != null) {
 318                     debug.println("Multi-threaded initialization failed: " + e);
 319                 }
 320                 if (config.getAllowSingleThreadedModules() == false) {
 321                     throw e;
 322                 }
 323                 // fall back to single threaded access
 324                 if (nssArgs == null) {
 325                     // if possible, use null initArgs for better compatibility
 326                     initArgs = null;
 327                 } else {
 328                     initArgs.flags = 0;
 329                 }
 330                 tmpPKCS11 = PKCS11.getInstance(library,
 331                     functionList, initArgs, config.getOmitInitialize());
 332             }
 333             p11 = tmpPKCS11;
 334 
 335             CK_INFO p11Info = p11.C_GetInfo();
 336             if (p11Info.cryptokiVersion.major < 2) {
 337                 throw new ProviderException("Only PKCS#11 v2.0 and later "
 338                 + "supported, library version is v" + p11Info.cryptokiVersion);
 339             }
 340             boolean showInfo = config.getShowInfo();
 341             if (showInfo) {
 342                 System.out.println("Information for provider " + getName());
 343                 System.out.println("Library info:");
 344                 System.out.println(p11Info);
 345             }
 346 
 347             if ((slotID < 0) || showInfo) {
 348                 long[] slots = p11.C_GetSlotList(false);
 349                 if (showInfo) {
 350                     System.out.println("All slots: " + toString(slots));
 351                     slots = p11.C_GetSlotList(true);
 352                     System.out.println("Slots with tokens: " + toString(slots));
 353                 }
 354                 if (slotID < 0) {
 355                     if ((slotListIndex < 0)
 356                             || (slotListIndex >= slots.length)) {
 357                         throw new ProviderException("slotListIndex is "
 358                             + slotListIndex
 359                             + " but token only has " + slots.length + " slots");
 360                     }
 361                     slotID = slots[slotListIndex];
 362                 }
 363             }
 364             this.slotID = slotID;
 365             CK_SLOT_INFO slotInfo = p11.C_GetSlotInfo(slotID);
 366             removable = (slotInfo.flags & CKF_REMOVABLE_DEVICE) != 0;
 367             initToken(slotInfo);
 368             if (nssModule != null) {
 369                 nssModule.setProvider(this);
 370             }
 371         } catch (Exception e) {
 372             if (config.getHandleStartupErrors() == Config.ERR_IGNORE_ALL) {
 373                 throw new UnsupportedOperationException
 374                         ("Initialization failed", e);
 375             } else {
 376                 throw new ProviderException
 377                         ("Initialization failed", e);
 378             }
 379         }
 380     }
 381 
 382     private static String toString(long[] longs) {
 383         if (longs.length == 0) {
 384             return "(none)";
 385         }
 386         StringBuilder sb = new StringBuilder();
 387         sb.append(longs[0]);
 388         for (int i = 1; i < longs.length; i++) {
 389             sb.append(", ");
 390             sb.append(longs[i]);
 391         }
 392         return sb.toString();
 393     }
 394 
 395     public boolean equals(Object obj) {
 396         return this == obj;
 397     }
 398 
 399     public int hashCode() {
 400         return System.identityHashCode(this);
 401     }
 402 
 403     private static String[] s(String s1) {
 404         return new String[] {s1};
 405     }
 406 
 407     private static String[] s(String s1, String s2) {
 408         return new String[] {s1, s2};
 409     }
 410 
 411     private static final class Descriptor {
 412         final String type;
 413         final String algorithm;
 414         final String className;
 415         final String[] aliases;
 416         final int[] mechanisms;
 417 
 418         private Descriptor(String type, String algorithm, String className,
 419                 String[] aliases, int[] mechanisms) {
 420             this.type = type;
 421             this.algorithm = algorithm;
 422             this.className = className;
 423             this.aliases = aliases;
 424             this.mechanisms = mechanisms;
 425         }
 426         private P11Service service(Token token, int mechanism) {
 427             return new P11Service
 428                 (token, type, algorithm, className, aliases, mechanism);
 429         }
 430         public String toString() {
 431             return type + "." + algorithm;
 432         }
 433     }
 434 
 435     // Map from mechanism to List of Descriptors that should be
 436     // registered if the mechanism is supported
 437     private final static Map<Integer,List<Descriptor>> descriptors =
 438         new HashMap<Integer,List<Descriptor>>();
 439 
 440     private static int[] m(long m1) {
 441         return new int[] {(int)m1};
 442     }
 443 
 444     private static int[] m(long m1, long m2) {
 445         return new int[] {(int)m1, (int)m2};
 446     }
 447 
 448     private static int[] m(long m1, long m2, long m3) {
 449         return new int[] {(int)m1, (int)m2, (int)m3};
 450     }
 451 
 452     private static int[] m(long m1, long m2, long m3, long m4) {
 453         return new int[] {(int)m1, (int)m2, (int)m3, (int)m4};
 454     }
 455 
 456     private static void d(String type, String algorithm, String className,
 457             int[] m) {
 458         register(new Descriptor(type, algorithm, className, null, m));
 459     }
 460 
 461     private static void d(String type, String algorithm, String className,
 462             String[] aliases, int[] m) {
 463         register(new Descriptor(type, algorithm, className, aliases, m));
 464     }
 465 
 466     private static void register(Descriptor d) {
 467         for (int i = 0; i < d.mechanisms.length; i++) {
 468             int m = d.mechanisms[i];
 469             Integer key = Integer.valueOf(m);
 470             List<Descriptor> list = descriptors.get(key);
 471             if (list == null) {
 472                 list = new ArrayList<Descriptor>();
 473                 descriptors.put(key, list);
 474             }
 475             list.add(d);
 476         }
 477     }
 478 
 479     private final static String MD  = "MessageDigest";
 480 
 481     private final static String SIG = "Signature";
 482 
 483     private final static String KPG = "KeyPairGenerator";
 484 
 485     private final static String KG  = "KeyGenerator";
 486 
 487     private final static String AGP = "AlgorithmParameters";
 488 
 489     private final static String KF  = "KeyFactory";
 490 
 491     private final static String SKF = "SecretKeyFactory";
 492 
 493     private final static String CIP = "Cipher";
 494 
 495     private final static String MAC = "Mac";
 496 
 497     private final static String KA  = "KeyAgreement";
 498 
 499     private final static String KS  = "KeyStore";
 500 
 501     private final static String SR  = "SecureRandom";
 502 
 503     static {
 504         // names of all the implementation classes
 505         // use local variables, only used here
 506         String P11Digest           = "sun.security.pkcs11.P11Digest";
 507         String P11MAC              = "sun.security.pkcs11.P11MAC";
 508         String P11KeyPairGenerator = "sun.security.pkcs11.P11KeyPairGenerator";
 509         String P11KeyGenerator     = "sun.security.pkcs11.P11KeyGenerator";
 510         String P11RSAKeyFactory    = "sun.security.pkcs11.P11RSAKeyFactory";
 511         String P11DSAKeyFactory    = "sun.security.pkcs11.P11DSAKeyFactory";
 512         String P11DHKeyFactory     = "sun.security.pkcs11.P11DHKeyFactory";
 513         String P11KeyAgreement     = "sun.security.pkcs11.P11KeyAgreement";
 514         String P11SecretKeyFactory = "sun.security.pkcs11.P11SecretKeyFactory";
 515         String P11Cipher           = "sun.security.pkcs11.P11Cipher";
 516         String P11RSACipher        = "sun.security.pkcs11.P11RSACipher";
 517         String P11Signature        = "sun.security.pkcs11.P11Signature";
 518 
 519         // XXX register all aliases
 520 
 521         d(MD, "MD2",            P11Digest,
 522                 m(CKM_MD2));
 523         d(MD, "MD5",            P11Digest,
 524                 m(CKM_MD5));
 525         d(MD, "SHA1",           P11Digest, s("SHA", "SHA-1"),
 526                 m(CKM_SHA_1));
 527 
 528         d(MD, "SHA-224",        P11Digest,
 529                 s("2.16.840.1.101.3.4.2.4", "OID.2.16.840.1.101.3.4.2.4"),
 530                 m(CKM_SHA224));
 531         d(MD, "SHA-256",        P11Digest,
 532                 s("2.16.840.1.101.3.4.2.1", "OID.2.16.840.1.101.3.4.2.1"),
 533                 m(CKM_SHA256));
 534         d(MD, "SHA-384",        P11Digest,
 535                 s("2.16.840.1.101.3.4.2.2", "OID.2.16.840.1.101.3.4.2.2"),
 536                 m(CKM_SHA384));
 537         d(MD, "SHA-512",        P11Digest,
 538                 s("2.16.840.1.101.3.4.2.3", "OID.2.16.840.1.101.3.4.2.3"),
 539                 m(CKM_SHA512));
 540 
 541         d(MAC, "HmacMD5",       P11MAC,
 542                 m(CKM_MD5_HMAC));
 543         d(MAC, "HmacSHA1",      P11MAC,
 544                 m(CKM_SHA_1_HMAC));
 545         d(MAC, "HmacSHA224",    P11MAC,
 546                 s("1.2.840.113549.2.8", "OID.1.2.840.113549.2.8"),
 547                 m(CKM_SHA224_HMAC));
 548         d(MAC, "HmacSHA256",    P11MAC,
 549                 s("1.2.840.113549.2.9", "OID.1.2.840.113549.2.9"),
 550                 m(CKM_SHA256_HMAC));
 551         d(MAC, "HmacSHA384",    P11MAC,
 552                 s("1.2.840.113549.2.10", "OID.1.2.840.113549.2.10"),
 553                 m(CKM_SHA384_HMAC));
 554         d(MAC, "HmacSHA512",    P11MAC,
 555                 s("1.2.840.113549.2.11", "OID.1.2.840.113549.2.11"),
 556                 m(CKM_SHA512_HMAC));
 557         d(MAC, "SslMacMD5",     P11MAC,
 558                 m(CKM_SSL3_MD5_MAC));
 559         d(MAC, "SslMacSHA1",    P11MAC,
 560                 m(CKM_SSL3_SHA1_MAC));
 561 
 562         d(KPG, "RSA",           P11KeyPairGenerator,
 563                 m(CKM_RSA_PKCS_KEY_PAIR_GEN));
 564         d(KPG, "DSA",           P11KeyPairGenerator,
 565                 m(CKM_DSA_KEY_PAIR_GEN));
 566         d(KPG, "DH",            P11KeyPairGenerator,    s("DiffieHellman"),
 567                 m(CKM_DH_PKCS_KEY_PAIR_GEN));
 568         d(KPG, "EC",            P11KeyPairGenerator,
 569                 m(CKM_EC_KEY_PAIR_GEN));
 570 
 571         d(KG,  "ARCFOUR",       P11KeyGenerator,        s("RC4"),
 572                 m(CKM_RC4_KEY_GEN));
 573         d(KG,  "DES",           P11KeyGenerator,
 574                 m(CKM_DES_KEY_GEN));
 575         d(KG,  "DESede",        P11KeyGenerator,
 576                 m(CKM_DES3_KEY_GEN, CKM_DES2_KEY_GEN));
 577         d(KG,  "AES",           P11KeyGenerator,
 578                 m(CKM_AES_KEY_GEN));
 579         d(KG,  "Blowfish",      P11KeyGenerator,
 580                 m(CKM_BLOWFISH_KEY_GEN));
 581 
 582         // register (Secret)KeyFactories if there are any mechanisms
 583         // for a particular algorithm that we support
 584         d(KF, "RSA",            P11RSAKeyFactory,
 585                 m(CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_X_509));
 586         d(KF, "DSA",            P11DSAKeyFactory,
 587                 m(CKM_DSA_KEY_PAIR_GEN, CKM_DSA, CKM_DSA_SHA1));
 588         d(KF, "DH",             P11DHKeyFactory,        s("DiffieHellman"),
 589                 m(CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_DERIVE));
 590         d(KF, "EC",             P11DHKeyFactory,
 591                 m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE,
 592                     CKM_ECDSA, CKM_ECDSA_SHA1));
 593 
 594         // AlgorithmParameters for EC.
 595         // Only needed until we have an EC implementation in the SUN provider.
 596         d(AGP, "EC",            "sun.security.ec.ECParameters",
 597                                                 s("1.2.840.10045.2.1"),
 598                 m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE,
 599                     CKM_ECDSA, CKM_ECDSA_SHA1));
 600 
 601         d(KA, "DH",             P11KeyAgreement,        s("DiffieHellman"),
 602                 m(CKM_DH_PKCS_DERIVE));
 603         d(KA, "ECDH",           "sun.security.pkcs11.P11ECDHKeyAgreement",
 604                 m(CKM_ECDH1_DERIVE));
 605 
 606         d(SKF, "ARCFOUR",       P11SecretKeyFactory,    s("RC4"),
 607                 m(CKM_RC4));
 608         d(SKF, "DES",           P11SecretKeyFactory,
 609                 m(CKM_DES_CBC));
 610         d(SKF, "DESede",        P11SecretKeyFactory,
 611                 m(CKM_DES3_CBC));
 612         d(SKF, "AES",           P11SecretKeyFactory,
 613                 m(CKM_AES_CBC));
 614         d(SKF, "Blowfish",      P11SecretKeyFactory,
 615                 m(CKM_BLOWFISH_CBC));
 616 
 617         // XXX attributes for Ciphers (supported modes, padding)
 618         d(CIP, "ARCFOUR",                       P11Cipher,      s("RC4"),
 619                 m(CKM_RC4));
 620         d(CIP, "DES/CBC/NoPadding",             P11Cipher,
 621                 m(CKM_DES_CBC));
 622         d(CIP, "DES/CBC/PKCS5Padding",          P11Cipher,
 623                 m(CKM_DES_CBC_PAD, CKM_DES_CBC));
 624         d(CIP, "DES/ECB/NoPadding",             P11Cipher,
 625                 m(CKM_DES_ECB));
 626         d(CIP, "DES/ECB/PKCS5Padding",          P11Cipher,      s("DES"),
 627                 m(CKM_DES_ECB));
 628         d(CIP, "DESede/CBC/NoPadding",          P11Cipher,
 629                 m(CKM_DES3_CBC));
 630         d(CIP, "DESede/CBC/PKCS5Padding",       P11Cipher,
 631                 m(CKM_DES3_CBC_PAD, CKM_DES3_CBC));
 632         d(CIP, "DESede/ECB/NoPadding",          P11Cipher,
 633                 m(CKM_DES3_ECB));
 634         d(CIP, "DESede/ECB/PKCS5Padding",       P11Cipher,      s("DESede"),
 635                 m(CKM_DES3_ECB));
 636         d(CIP, "AES/CBC/NoPadding",             P11Cipher,
 637                 m(CKM_AES_CBC));
 638         d(CIP, "AES/CBC/PKCS5Padding",          P11Cipher,
 639                 m(CKM_AES_CBC_PAD, CKM_AES_CBC));
 640         d(CIP, "AES/ECB/NoPadding",             P11Cipher,
 641                 m(CKM_AES_ECB));
 642         d(CIP, "AES/ECB/PKCS5Padding",          P11Cipher,      s("AES"),
 643                 m(CKM_AES_ECB));
 644         d(CIP, "AES/CTR/NoPadding",             P11Cipher,
 645                 m(CKM_AES_CTR));
 646         d(CIP, "Blowfish/CBC/NoPadding",        P11Cipher,
 647                 m(CKM_BLOWFISH_CBC));
 648         d(CIP, "Blowfish/CBC/PKCS5Padding",     P11Cipher,
 649                 m(CKM_BLOWFISH_CBC));
 650 
 651         // XXX RSA_X_509, RSA_OAEP not yet supported
 652         d(CIP, "RSA/ECB/PKCS1Padding",          P11RSACipher,   s("RSA"),
 653                 m(CKM_RSA_PKCS));
 654         d(CIP, "RSA/ECB/NoPadding",             P11RSACipher,
 655                 m(CKM_RSA_X_509));
 656 
 657         d(SIG, "RawDSA",        P11Signature,           s("NONEwithDSA"),
 658                 m(CKM_DSA));
 659         d(SIG, "DSA",           P11Signature,           s("SHA1withDSA"),
 660                 m(CKM_DSA_SHA1, CKM_DSA));
 661         d(SIG, "NONEwithECDSA", P11Signature,
 662                 m(CKM_ECDSA));
 663         d(SIG, "SHA1withECDSA", P11Signature,           s("ECDSA"),
 664                 m(CKM_ECDSA_SHA1, CKM_ECDSA));
 665         d(SIG, "SHA224withECDSA",       P11Signature,
 666                 s("1.2.840.10045.4.3.1", "OID.1.2.840.10045.4.3.1"),
 667                 m(CKM_ECDSA));
 668         d(SIG, "SHA256withECDSA",       P11Signature,
 669                 s("1.2.840.10045.4.3.2", "OID.1.2.840.10045.4.3.2"),
 670                 m(CKM_ECDSA));
 671         d(SIG, "SHA384withECDSA",       P11Signature,
 672                 s("1.2.840.10045.4.3.3", "OID.1.2.840.10045.4.3.3"),
 673                 m(CKM_ECDSA));
 674         d(SIG, "SHA512withECDSA",       P11Signature,
 675                 s("1.2.840.10045.4.3.4", "OID.1.2.840.10045.4.3.4"),
 676                 m(CKM_ECDSA));
 677         d(SIG, "MD2withRSA",    P11Signature,
 678                 m(CKM_MD2_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 679         d(SIG, "MD5withRSA",    P11Signature,
 680                 m(CKM_MD5_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 681         d(SIG, "SHA1withRSA",   P11Signature,
 682                 m(CKM_SHA1_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 683         d(SIG, "SHA224withRSA", P11Signature,
 684                 s("1.2.840.113549.1.1.14", "OID.1.2.840.113549.1.1.14"),
 685                 m(CKM_SHA224_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 686         d(SIG, "SHA256withRSA", P11Signature,
 687                 s("1.2.840.113549.1.1.11", "OID.1.2.840.113549.1.1.11"),
 688                 m(CKM_SHA256_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 689         d(SIG, "SHA384withRSA", P11Signature,
 690                 s("1.2.840.113549.1.1.12", "OID.1.2.840.113549.1.1.12"),
 691                 m(CKM_SHA384_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 692         d(SIG, "SHA512withRSA", P11Signature,
 693                 s("1.2.840.113549.1.1.13", "OID.1.2.840.113549.1.1.13"),
 694                 m(CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 695 
 696         /*
 697          * TLS 1.2 uses a different hash algorithm than 1.0/1.1 for the
 698          * PRF calculations.  As of 2010, there is no PKCS11-level
 699          * support for TLS 1.2 PRF calculations, and no known OS's have
 700          * an internal variant we could use.  Therefore for TLS 1.2, we
 701          * are updating JSSE to request different provider algorithms
 702          * (e.g. "SunTls12Prf"), and currently only SunJCE has these
 703          * TLS 1.2 algorithms.
 704          *
 705          * If we reused the names such as "SunTlsPrf", the PKCS11
 706          * providers would need be updated to fail correctly when
 707          * presented with the wrong version number (via
 708          * Provider.Service.supportsParameters()), and we would also
 709          * need to add the appropriate supportsParamters() checks into
 710          * KeyGenerators (not currently there).
 711          *
 712          * In the future, if PKCS11 support is added, we will restructure
 713          * this.
 714          */
 715         d(KG, "SunTlsRsaPremasterSecret",
 716                     "sun.security.pkcs11.P11TlsRsaPremasterSecretGenerator",
 717                 m(CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_TLS_PRE_MASTER_KEY_GEN));
 718         d(KG, "SunTlsMasterSecret",
 719                     "sun.security.pkcs11.P11TlsMasterSecretGenerator",
 720                 m(CKM_SSL3_MASTER_KEY_DERIVE, CKM_TLS_MASTER_KEY_DERIVE,
 721                     CKM_SSL3_MASTER_KEY_DERIVE_DH,
 722                     CKM_TLS_MASTER_KEY_DERIVE_DH));
 723         d(KG, "SunTlsKeyMaterial",
 724                     "sun.security.pkcs11.P11TlsKeyMaterialGenerator",
 725                 m(CKM_SSL3_KEY_AND_MAC_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE));
 726         d(KG, "SunTlsPrf", "sun.security.pkcs11.P11TlsPrfGenerator",
 727                 m(CKM_TLS_PRF, CKM_NSS_TLS_PRF_GENERAL));
 728     }
 729 
 730     // background thread that periodically checks for token insertion
 731     // if no token is present. We need to do that in a separate thread because
 732     // the insertion check may block for quite a long time on some tokens.
 733     private static class TokenPoller implements Runnable {
 734         private final SunPKCS11 provider;
 735         private volatile boolean enabled;
 736         private TokenPoller(SunPKCS11 provider) {
 737             this.provider = provider;
 738             enabled = true;
 739         }
 740         public void run() {
 741             int interval = provider.config.getInsertionCheckInterval();
 742             while (enabled) {
 743                 try {
 744                     Thread.sleep(interval);
 745                 } catch (InterruptedException e) {
 746                     break;
 747                 }
 748                 if (enabled == false) {
 749                     break;
 750                 }
 751                 try {
 752                     provider.initToken(null);
 753                 } catch (PKCS11Exception e) {
 754                     // ignore
 755                 }
 756             }
 757         }
 758         void disable() {
 759             enabled = false;
 760         }
 761     }
 762 
 763     // create the poller thread, if not already active
 764     private void createPoller() {
 765         if (poller != null) {
 766             return;
 767         }
 768         TokenPoller poller = new TokenPoller(this);
 769         Thread t = new Thread(poller, "Poller " + getName());
 770         t.setDaemon(true);
 771         t.setPriority(Thread.MIN_PRIORITY);
 772         t.start();
 773         this.poller = poller;
 774     }
 775 
 776     // destroy the poller thread, if active
 777     private void destroyPoller() {
 778         if (poller != null) {
 779             poller.disable();
 780             poller = null;
 781         }
 782     }
 783 
 784     private boolean hasValidToken() {
 785         /* Commented out to work with Solaris softtoken impl which
 786            returns 0-value flags, e.g. both REMOVABLE_DEVICE and
 787            TOKEN_PRESENT are false, when it can't access the token.
 788         if (removable == false) {
 789             return true;
 790         }
 791         */
 792         Token token = this.token;
 793         return (token != null) && token.isValid();
 794     }
 795 
 796     // destroy the token. Called if we detect that it has been removed
 797     synchronized void uninitToken(Token token) {
 798         if (this.token != token) {
 799             // mismatch, our token must already be destroyed
 800             return;
 801         }
 802         destroyPoller();
 803         this.token = null;
 804         // unregister all algorithms
 805         AccessController.doPrivileged(new PrivilegedAction<Object>() {
 806             public Object run() {
 807                 clear();
 808                 return null;
 809             }
 810         });
 811         createPoller();
 812     }
 813 
 814     // test if a token is present and initialize this provider for it if so.
 815     // does nothing if no token is found
 816     // called from constructor and by poller
 817     private void initToken(CK_SLOT_INFO slotInfo) throws PKCS11Exception {
 818         if (slotInfo == null) {
 819             slotInfo = p11.C_GetSlotInfo(slotID);
 820         }
 821         if (removable && (slotInfo.flags & CKF_TOKEN_PRESENT) == 0) {
 822             createPoller();
 823             return;
 824         }
 825         destroyPoller();
 826         boolean showInfo = config.getShowInfo();
 827         if (showInfo) {
 828             System.out.println("Slot info for slot " + slotID + ":");
 829             System.out.println(slotInfo);
 830         }
 831         final Token token = new Token(this);
 832         if (showInfo) {
 833             System.out.println
 834                 ("Token info for token in slot " + slotID + ":");
 835             System.out.println(token.tokenInfo);
 836         }
 837         long[] supportedMechanisms = p11.C_GetMechanismList(slotID);
 838 
 839         // Create a map from the various Descriptors to the "most
 840         // preferred" mechanism that was defined during the
 841         // static initialization.  For example, DES/CBC/PKCS5Padding
 842         // could be mapped to CKM_DES_CBC_PAD or CKM_DES_CBC.  Prefer
 843         // the earliest entry.  When asked for "DES/CBC/PKCS5Padding", we
 844         // return a CKM_DES_CBC_PAD.
 845         final Map<Descriptor,Integer> supportedAlgs =
 846                                         new HashMap<Descriptor,Integer>();
 847         for (int i = 0; i < supportedMechanisms.length; i++) {
 848             long longMech = supportedMechanisms[i];
 849             boolean isEnabled = config.isEnabled(longMech);
 850             if (showInfo) {
 851                 CK_MECHANISM_INFO mechInfo =
 852                         p11.C_GetMechanismInfo(slotID, longMech);
 853                 System.out.println("Mechanism " +
 854                         Functions.getMechanismName(longMech) + ":");
 855                 if (isEnabled == false) {
 856                     System.out.println("DISABLED in configuration");
 857                 }
 858                 System.out.println(mechInfo);
 859             }
 860             if (isEnabled == false) {
 861                 continue;
 862             }
 863             // we do not know of mechs with the upper 32 bits set
 864             if (longMech >>> 32 != 0) {
 865                 continue;
 866             }
 867             int mech = (int)longMech;
 868             Integer integerMech = Integer.valueOf(mech);
 869             List<Descriptor> ds = descriptors.get(integerMech);
 870             if (ds == null) {
 871                 continue;
 872             }
 873             for (Descriptor d : ds) {
 874                 Integer oldMech = supportedAlgs.get(d);
 875                 if (oldMech == null) {
 876                     supportedAlgs.put(d, integerMech);
 877                     continue;
 878                 }
 879                 // See if there is something "more preferred"
 880                 // than what we currently have in the supportedAlgs
 881                 // map.
 882                 int intOldMech = oldMech.intValue();
 883                 for (int j = 0; j < d.mechanisms.length; j++) {
 884                     int nextMech = d.mechanisms[j];
 885                     if (mech == nextMech) {
 886                         supportedAlgs.put(d, integerMech);
 887                         break;
 888                     } else if (intOldMech == nextMech) {
 889                         break;
 890                     }
 891                 }
 892             }
 893 
 894         }
 895 
 896         // register algorithms in provider
 897         AccessController.doPrivileged(new PrivilegedAction<Object>() {
 898             public Object run() {
 899                 for (Map.Entry<Descriptor,Integer> entry
 900                         : supportedAlgs.entrySet()) {
 901                     Descriptor d = entry.getKey();
 902                     int mechanism = entry.getValue().intValue();
 903                     Service s = d.service(token, mechanism);
 904                     putService(s);
 905                 }
 906                 if (((token.tokenInfo.flags & CKF_RNG) != 0)
 907                         && config.isEnabled(PCKM_SECURERANDOM)
 908                         && !token.sessionManager.lowMaxSessions()) {
 909                     // do not register SecureRandom if the token does
 910                     // not support many sessions. if we did, we might
 911                     // run out of sessions in the middle of a
 912                     // nextBytes() call where we cannot fail over.
 913                     putService(new P11Service(token, SR, "PKCS11",
 914                         "sun.security.pkcs11.P11SecureRandom", null,
 915                         PCKM_SECURERANDOM));
 916                 }
 917                 if (config.isEnabled(PCKM_KEYSTORE)) {
 918                     putService(new P11Service(token, KS, "PKCS11",
 919                         "sun.security.pkcs11.P11KeyStore",
 920                         s("PKCS11-" + config.getName()),
 921                         PCKM_KEYSTORE));
 922                 }
 923                 return null;
 924             }
 925         });
 926 
 927         this.token = token;
 928     }
 929 
 930     private static final class P11Service extends Service {
 931 
 932         private final Token token;
 933 
 934         private final long mechanism;
 935 
 936         P11Service(Token token, String type, String algorithm,
 937                 String className, String[] al, long mechanism) {
 938             super(token.provider, type, algorithm, className, toList(al), null);
 939             this.token = token;
 940             this.mechanism = mechanism & 0xFFFFFFFFL;
 941         }
 942 
 943         private static List<String> toList(String[] aliases) {
 944             return (aliases == null) ? null : Arrays.asList(aliases);
 945         }
 946 
 947         public Object newInstance(Object param)
 948                 throws NoSuchAlgorithmException {
 949             if (token.isValid() == false) {
 950                 throw new NoSuchAlgorithmException("Token has been removed");
 951             }
 952             try {
 953                 return newInstance0(param);
 954             } catch (PKCS11Exception e) {
 955                 throw new NoSuchAlgorithmException(e);
 956             }
 957         }
 958 
 959         public Object newInstance0(Object param) throws
 960                 PKCS11Exception, NoSuchAlgorithmException {
 961             String algorithm = getAlgorithm();
 962             String type = getType();
 963             if (type == MD) {
 964                 return new P11Digest(token, algorithm, mechanism);
 965             } else if (type == CIP) {
 966                 if (algorithm.startsWith("RSA")) {
 967                     return new P11RSACipher(token, algorithm, mechanism);
 968                 } else {
 969                     return new P11Cipher(token, algorithm, mechanism);
 970                 }
 971             } else if (type == SIG) {
 972                 return new P11Signature(token, algorithm, mechanism);
 973             } else if (type == MAC) {
 974                 return new P11Mac(token, algorithm, mechanism);
 975             } else if (type == KPG) {
 976                 return new P11KeyPairGenerator(token, algorithm, mechanism);
 977             } else if (type == KA) {
 978                 if (algorithm.equals("ECDH")) {
 979                     return new P11ECDHKeyAgreement(token, algorithm, mechanism);
 980                 } else {
 981                     return new P11KeyAgreement(token, algorithm, mechanism);
 982                 }
 983             } else if (type == KF) {
 984                 return token.getKeyFactory(algorithm);
 985             } else if (type == SKF) {
 986                 return new P11SecretKeyFactory(token, algorithm);
 987             } else if (type == KG) {
 988                 // reference equality
 989                 if (algorithm == "SunTlsRsaPremasterSecret") {
 990                     return new P11TlsRsaPremasterSecretGenerator(
 991                         token, algorithm, mechanism);
 992                 } else if (algorithm == "SunTlsMasterSecret") {
 993                     return new P11TlsMasterSecretGenerator(
 994                         token, algorithm, mechanism);
 995                 } else if (algorithm == "SunTlsKeyMaterial") {
 996                     return new P11TlsKeyMaterialGenerator(
 997                         token, algorithm, mechanism);
 998                 } else if (algorithm == "SunTlsPrf") {
 999                     return new P11TlsPrfGenerator(token, algorithm, mechanism);
1000                 } else {
1001                     return new P11KeyGenerator(token, algorithm, mechanism);
1002                 }
1003             } else if (type == SR) {
1004                 return token.getRandom();
1005             } else if (type == KS) {
1006                 return token.getKeyStore();
1007             } else if (type == AGP) {
1008                 return new sun.security.ec.ECParameters();
1009             } else {
1010                 throw new NoSuchAlgorithmException("Unknown type: " + type);
1011             }
1012         }
1013 
1014         public boolean supportsParameter(Object param) {
1015             if ((param == null) || (token.isValid() == false)) {
1016                 return false;
1017             }
1018             if (param instanceof Key == false) {
1019                 throw new InvalidParameterException("Parameter must be a Key");
1020             }
1021             String algorithm = getAlgorithm();
1022             String type = getType();
1023             Key key = (Key)param;
1024             String keyAlgorithm = key.getAlgorithm();
1025             // RSA signatures and cipher
1026             if (((type == CIP) && algorithm.startsWith("RSA"))
1027                     || (type == SIG) && algorithm.endsWith("RSA")) {
1028                 if (keyAlgorithm.equals("RSA") == false) {
1029                     return false;
1030                 }
1031                 return isLocalKey(key)
1032                         || (key instanceof RSAPrivateKey)
1033                         || (key instanceof RSAPublicKey);
1034             }
1035             // EC
1036             if (((type == KA) && algorithm.equals("ECDH"))
1037                     || ((type == SIG) && algorithm.endsWith("ECDSA"))) {
1038                 if (keyAlgorithm.equals("EC") == false) {
1039                     return false;
1040                 }
1041                 return isLocalKey(key)
1042                         || (key instanceof ECPrivateKey)
1043                         || (key instanceof ECPublicKey);
1044             }
1045             // DSA signatures
1046             if ((type == SIG) && algorithm.endsWith("DSA")) {
1047                 if (keyAlgorithm.equals("DSA") == false) {
1048                     return false;
1049                 }
1050                 return isLocalKey(key)
1051                         || (key instanceof DSAPrivateKey)
1052                         || (key instanceof DSAPublicKey);
1053             }
1054             // MACs and symmetric ciphers
1055             if ((type == CIP) || (type == MAC)) {
1056                 // do not check algorithm name, mismatch is unlikely anyway
1057                 return isLocalKey(key) || "RAW".equals(key.getFormat());
1058             }
1059             // DH key agreement
1060             if (type == KA) {
1061                 if (keyAlgorithm.equals("DH") == false) {
1062                     return false;
1063                 }
1064                 return isLocalKey(key)
1065                         || (key instanceof DHPrivateKey)
1066                         || (key instanceof DHPublicKey);
1067             }
1068             // should not reach here,
1069             // unknown engine type or algorithm
1070             throw new AssertionError
1071                 ("SunPKCS11 error: " + type + ", " + algorithm);
1072         }
1073 
1074         private boolean isLocalKey(Key key) {
1075             return (key instanceof P11Key) && (((P11Key)key).token == token);
1076         }
1077 
1078         public String toString() {
1079             return super.toString() +
1080                 " (" + Functions.getMechanismName(mechanism) + ")";
1081         }
1082 
1083     }
1084 
1085     /**
1086      * Log in to this provider.
1087      *
1088      * <p> If the token expects a PIN to be supplied by the caller,
1089      * the <code>handler</code> implementation must support
1090      * a <code>PasswordCallback</code>.
1091      *
1092      * <p> To determine if the token supports a protected authentication path,
1093      * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted.
1094      *
1095      * @param subject this parameter is ignored
1096      * @param handler the <code>CallbackHandler</code> used by
1097      *  this provider to communicate with the caller
1098      *
1099      * @exception LoginException if the login operation fails
1100      * @exception SecurityException if the does not pass a security check for
1101      *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
1102      *  where <i>name</i> is the value returned by
1103      *  this provider's <code>getName</code> method
1104      */
1105     public void login(Subject subject, CallbackHandler handler)
1106         throws LoginException {
1107 
1108         // security check
1109 
1110         SecurityManager sm = System.getSecurityManager();
1111         if (sm != null) {
1112             if (debug != null) {
1113                 debug.println("checking login permission");
1114             }
1115             sm.checkPermission(new SecurityPermission
1116                         ("authProvider." + this.getName()));
1117         }
1118 
1119         if (hasValidToken() == false) {
1120             throw new LoginException("No token present");
1121         }
1122 
1123         // see if a login is required
1124 
1125         if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) {
1126             if (debug != null) {
1127                 debug.println("login operation not required for token - " +
1128                                 "ignoring login request");
1129             }
1130             return;
1131         }
1132 
1133         // see if user already logged in
1134 
1135         try {
1136             if (token.isLoggedInNow(null)) {
1137                 // user already logged in
1138                 if (debug != null) {
1139                     debug.println("user already logged in");
1140                 }
1141                 return;
1142             }
1143         } catch (PKCS11Exception e) {
1144             // ignore - fall thru and attempt login
1145         }
1146 
1147         // get the pin if necessary
1148 
1149         char[] pin = null;
1150         if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) {
1151 
1152             // get password
1153 
1154             CallbackHandler myHandler = getCallbackHandler(handler);
1155             if (myHandler == null) {
1156                 // XXX PolicyTool is dependent on this message text
1157                 throw new LoginException
1158                         ("no password provided, and no callback handler " +
1159                         "available for retrieving password");
1160             }
1161 
1162             java.text.MessageFormat form = new java.text.MessageFormat
1163                         (ResourcesMgr.getString
1164                         ("PKCS11.Token.providerName.Password."));
1165             Object[] source = { getName() };
1166 
1167             PasswordCallback pcall = new PasswordCallback(form.format(source),
1168                                                         false);
1169             Callback[] callbacks = { pcall };
1170             try {
1171                 myHandler.handle(callbacks);
1172             } catch (Exception e) {
1173                 LoginException le = new LoginException
1174                         ("Unable to perform password callback");
1175                 le.initCause(e);
1176                 throw le;
1177             }
1178 
1179             pin = pcall.getPassword();
1180             pcall.clearPassword();
1181             if (pin == null) {
1182                 if (debug != null) {
1183                     debug.println("caller passed NULL pin");
1184                 }
1185             }
1186         }
1187 
1188         // perform token login
1189 
1190         Session session = null;
1191         try {
1192             session = token.getOpSession();
1193 
1194             // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH
1195             p11.C_Login(session.id(), CKU_USER, pin);
1196             if (debug != null) {
1197                 debug.println("login succeeded");
1198             }
1199         } catch (PKCS11Exception pe) {
1200             if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) {
1201                 // let this one go
1202                 if (debug != null) {
1203                     debug.println("user already logged in");
1204                 }
1205                 return;
1206             } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) {
1207                 FailedLoginException fle = new FailedLoginException();
1208                 fle.initCause(pe);
1209                 throw fle;
1210             } else {
1211                 LoginException le = new LoginException();
1212                 le.initCause(pe);
1213                 throw le;
1214             }
1215         } finally {
1216             token.releaseSession(session);
1217             if (pin != null) {
1218                 Arrays.fill(pin, ' ');
1219             }
1220         }
1221 
1222         // we do not store the PIN in the subject for now
1223     }
1224 
1225     /**
1226      * Log out from this provider
1227      *
1228      * @exception LoginException if the logout operation fails
1229      * @exception SecurityException if the does not pass a security check for
1230      *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
1231      *  where <i>name</i> is the value returned by
1232      *  this provider's <code>getName</code> method
1233      */
1234     public void logout() throws LoginException {
1235 
1236         // security check
1237 
1238         SecurityManager sm = System.getSecurityManager();
1239         if (sm != null) {
1240             sm.checkPermission
1241                 (new SecurityPermission("authProvider." + this.getName()));
1242         }
1243 
1244         if (hasValidToken() == false) {
1245             // app may call logout for cleanup, allow
1246             return;
1247         }
1248 
1249         if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) {
1250             if (debug != null) {
1251                 debug.println("logout operation not required for token - " +
1252                                 "ignoring logout request");
1253             }
1254             return;
1255         }
1256 
1257         try {
1258             if (token.isLoggedInNow(null) == false) {
1259                 if (debug != null) {
1260                     debug.println("user not logged in");
1261                 }
1262                 return;
1263             }
1264         } catch (PKCS11Exception e) {
1265             // ignore
1266         }
1267 
1268         // perform token logout
1269 
1270         Session session = null;
1271         try {
1272             session = token.getOpSession();
1273             p11.C_Logout(session.id());
1274             if (debug != null) {
1275                 debug.println("logout succeeded");
1276             }
1277         } catch (PKCS11Exception pe) {
1278             if (pe.getErrorCode() == CKR_USER_NOT_LOGGED_IN) {
1279                 // let this one go
1280                 if (debug != null) {
1281                     debug.println("user not logged in");
1282                 }
1283                 return;
1284             }
1285             LoginException le = new LoginException();
1286             le.initCause(pe);
1287             throw le;
1288         } finally {
1289             token.releaseSession(session);
1290         }
1291     }
1292 
1293     /**
1294      * Set a <code>CallbackHandler</code>
1295      *
1296      * <p> The provider uses this handler if one is not passed to the
1297      * <code>login</code> method.  The provider also uses this handler
1298      * if it invokes <code>login</code> on behalf of callers.
1299      * In either case if a handler is not set via this method,
1300      * the provider queries the
1301      * <i>auth.login.defaultCallbackHandler</i> security property
1302      * for the fully qualified class name of a default handler implementation.
1303      * If the security property is not set,
1304      * the provider is assumed to have alternative means
1305      * for obtaining authentication information.
1306      *
1307      * @param handler a <code>CallbackHandler</code> for obtaining
1308      *          authentication information, which may be <code>null</code>
1309      *
1310      * @exception SecurityException if the caller does not pass a
1311      *  security check for
1312      *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
1313      *  where <i>name</i> is the value returned by
1314      *  this provider's <code>getName</code> method
1315      */
1316     public void setCallbackHandler(CallbackHandler handler) {
1317 
1318         // security check
1319 
1320         SecurityManager sm = System.getSecurityManager();
1321         if (sm != null) {
1322             sm.checkPermission
1323                 (new SecurityPermission("authProvider." + this.getName()));
1324         }
1325 
1326         synchronized (LOCK_HANDLER) {
1327             pHandler = handler;
1328         }
1329     }
1330 
1331     private CallbackHandler getCallbackHandler(CallbackHandler handler) {
1332 
1333         // get default handler if necessary
1334 
1335         if (handler != null) {
1336             return handler;
1337         }
1338 
1339         if (debug != null) {
1340             debug.println("getting provider callback handler");
1341         }
1342 
1343         synchronized (LOCK_HANDLER) {
1344             // see if handler was set via setCallbackHandler
1345             if (pHandler != null) {
1346                 return pHandler;
1347             }
1348 
1349             try {
1350                 if (debug != null) {
1351                     debug.println("getting default callback handler");
1352                 }
1353 
1354                 CallbackHandler myHandler = AccessController.doPrivileged
1355                     (new PrivilegedExceptionAction<CallbackHandler>() {
1356                     public CallbackHandler run() throws Exception {
1357 
1358                         String defaultHandler =
1359                                 java.security.Security.getProperty
1360                                 ("auth.login.defaultCallbackHandler");
1361 
1362                         if (defaultHandler == null ||
1363                             defaultHandler.length() == 0) {
1364 
1365                             // ok
1366                             if (debug != null) {
1367                                 debug.println("no default handler set");
1368                             }
1369                             return null;
1370                         }
1371 
1372                         Class c = Class.forName
1373                                 (defaultHandler,
1374                                 true,
1375                                 Thread.currentThread().getContextClassLoader());
1376                         return (CallbackHandler)c.newInstance();
1377                     }
1378                 });
1379 
1380                 // save it
1381                 pHandler = myHandler;
1382                 return myHandler;
1383 
1384             } catch (PrivilegedActionException pae) {
1385                 // ok
1386                 if (debug != null) {
1387                     debug.println("Unable to load default callback handler");
1388                     pae.printStackTrace();
1389                 }
1390             }
1391         }
1392         return null;
1393     }
1394 
1395     private Object writeReplace() throws ObjectStreamException {
1396         return new SunPKCS11Rep(this);
1397     }
1398 
1399     /**
1400      * Serialized representation of the SunPKCS11 provider.
1401      */
1402     private static class SunPKCS11Rep implements Serializable {
1403 
1404         static final long serialVersionUID = -2896606995897745419L;
1405 
1406         private final String providerName;
1407 
1408         private final String configName;
1409 
1410         SunPKCS11Rep(SunPKCS11 provider) throws NotSerializableException {
1411             providerName = provider.getName();
1412             configName = provider.configName;
1413             if (Security.getProvider(providerName) != provider) {
1414                 throw new NotSerializableException("Only SunPKCS11 providers "
1415                     + "installed in java.security.Security can be serialized");
1416             }
1417         }
1418 
1419         private Object readResolve() throws ObjectStreamException {
1420             SunPKCS11 p = (SunPKCS11)Security.getProvider(providerName);
1421             if ((p == null) || (p.configName.equals(configName) == false)) {
1422                 throw new NotSerializableException("Could not find "
1423                         + providerName + " in installed providers");
1424             }
1425             return p;
1426         }
1427     }
1428 }