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             if ((slotID < 0) || showInfo) {
 347                 long[] slots = p11.C_GetSlotList(false);
 348                 if (showInfo) {
 349                     System.out.println("All slots: " + toString(slots));
 350                     slots = p11.C_GetSlotList(true);
 351                     System.out.println("Slots with tokens: " + toString(slots));
 352                 }
 353                 if (slotID < 0) {
 354                     if ((slotListIndex < 0)
 355                             || (slotListIndex >= slots.length)) {
 356                         throw new ProviderException("slotListIndex is "
 357                             + slotListIndex
 358                             + " but token only has " + slots.length + " slots");
 359                     }
 360                     slotID = slots[slotListIndex];
 361                 }
 362             }
 363             this.slotID = slotID;
 364             CK_SLOT_INFO slotInfo = p11.C_GetSlotInfo(slotID);
 365             removable = (slotInfo.flags & CKF_REMOVABLE_DEVICE) != 0;
 366             initToken(slotInfo);
 367             if (nssModule != null) {
 368                 nssModule.setProvider(this);
 369             }
 370         } catch (Exception e) {
 371             if (config.getHandleStartupErrors() == Config.ERR_IGNORE_ALL) {
 372                 throw new UnsupportedOperationException
 373                         ("Initialization failed", e);
 374             } else {
 375                 throw new ProviderException
 376                         ("Initialization failed", e);
 377             }
 378         }
 379     }
 380 
 381     private static String toString(long[] longs) {
 382         if (longs.length == 0) {
 383             return "(none)";
 384         }
 385         StringBuilder sb = new StringBuilder();
 386         sb.append(longs[0]);
 387         for (int i = 1; i < longs.length; i++) {
 388             sb.append(", ");
 389             sb.append(longs[i]);
 390         }
 391         return sb.toString();
 392     }
 393 
 394     public boolean equals(Object obj) {
 395         return this == obj;
 396     }
 397 
 398     public int hashCode() {
 399         return System.identityHashCode(this);
 400     }
 401 
 402     private static String[] s(String s1) {
 403         return new String[] {s1};
 404     }
 405 
 406     private static String[] s(String s1, String s2) {
 407         return new String[] {s1, s2};
 408     }
 409 
 410     private static final class Descriptor {
 411         final String type;
 412         final String algorithm;
 413         final String className;
 414         final String[] aliases;
 415         final int[] mechanisms;
 416 
 417         private Descriptor(String type, String algorithm, String className,
 418                 String[] aliases, int[] mechanisms) {
 419             this.type = type;
 420             this.algorithm = algorithm;
 421             this.className = className;
 422             this.aliases = aliases;
 423             this.mechanisms = mechanisms;
 424         }
 425         private P11Service service(Token token, int mechanism) {
 426             return new P11Service
 427                 (token, type, algorithm, className, aliases, mechanism);
 428         }
 429         public String toString() {
 430             return type + "." + algorithm;
 431         }
 432     }
 433 
 434     // Map from mechanism to List of Descriptors that should be
 435     // registered if the mechanism is supported
 436     private final static Map<Integer,List<Descriptor>> descriptors =
 437         new HashMap<Integer,List<Descriptor>>();
 438 
 439     private static int[] m(long m1) {
 440         return new int[] {(int)m1};
 441     }
 442 
 443     private static int[] m(long m1, long m2) {
 444         return new int[] {(int)m1, (int)m2};
 445     }
 446 
 447     private static int[] m(long m1, long m2, long m3) {
 448         return new int[] {(int)m1, (int)m2, (int)m3};
 449     }
 450 
 451     private static int[] m(long m1, long m2, long m3, long m4) {
 452         return new int[] {(int)m1, (int)m2, (int)m3, (int)m4};
 453     }
 454 
 455     private static void d(String type, String algorithm, String className,
 456             int[] m) {
 457         register(new Descriptor(type, algorithm, className, null, m));
 458     }
 459 
 460     private static void d(String type, String algorithm, String className,
 461             String[] aliases, int[] m) {
 462         register(new Descriptor(type, algorithm, className, aliases, m));
 463     }
 464 
 465     private static void register(Descriptor d) {
 466         for (int i = 0; i < d.mechanisms.length; i++) {
 467             int m = d.mechanisms[i];
 468             Integer key = Integer.valueOf(m);
 469             List<Descriptor> list = descriptors.get(key);
 470             if (list == null) {
 471                 list = new ArrayList<Descriptor>();
 472                 descriptors.put(key, list);
 473             }
 474             list.add(d);
 475         }
 476     }
 477 
 478     private final static String MD  = "MessageDigest";
 479 
 480     private final static String SIG = "Signature";
 481 
 482     private final static String KPG = "KeyPairGenerator";
 483 
 484     private final static String KG  = "KeyGenerator";
 485 
 486     private final static String AGP = "AlgorithmParameters";
 487 
 488     private final static String KF  = "KeyFactory";
 489 
 490     private final static String SKF = "SecretKeyFactory";
 491 
 492     private final static String CIP = "Cipher";
 493 
 494     private final static String MAC = "Mac";
 495 
 496     private final static String KA  = "KeyAgreement";
 497 
 498     private final static String KS  = "KeyStore";
 499 
 500     private final static String SR  = "SecureRandom";
 501 
 502     static {
 503         // names of all the implementation classes
 504         // use local variables, only used here
 505         String P11Digest           = "sun.security.pkcs11.P11Digest";
 506         String P11MAC              = "sun.security.pkcs11.P11MAC";
 507         String P11KeyPairGenerator = "sun.security.pkcs11.P11KeyPairGenerator";
 508         String P11KeyGenerator     = "sun.security.pkcs11.P11KeyGenerator";
 509         String P11RSAKeyFactory    = "sun.security.pkcs11.P11RSAKeyFactory";
 510         String P11DSAKeyFactory    = "sun.security.pkcs11.P11DSAKeyFactory";
 511         String P11DHKeyFactory     = "sun.security.pkcs11.P11DHKeyFactory";
 512         String P11KeyAgreement     = "sun.security.pkcs11.P11KeyAgreement";
 513         String P11SecretKeyFactory = "sun.security.pkcs11.P11SecretKeyFactory";
 514         String P11Cipher           = "sun.security.pkcs11.P11Cipher";
 515         String P11RSACipher        = "sun.security.pkcs11.P11RSACipher";
 516         String P11Signature        = "sun.security.pkcs11.P11Signature";
 517 
 518         // XXX register all aliases
 519 
 520         d(MD, "MD2",            P11Digest,
 521                 m(CKM_MD2));
 522         d(MD, "MD5",            P11Digest,
 523                 m(CKM_MD5));
 524         d(MD, "SHA1",           P11Digest,              s("SHA", "SHA-1"),
 525                 m(CKM_SHA_1));
 526         d(MD, "SHA-256",        P11Digest,
 527                 m(CKM_SHA256));
 528         d(MD, "SHA-384",        P11Digest,
 529                 m(CKM_SHA384));
 530         d(MD, "SHA-512",        P11Digest,
 531                 m(CKM_SHA512));
 532 
 533         d(MAC, "HmacMD5",       P11MAC,
 534                 m(CKM_MD5_HMAC));
 535         d(MAC, "HmacSHA1",      P11MAC,
 536                 m(CKM_SHA_1_HMAC));
 537         d(MAC, "HmacSHA256",    P11MAC,
 538                 m(CKM_SHA256_HMAC));
 539         d(MAC, "HmacSHA384",    P11MAC,
 540                 m(CKM_SHA384_HMAC));
 541         d(MAC, "HmacSHA512",    P11MAC,
 542                 m(CKM_SHA512_HMAC));
 543         d(MAC, "SslMacMD5",     P11MAC,
 544                 m(CKM_SSL3_MD5_MAC));
 545         d(MAC, "SslMacSHA1",    P11MAC,
 546                 m(CKM_SSL3_SHA1_MAC));
 547 
 548         d(KPG, "RSA",           P11KeyPairGenerator,
 549                 m(CKM_RSA_PKCS_KEY_PAIR_GEN));
 550         d(KPG, "DSA",           P11KeyPairGenerator,
 551                 m(CKM_DSA_KEY_PAIR_GEN));
 552         d(KPG, "DH",            P11KeyPairGenerator,    s("DiffieHellman"),
 553                 m(CKM_DH_PKCS_KEY_PAIR_GEN));
 554         d(KPG, "EC",            P11KeyPairGenerator,
 555                 m(CKM_EC_KEY_PAIR_GEN));
 556 
 557         d(KG,  "ARCFOUR",       P11KeyGenerator,        s("RC4"),
 558                 m(CKM_RC4_KEY_GEN));
 559         d(KG,  "DES",           P11KeyGenerator,
 560                 m(CKM_DES_KEY_GEN));
 561         d(KG,  "DESede",        P11KeyGenerator,
 562                 m(CKM_DES3_KEY_GEN, CKM_DES2_KEY_GEN));
 563         d(KG,  "AES",           P11KeyGenerator,
 564                 m(CKM_AES_KEY_GEN));
 565         d(KG,  "Blowfish",      P11KeyGenerator,
 566                 m(CKM_BLOWFISH_KEY_GEN));
 567 
 568         // register (Secret)KeyFactories if there are any mechanisms
 569         // for a particular algorithm that we support
 570         d(KF, "RSA",            P11RSAKeyFactory,
 571                 m(CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_X_509));
 572         d(KF, "DSA",            P11DSAKeyFactory,
 573                 m(CKM_DSA_KEY_PAIR_GEN, CKM_DSA, CKM_DSA_SHA1));
 574         d(KF, "DH",             P11DHKeyFactory,        s("DiffieHellman"),
 575                 m(CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_DERIVE));
 576         d(KF, "EC",             P11DHKeyFactory,
 577                 m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE,
 578                     CKM_ECDSA, CKM_ECDSA_SHA1));
 579 
 580         // AlgorithmParameters for EC.
 581         // Only needed until we have an EC implementation in the SUN provider.
 582         d(AGP, "EC",            "sun.security.ec.ECParameters",
 583                                                 s("1.2.840.10045.2.1"),
 584                 m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE,
 585                     CKM_ECDSA, CKM_ECDSA_SHA1));
 586 
 587         d(KA, "DH",             P11KeyAgreement,        s("DiffieHellman"),
 588                 m(CKM_DH_PKCS_DERIVE));
 589         d(KA, "ECDH",           "sun.security.pkcs11.P11ECDHKeyAgreement",
 590                 m(CKM_ECDH1_DERIVE));
 591 
 592         d(SKF, "ARCFOUR",       P11SecretKeyFactory,    s("RC4"),
 593                 m(CKM_RC4));
 594         d(SKF, "DES",           P11SecretKeyFactory,
 595                 m(CKM_DES_CBC));
 596         d(SKF, "DESede",        P11SecretKeyFactory,
 597                 m(CKM_DES3_CBC));
 598         d(SKF, "AES",           P11SecretKeyFactory,
 599                 m(CKM_AES_CBC));
 600         d(SKF, "Blowfish",      P11SecretKeyFactory,
 601                 m(CKM_BLOWFISH_CBC));
 602 
 603         // XXX attributes for Ciphers (supported modes, padding)
 604         d(CIP, "ARCFOUR",                       P11Cipher,      s("RC4"),
 605                 m(CKM_RC4));
 606         d(CIP, "DES/CBC/NoPadding",             P11Cipher,
 607                 m(CKM_DES_CBC));
 608         d(CIP, "DES/CBC/PKCS5Padding",          P11Cipher,
 609                 m(CKM_DES_CBC_PAD, CKM_DES_CBC));
 610         d(CIP, "DES/ECB/NoPadding",             P11Cipher,
 611                 m(CKM_DES_ECB));
 612         d(CIP, "DES/ECB/PKCS5Padding",          P11Cipher,      s("DES"),
 613                 m(CKM_DES_ECB));
 614         d(CIP, "DESede/CBC/NoPadding",          P11Cipher,
 615                 m(CKM_DES3_CBC));
 616         d(CIP, "DESede/CBC/PKCS5Padding",       P11Cipher,
 617                 m(CKM_DES3_CBC_PAD, CKM_DES3_CBC));
 618         d(CIP, "DESede/ECB/NoPadding",          P11Cipher,
 619                 m(CKM_DES3_ECB));
 620         d(CIP, "DESede/ECB/PKCS5Padding",       P11Cipher,      s("DESede"),
 621                 m(CKM_DES3_ECB));
 622         d(CIP, "AES/CBC/NoPadding",             P11Cipher,
 623                 m(CKM_AES_CBC));
 624         d(CIP, "AES/CBC/PKCS5Padding",          P11Cipher,
 625                 m(CKM_AES_CBC_PAD, CKM_AES_CBC));
 626         d(CIP, "AES/ECB/NoPadding",             P11Cipher,
 627                 m(CKM_AES_ECB));
 628         d(CIP, "AES/ECB/PKCS5Padding",          P11Cipher,      s("AES"),
 629                 m(CKM_AES_ECB));
 630         d(CIP, "AES/CTR/NoPadding",             P11Cipher,
 631                 m(CKM_AES_CTR));
 632         d(CIP, "Blowfish/CBC/NoPadding",        P11Cipher,
 633                 m(CKM_BLOWFISH_CBC));
 634         d(CIP, "Blowfish/CBC/PKCS5Padding",     P11Cipher,
 635                 m(CKM_BLOWFISH_CBC));
 636 
 637         // XXX RSA_X_509, RSA_OAEP not yet supported
 638         d(CIP, "RSA/ECB/PKCS1Padding",          P11RSACipher,   s("RSA"),
 639                 m(CKM_RSA_PKCS));
 640         d(CIP, "RSA/ECB/NoPadding",             P11RSACipher,
 641                 m(CKM_RSA_X_509));
 642 
 643         d(SIG, "RawDSA",        P11Signature,           s("NONEwithDSA"),
 644                 m(CKM_DSA));
 645         d(SIG, "DSA",           P11Signature,           s("SHA1withDSA"),
 646                 m(CKM_DSA_SHA1, CKM_DSA));
 647         d(SIG, "NONEwithECDSA", P11Signature,
 648                 m(CKM_ECDSA));
 649         d(SIG, "SHA1withECDSA", P11Signature,           s("ECDSA"),
 650                 m(CKM_ECDSA_SHA1, CKM_ECDSA));
 651         d(SIG, "SHA256withECDSA",       P11Signature,
 652                 m(CKM_ECDSA));
 653         d(SIG, "SHA384withECDSA",       P11Signature,
 654                 m(CKM_ECDSA));
 655         d(SIG, "SHA512withECDSA",       P11Signature,
 656                 m(CKM_ECDSA));
 657         d(SIG, "MD2withRSA",    P11Signature,
 658                 m(CKM_MD2_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 659         d(SIG, "MD5withRSA",    P11Signature,
 660                 m(CKM_MD5_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 661         d(SIG, "SHA1withRSA",   P11Signature,
 662                 m(CKM_SHA1_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 663         d(SIG, "SHA256withRSA", P11Signature,
 664                 m(CKM_SHA256_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 665         d(SIG, "SHA384withRSA", P11Signature,
 666                 m(CKM_SHA384_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 667         d(SIG, "SHA512withRSA", P11Signature,
 668                 m(CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
 669 
 670         /*
 671          * TLS 1.2 uses a different hash algorithm than 1.0/1.1 for the
 672          * PRF calculations.  As of 2010, there is no PKCS11-level
 673          * support for TLS 1.2 PRF calculations, and no known OS's have
 674          * an internal variant we could use.  Therefore for TLS 1.2, we
 675          * are updating JSSE to request different provider algorithms
 676          * (e.g. "SunTls12Prf"), and currently only SunJCE has these
 677          * TLS 1.2 algorithms.
 678          *
 679          * If we reused the names such as "SunTlsPrf", the PKCS11
 680          * providers would need be updated to fail correctly when
 681          * presented with the wrong version number (via
 682          * Provider.Service.supportsParameters()), and we would also
 683          * need to add the appropriate supportsParamters() checks into
 684          * KeyGenerators (not currently there).
 685          *
 686          * In the future, if PKCS11 support is added, we will restructure
 687          * this.
 688          */
 689         d(KG, "SunTlsRsaPremasterSecret",
 690                     "sun.security.pkcs11.P11TlsRsaPremasterSecretGenerator",
 691                 m(CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_TLS_PRE_MASTER_KEY_GEN));
 692         d(KG, "SunTlsMasterSecret",
 693                     "sun.security.pkcs11.P11TlsMasterSecretGenerator",
 694                 m(CKM_SSL3_MASTER_KEY_DERIVE, CKM_TLS_MASTER_KEY_DERIVE,
 695                     CKM_SSL3_MASTER_KEY_DERIVE_DH,
 696                     CKM_TLS_MASTER_KEY_DERIVE_DH));
 697         d(KG, "SunTlsKeyMaterial",
 698                     "sun.security.pkcs11.P11TlsKeyMaterialGenerator",
 699                 m(CKM_SSL3_KEY_AND_MAC_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE));
 700         d(KG, "SunTlsPrf", "sun.security.pkcs11.P11TlsPrfGenerator",
 701                 m(CKM_TLS_PRF, CKM_NSS_TLS_PRF_GENERAL));
 702     }
 703 
 704     // background thread that periodically checks for token insertion
 705     // if no token is present. We need to do that in a separate thread because
 706     // the insertion check may block for quite a long time on some tokens.
 707     private static class TokenPoller implements Runnable {
 708         private final SunPKCS11 provider;
 709         private volatile boolean enabled;
 710         private TokenPoller(SunPKCS11 provider) {
 711             this.provider = provider;
 712             enabled = true;
 713         }
 714         public void run() {
 715             int interval = provider.config.getInsertionCheckInterval();
 716             while (enabled) {
 717                 try {
 718                     Thread.sleep(interval);
 719                 } catch (InterruptedException e) {
 720                     break;
 721                 }
 722                 if (enabled == false) {
 723                     break;
 724                 }
 725                 try {
 726                     provider.initToken(null);
 727                 } catch (PKCS11Exception e) {
 728                     // ignore
 729                 }
 730             }
 731         }
 732         void disable() {
 733             enabled = false;
 734         }
 735     }
 736 
 737     // create the poller thread, if not already active
 738     private void createPoller() {
 739         if (poller != null) {
 740             return;
 741         }
 742         TokenPoller poller = new TokenPoller(this);
 743         Thread t = new Thread(poller, "Poller " + getName());
 744         t.setDaemon(true);
 745         t.setPriority(Thread.MIN_PRIORITY);
 746         t.start();
 747         this.poller = poller;
 748     }
 749 
 750     // destroy the poller thread, if active
 751     private void destroyPoller() {
 752         if (poller != null) {
 753             poller.disable();
 754             poller = null;
 755         }
 756     }
 757 
 758     private boolean hasValidToken() {
 759         /* Commented out to work with Solaris softtoken impl which
 760            returns 0-value flags, e.g. both REMOVABLE_DEVICE and
 761            TOKEN_PRESENT are false, when it can't access the token.
 762         if (removable == false) {
 763             return true;
 764         }
 765         */
 766         Token token = this.token;
 767         return (token != null) && token.isValid();
 768     }
 769 
 770     // destroy the token. Called if we detect that it has been removed
 771     synchronized void uninitToken(Token token) {
 772         if (this.token != token) {
 773             // mismatch, our token must already be destroyed
 774             return;
 775         }
 776         destroyPoller();
 777         this.token = null;
 778         // unregister all algorithms
 779         AccessController.doPrivileged(new PrivilegedAction<Object>() {
 780             public Object run() {
 781                 clear();
 782                 return null;
 783             }
 784         });
 785         createPoller();
 786     }
 787 
 788     // test if a token is present and initialize this provider for it if so.
 789     // does nothing if no token is found
 790     // called from constructor and by poller
 791     private void initToken(CK_SLOT_INFO slotInfo) throws PKCS11Exception {
 792         if (slotInfo == null) {
 793             slotInfo = p11.C_GetSlotInfo(slotID);
 794         }
 795         if (removable && (slotInfo.flags & CKF_TOKEN_PRESENT) == 0) {
 796             createPoller();
 797             return;
 798         }
 799         destroyPoller();
 800         boolean showInfo = config.getShowInfo();
 801         if (showInfo) {
 802             System.out.println("Slot info for slot " + slotID + ":");
 803             System.out.println(slotInfo);
 804         }
 805         final Token token = new Token(this);
 806         if (showInfo) {
 807             System.out.println
 808                 ("Token info for token in slot " + slotID + ":");
 809             System.out.println(token.tokenInfo);
 810         }
 811         long[] supportedMechanisms = p11.C_GetMechanismList(slotID);
 812 
 813         // Create a map from the various Descriptors to the "most
 814         // preferred" mechanism that was defined during the
 815         // static initialization.  For example, DES/CBC/PKCS5Padding
 816         // could be mapped to CKM_DES_CBC_PAD or CKM_DES_CBC.  Prefer
 817         // the earliest entry.  When asked for "DES/CBC/PKCS5Padding", we
 818         // return a CKM_DES_CBC_PAD.
 819         final Map<Descriptor,Integer> supportedAlgs =
 820                                         new HashMap<Descriptor,Integer>();
 821         for (int i = 0; i < supportedMechanisms.length; i++) {
 822             long longMech = supportedMechanisms[i];
 823             boolean isEnabled = config.isEnabled(longMech);
 824             if (showInfo) {
 825                 CK_MECHANISM_INFO mechInfo =
 826                         p11.C_GetMechanismInfo(slotID, longMech);
 827                 System.out.println("Mechanism " +
 828                         Functions.getMechanismName(longMech) + ":");
 829                 if (isEnabled == false) {
 830                     System.out.println("DISABLED in configuration");
 831                 }
 832                 System.out.println(mechInfo);
 833             }
 834             if (isEnabled == false) {
 835                 continue;
 836             }
 837             // we do not know of mechs with the upper 32 bits set
 838             if (longMech >>> 32 != 0) {
 839                 continue;
 840             }
 841             int mech = (int)longMech;
 842             Integer integerMech = Integer.valueOf(mech);
 843             List<Descriptor> ds = descriptors.get(integerMech);
 844             if (ds == null) {
 845                 continue;
 846             }
 847             for (Descriptor d : ds) {
 848                 Integer oldMech = supportedAlgs.get(d);
 849                 if (oldMech == null) {
 850                     supportedAlgs.put(d, integerMech);
 851                     continue;
 852                 }
 853                 // See if there is something "more preferred"
 854                 // than what we currently have in the supportedAlgs
 855                 // map.
 856                 int intOldMech = oldMech.intValue();
 857                 for (int j = 0; j < d.mechanisms.length; j++) {
 858                     int nextMech = d.mechanisms[j];
 859                     if (mech == nextMech) {
 860                         supportedAlgs.put(d, integerMech);
 861                         break;
 862                     } else if (intOldMech == nextMech) {
 863                         break;
 864                     }
 865                 }
 866             }
 867 
 868         }
 869 
 870         // register algorithms in provider
 871         AccessController.doPrivileged(new PrivilegedAction<Object>() {
 872             public Object run() {
 873                 for (Map.Entry<Descriptor,Integer> entry
 874                         : supportedAlgs.entrySet()) {
 875                     Descriptor d = entry.getKey();
 876                     int mechanism = entry.getValue().intValue();
 877                     Service s = d.service(token, mechanism);
 878                     putService(s);
 879                 }
 880                 if (((token.tokenInfo.flags & CKF_RNG) != 0)
 881                         && config.isEnabled(PCKM_SECURERANDOM)
 882                         && !token.sessionManager.lowMaxSessions()) {
 883                     // do not register SecureRandom if the token does
 884                     // not support many sessions. if we did, we might
 885                     // run out of sessions in the middle of a
 886                     // nextBytes() call where we cannot fail over.
 887                     putService(new P11Service(token, SR, "PKCS11",
 888                         "sun.security.pkcs11.P11SecureRandom", null,
 889                         PCKM_SECURERANDOM));
 890                 }
 891                 if (config.isEnabled(PCKM_KEYSTORE)) {
 892                     putService(new P11Service(token, KS, "PKCS11",
 893                         "sun.security.pkcs11.P11KeyStore",
 894                         s("PKCS11-" + config.getName()),
 895                         PCKM_KEYSTORE));
 896                 }
 897                 return null;
 898             }
 899         });
 900 
 901         this.token = token;
 902     }
 903 
 904     private static final class P11Service extends Service {
 905 
 906         private final Token token;
 907 
 908         private final long mechanism;
 909 
 910         P11Service(Token token, String type, String algorithm,
 911                 String className, String[] al, long mechanism) {
 912             super(token.provider, type, algorithm, className, toList(al), null);
 913             this.token = token;
 914             this.mechanism = mechanism & 0xFFFFFFFFL;
 915         }
 916 
 917         private static List<String> toList(String[] aliases) {
 918             return (aliases == null) ? null : Arrays.asList(aliases);
 919         }
 920 
 921         public Object newInstance(Object param)
 922                 throws NoSuchAlgorithmException {
 923             if (token.isValid() == false) {
 924                 throw new NoSuchAlgorithmException("Token has been removed");
 925             }
 926             try {
 927                 return newInstance0(param);
 928             } catch (PKCS11Exception e) {
 929                 throw new NoSuchAlgorithmException(e);
 930             }
 931         }
 932 
 933         public Object newInstance0(Object param) throws
 934                 PKCS11Exception, NoSuchAlgorithmException {
 935             String algorithm = getAlgorithm();
 936             String type = getType();
 937             if (type == MD) {
 938                 return new P11Digest(token, algorithm, mechanism);
 939             } else if (type == CIP) {
 940                 if (algorithm.startsWith("RSA")) {
 941                     return new P11RSACipher(token, algorithm, mechanism);
 942                 } else {
 943                     return new P11Cipher(token, algorithm, mechanism);
 944                 }
 945             } else if (type == SIG) {
 946                 return new P11Signature(token, algorithm, mechanism);
 947             } else if (type == MAC) {
 948                 return new P11Mac(token, algorithm, mechanism);
 949             } else if (type == KPG) {
 950                 return new P11KeyPairGenerator(token, algorithm, mechanism);
 951             } else if (type == KA) {
 952                 if (algorithm.equals("ECDH")) {
 953                     return new P11ECDHKeyAgreement(token, algorithm, mechanism);
 954                 } else {
 955                     return new P11KeyAgreement(token, algorithm, mechanism);
 956                 }
 957             } else if (type == KF) {
 958                 return token.getKeyFactory(algorithm);
 959             } else if (type == SKF) {
 960                 return new P11SecretKeyFactory(token, algorithm);
 961             } else if (type == KG) {
 962                 // reference equality
 963                 if (algorithm == "SunTlsRsaPremasterSecret") {
 964                     return new P11TlsRsaPremasterSecretGenerator(
 965                         token, algorithm, mechanism);
 966                 } else if (algorithm == "SunTlsMasterSecret") {
 967                     return new P11TlsMasterSecretGenerator(
 968                         token, algorithm, mechanism);
 969                 } else if (algorithm == "SunTlsKeyMaterial") {
 970                     return new P11TlsKeyMaterialGenerator(
 971                         token, algorithm, mechanism);
 972                 } else if (algorithm == "SunTlsPrf") {
 973                     return new P11TlsPrfGenerator(token, algorithm, mechanism);
 974                 } else {
 975                     return new P11KeyGenerator(token, algorithm, mechanism);
 976                 }
 977             } else if (type == SR) {
 978                 return token.getRandom();
 979             } else if (type == KS) {
 980                 return token.getKeyStore();
 981             } else if (type == AGP) {
 982                 return new sun.security.ec.ECParameters();
 983             } else {
 984                 throw new NoSuchAlgorithmException("Unknown type: " + type);
 985             }
 986         }
 987 
 988         public boolean supportsParameter(Object param) {
 989             if ((param == null) || (token.isValid() == false)) {
 990                 return false;
 991             }
 992             if (param instanceof Key == false) {
 993                 throw new InvalidParameterException("Parameter must be a Key");
 994             }
 995             String algorithm = getAlgorithm();
 996             String type = getType();
 997             Key key = (Key)param;
 998             String keyAlgorithm = key.getAlgorithm();
 999             // RSA signatures and cipher
1000             if (((type == CIP) && algorithm.startsWith("RSA"))
1001                     || (type == SIG) && algorithm.endsWith("RSA")) {
1002                 if (keyAlgorithm.equals("RSA") == false) {
1003                     return false;
1004                 }
1005                 return isLocalKey(key)
1006                         || (key instanceof RSAPrivateKey)
1007                         || (key instanceof RSAPublicKey);
1008             }
1009             // EC
1010             if (((type == KA) && algorithm.equals("ECDH"))
1011                     || ((type == SIG) && algorithm.endsWith("ECDSA"))) {
1012                 if (keyAlgorithm.equals("EC") == false) {
1013                     return false;
1014                 }
1015                 return isLocalKey(key)
1016                         || (key instanceof ECPrivateKey)
1017                         || (key instanceof ECPublicKey);
1018             }
1019             // DSA signatures
1020             if ((type == SIG) && algorithm.endsWith("DSA")) {
1021                 if (keyAlgorithm.equals("DSA") == false) {
1022                     return false;
1023                 }
1024                 return isLocalKey(key)
1025                         || (key instanceof DSAPrivateKey)
1026                         || (key instanceof DSAPublicKey);
1027             }
1028             // MACs and symmetric ciphers
1029             if ((type == CIP) || (type == MAC)) {
1030                 // do not check algorithm name, mismatch is unlikely anyway
1031                 return isLocalKey(key) || "RAW".equals(key.getFormat());
1032             }
1033             // DH key agreement
1034             if (type == KA) {
1035                 if (keyAlgorithm.equals("DH") == false) {
1036                     return false;
1037                 }
1038                 return isLocalKey(key)
1039                         || (key instanceof DHPrivateKey)
1040                         || (key instanceof DHPublicKey);
1041             }
1042             // should not reach here,
1043             // unknown engine type or algorithm
1044             throw new AssertionError
1045                 ("SunPKCS11 error: " + type + ", " + algorithm);
1046         }
1047 
1048         private boolean isLocalKey(Key key) {
1049             return (key instanceof P11Key) && (((P11Key)key).token == token);
1050         }
1051 
1052         public String toString() {
1053             return super.toString() +
1054                 " (" + Functions.getMechanismName(mechanism) + ")";
1055         }
1056 
1057     }
1058 
1059     /**
1060      * Log in to this provider.
1061      *
1062      * <p> If the token expects a PIN to be supplied by the caller,
1063      * the <code>handler</code> implementation must support
1064      * a <code>PasswordCallback</code>.
1065      *
1066      * <p> To determine if the token supports a protected authentication path,
1067      * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted.
1068      *
1069      * @param subject this parameter is ignored
1070      * @param handler the <code>CallbackHandler</code> used by
1071      *  this provider to communicate with the caller
1072      *
1073      * @exception LoginException if the login operation fails
1074      * @exception SecurityException if the does not pass a security check for
1075      *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
1076      *  where <i>name</i> is the value returned by
1077      *  this provider's <code>getName</code> method
1078      */
1079     public void login(Subject subject, CallbackHandler handler)
1080         throws LoginException {
1081 
1082         // security check
1083 
1084         SecurityManager sm = System.getSecurityManager();
1085         if (sm != null) {
1086             if (debug != null) {
1087                 debug.println("checking login permission");
1088             }
1089             sm.checkPermission(new SecurityPermission
1090                         ("authProvider." + this.getName()));
1091         }
1092 
1093         if (hasValidToken() == false) {
1094             throw new LoginException("No token present");
1095         }
1096 
1097         // see if a login is required
1098 
1099         if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) {
1100             if (debug != null) {
1101                 debug.println("login operation not required for token - " +
1102                                 "ignoring login request");
1103             }
1104             return;
1105         }
1106 
1107         // see if user already logged in
1108 
1109         try {
1110             if (token.isLoggedInNow(null)) {
1111                 // user already logged in
1112                 if (debug != null) {
1113                     debug.println("user already logged in");
1114                 }
1115                 return;
1116             }
1117         } catch (PKCS11Exception e) {
1118             // ignore - fall thru and attempt login
1119         }
1120 
1121         // get the pin if necessary
1122 
1123         char[] pin = null;
1124         if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) {
1125 
1126             // get password
1127 
1128             CallbackHandler myHandler = getCallbackHandler(handler);
1129             if (myHandler == null) {
1130                 // XXX PolicyTool is dependent on this message text
1131                 throw new LoginException
1132                         ("no password provided, and no callback handler " +
1133                         "available for retrieving password");
1134             }
1135 
1136             java.text.MessageFormat form = new java.text.MessageFormat
1137                         (ResourcesMgr.getString
1138                         ("PKCS11.Token.providerName.Password."));
1139             Object[] source = { getName() };
1140 
1141             PasswordCallback pcall = new PasswordCallback(form.format(source),
1142                                                         false);
1143             Callback[] callbacks = { pcall };
1144             try {
1145                 myHandler.handle(callbacks);
1146             } catch (Exception e) {
1147                 LoginException le = new LoginException
1148                         ("Unable to perform password callback");
1149                 le.initCause(e);
1150                 throw le;
1151             }
1152 
1153             pin = pcall.getPassword();
1154             pcall.clearPassword();
1155             if (pin == null) {
1156                 if (debug != null) {
1157                     debug.println("caller passed NULL pin");
1158                 }
1159             }
1160         }
1161 
1162         // perform token login
1163 
1164         Session session = null;
1165         try {
1166             session = token.getOpSession();
1167 
1168             // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH
1169             p11.C_Login(session.id(), CKU_USER, pin);
1170             if (debug != null) {
1171                 debug.println("login succeeded");
1172             }
1173         } catch (PKCS11Exception pe) {
1174             if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) {
1175                 // let this one go
1176                 if (debug != null) {
1177                     debug.println("user already logged in");
1178                 }
1179                 return;
1180             } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) {
1181                 FailedLoginException fle = new FailedLoginException();
1182                 fle.initCause(pe);
1183                 throw fle;
1184             } else {
1185                 LoginException le = new LoginException();
1186                 le.initCause(pe);
1187                 throw le;
1188             }
1189         } finally {
1190             token.releaseSession(session);
1191             if (pin != null) {
1192                 Arrays.fill(pin, ' ');
1193             }
1194         }
1195 
1196         // we do not store the PIN in the subject for now
1197     }
1198 
1199     /**
1200      * Log out from this provider
1201      *
1202      * @exception LoginException if the logout operation fails
1203      * @exception SecurityException if the does not pass a security check for
1204      *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
1205      *  where <i>name</i> is the value returned by
1206      *  this provider's <code>getName</code> method
1207      */
1208     public void logout() throws LoginException {
1209 
1210         // security check
1211 
1212         SecurityManager sm = System.getSecurityManager();
1213         if (sm != null) {
1214             sm.checkPermission
1215                 (new SecurityPermission("authProvider." + this.getName()));
1216         }
1217 
1218         if (hasValidToken() == false) {
1219             // app may call logout for cleanup, allow
1220             return;
1221         }
1222 
1223         if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) {
1224             if (debug != null) {
1225                 debug.println("logout operation not required for token - " +
1226                                 "ignoring logout request");
1227             }
1228             return;
1229         }
1230 
1231         try {
1232             if (token.isLoggedInNow(null) == false) {
1233                 if (debug != null) {
1234                     debug.println("user not logged in");
1235                 }
1236                 return;
1237             }
1238         } catch (PKCS11Exception e) {
1239             // ignore
1240         }
1241 
1242         // perform token logout
1243 
1244         Session session = null;
1245         try {
1246             session = token.getOpSession();
1247             p11.C_Logout(session.id());
1248             if (debug != null) {
1249                 debug.println("logout succeeded");
1250             }
1251         } catch (PKCS11Exception pe) {
1252             if (pe.getErrorCode() == CKR_USER_NOT_LOGGED_IN) {
1253                 // let this one go
1254                 if (debug != null) {
1255                     debug.println("user not logged in");
1256                 }
1257                 return;
1258             }
1259             LoginException le = new LoginException();
1260             le.initCause(pe);
1261             throw le;
1262         } finally {
1263             token.releaseSession(session);
1264         }
1265     }
1266 
1267     /**
1268      * Set a <code>CallbackHandler</code>
1269      *
1270      * <p> The provider uses this handler if one is not passed to the
1271      * <code>login</code> method.  The provider also uses this handler
1272      * if it invokes <code>login</code> on behalf of callers.
1273      * In either case if a handler is not set via this method,
1274      * the provider queries the
1275      * <i>auth.login.defaultCallbackHandler</i> security property
1276      * for the fully qualified class name of a default handler implementation.
1277      * If the security property is not set,
1278      * the provider is assumed to have alternative means
1279      * for obtaining authentication information.
1280      *
1281      * @param handler a <code>CallbackHandler</code> for obtaining
1282      *          authentication information, which may be <code>null</code>
1283      *
1284      * @exception SecurityException if the caller does not pass a
1285      *  security check for
1286      *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
1287      *  where <i>name</i> is the value returned by
1288      *  this provider's <code>getName</code> method
1289      */
1290     public void setCallbackHandler(CallbackHandler handler) {
1291 
1292         // security check
1293 
1294         SecurityManager sm = System.getSecurityManager();
1295         if (sm != null) {
1296             sm.checkPermission
1297                 (new SecurityPermission("authProvider." + this.getName()));
1298         }
1299 
1300         synchronized (LOCK_HANDLER) {
1301             pHandler = handler;
1302         }
1303     }
1304 
1305     private CallbackHandler getCallbackHandler(CallbackHandler handler) {
1306 
1307         // get default handler if necessary
1308 
1309         if (handler != null) {
1310             return handler;
1311         }
1312 
1313         if (debug != null) {
1314             debug.println("getting provider callback handler");
1315         }
1316 
1317         synchronized (LOCK_HANDLER) {
1318             // see if handler was set via setCallbackHandler
1319             if (pHandler != null) {
1320                 return pHandler;
1321             }
1322 
1323             try {
1324                 if (debug != null) {
1325                     debug.println("getting default callback handler");
1326                 }
1327 
1328                 CallbackHandler myHandler = AccessController.doPrivileged
1329                     (new PrivilegedExceptionAction<CallbackHandler>() {
1330                     public CallbackHandler run() throws Exception {
1331 
1332                         String defaultHandler =
1333                                 java.security.Security.getProperty
1334                                 ("auth.login.defaultCallbackHandler");
1335 
1336                         if (defaultHandler == null ||
1337                             defaultHandler.length() == 0) {
1338 
1339                             // ok
1340                             if (debug != null) {
1341                                 debug.println("no default handler set");
1342                             }
1343                             return null;
1344                         }
1345 
1346                         Class c = Class.forName
1347                                 (defaultHandler,
1348                                 true,
1349                                 Thread.currentThread().getContextClassLoader());
1350                         return (CallbackHandler)c.newInstance();
1351                     }
1352                 });
1353 
1354                 // save it
1355                 pHandler = myHandler;
1356                 return myHandler;
1357 
1358             } catch (PrivilegedActionException pae) {
1359                 // ok
1360                 if (debug != null) {
1361                     debug.println("Unable to load default callback handler");
1362                     pae.printStackTrace();
1363                 }
1364             }
1365         }
1366         return null;
1367     }
1368 
1369     private Object writeReplace() throws ObjectStreamException {
1370         return new SunPKCS11Rep(this);
1371     }
1372 
1373     /**
1374      * Serialized representation of the SunPKCS11 provider.
1375      */
1376     private static class SunPKCS11Rep implements Serializable {
1377 
1378         static final long serialVersionUID = -2896606995897745419L;
1379 
1380         private final String providerName;
1381 
1382         private final String configName;
1383 
1384         SunPKCS11Rep(SunPKCS11 provider) throws NotSerializableException {
1385             providerName = provider.getName();
1386             configName = provider.configName;
1387             if (Security.getProvider(providerName) != provider) {
1388                 throw new NotSerializableException("Only SunPKCS11 providers "
1389                     + "installed in java.security.Security can be serialized");
1390             }
1391         }
1392 
1393         private Object readResolve() throws ObjectStreamException {
1394             SunPKCS11 p = (SunPKCS11)Security.getProvider(providerName);
1395             if ((p == null) || (p.configName.equals(configName) == false)) {
1396                 throw new NotSerializableException("Could not find "
1397                         + providerName + " in installed providers");
1398             }
1399             return p;
1400         }
1401     }
1402 }