Path: blob/master/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Secmod.java
41154 views
/*1* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.pkcs11;2627import java.io.*;28import java.util.*;2930import java.security.*;31import java.security.KeyStore.*;32import java.security.cert.X509Certificate;3334import sun.security.pkcs11.wrapper.*;35import static sun.security.pkcs11.wrapper.PKCS11Constants.*;363738/**39* The Secmod class defines the interface to the native NSS40* library and the configuration information it stores in its41* secmod.db file.42*43* <p>Example code:44* <pre>45* Secmod secmod = Secmod.getInstance();46* if (secmod.isInitialized() == false) {47* secmod.initialize("/home/myself/.mozilla");48* }49*50* Provider p = secmod.getModule(ModuleType.KEYSTORE).getProvider();51* KeyStore ks = KeyStore.getInstance("PKCS11", p);52* ks.load(null, password);53* </pre>54*55* @since 1.656* @author Andreas Sterbenz57*/58public final class Secmod {5960private static final boolean DEBUG = false;6162private static final Secmod INSTANCE;6364static {65sun.security.pkcs11.wrapper.PKCS11.loadNative();66INSTANCE = new Secmod();67}6869private static final String NSS_LIB_NAME = "nss3";7071private static final String SOFTTOKEN_LIB_NAME = "softokn3";7273private static final String TRUST_LIB_NAME = "nssckbi";7475// Slot IDs - defined in j2secmod.h on the native side76// Values obtained from NSS's pkcs11i.h header7778private final static int NETSCAPE_SLOT_ID = 0x1;7980private final static int PRIVATE_KEY_SLOT_ID = 0x2;8182private final static int FIPS_SLOT_ID = 0x3;8384// handle to be passed to the native code, 0 means not initialized85private long nssHandle;8687// whether this is a supported version of NSS88private boolean supported;8990// list of the modules91private List<Module> modules;9293private String configDir;9495private String nssLibDir;9697private Secmod() {98// empty99}100101/**102* Return the singleton Secmod instance.103*/104public static Secmod getInstance() {105return INSTANCE;106}107108private boolean isLoaded() {109if (nssHandle == 0) {110nssHandle = nssGetLibraryHandle(System.mapLibraryName(NSS_LIB_NAME));111if (nssHandle != 0) {112fetchVersions();113}114}115return (nssHandle != 0);116}117118private void fetchVersions() {119supported = nssVersionCheck(nssHandle, "3.7");120}121122/**123* Test whether this Secmod has been initialized. Returns true124* if NSS has been initialized using either the initialize() method125* or by directly calling the native NSS APIs. The latter may be126* the case if the current process contains components that use127* NSS directly.128*129* @throws IOException if an incompatible version of NSS130* has been loaded131*/132public synchronized boolean isInitialized() throws IOException {133// NSS does not allow us to check if it is initialized already134// assume that if it is loaded it is also initialized135if (isLoaded() == false) {136return false;137}138if (supported == false) {139throw new IOException140("An incompatible version of NSS is already loaded, "141+ "3.7 or later required");142}143return true;144}145146String getConfigDir() {147return configDir;148}149150String getLibDir() {151return nssLibDir;152}153154/**155* Initialize this Secmod.156*157* @param configDir the directory containing the NSS configuration158* files such as secmod.db159* @param nssLibDir the directory containing the NSS libraries160* (libnss3.so or nss3.dll) or null if the library is on161* the system default shared library path162*163* @throws IOException if NSS has already been initialized,164* the specified directories are invalid, or initialization165* fails for any other reason166*/167public void initialize(String configDir, String nssLibDir)168throws IOException {169initialize(DbMode.READ_WRITE, configDir, nssLibDir, false);170}171172public void initialize(DbMode dbMode, String configDir, String nssLibDir)173throws IOException {174initialize(dbMode, configDir, nssLibDir, false);175}176177public synchronized void initialize(DbMode dbMode, String configDir,178String nssLibDir, boolean nssOptimizeSpace) throws IOException {179180if (isInitialized()) {181throw new IOException("NSS is already initialized");182}183184if (dbMode == null) {185throw new NullPointerException();186}187if ((dbMode != DbMode.NO_DB) && (configDir == null)) {188throw new NullPointerException();189}190String platformLibName = System.mapLibraryName("nss3");191String platformPath;192if (nssLibDir == null) {193platformPath = platformLibName;194} else {195File base = new File(nssLibDir);196if (base.isDirectory() == false) {197throw new IOException("nssLibDir must be a directory:" + nssLibDir);198}199File platformFile = new File(base, platformLibName);200if (platformFile.isFile() == false) {201throw new FileNotFoundException(platformFile.getPath());202}203platformPath = platformFile.getPath();204}205206if (configDir != null) {207String configDirPath = null;208String sqlPrefix = "sql:";209if (!configDir.startsWith(sqlPrefix)) {210configDirPath = configDir;211} else {212StringBuilder configDirPathSB = new StringBuilder(configDir);213configDirPath = configDirPathSB.substring(sqlPrefix.length());214}215File configBase = new File(configDirPath);216if (configBase.isDirectory() == false ) {217throw new IOException("configDir must be a directory: " + configDirPath);218}219if (!configDir.startsWith(sqlPrefix)) {220File secmodFile = new File(configBase, "secmod.db");221if (secmodFile.isFile() == false) {222throw new FileNotFoundException(secmodFile.getPath());223}224}225}226227if (DEBUG) System.out.println("lib: " + platformPath);228nssHandle = nssLoadLibrary(platformPath);229if (DEBUG) System.out.println("handle: " + nssHandle);230fetchVersions();231if (supported == false) {232throw new IOException233("The specified version of NSS is incompatible, "234+ "3.7 or later required");235}236237if (DEBUG) System.out.println("dir: " + configDir);238boolean initok = nssInitialize(dbMode.functionName, nssHandle,239configDir, nssOptimizeSpace);240if (DEBUG) System.out.println("init: " + initok);241if (initok == false) {242throw new IOException("NSS initialization failed");243}244245this.configDir = configDir;246this.nssLibDir = nssLibDir;247}248249/**250* Return an immutable list of all available modules.251*252* @throws IllegalStateException if this Secmod is misconfigured253* or not initialized254*/255public synchronized List<Module> getModules() {256try {257if (isInitialized() == false) {258throw new IllegalStateException("NSS not initialized");259}260} catch (IOException e) {261// IOException if misconfigured262throw new IllegalStateException(e);263}264if (modules == null) {265@SuppressWarnings("unchecked")266List<Module> modules = (List<Module>)nssGetModuleList(nssHandle,267nssLibDir);268this.modules = Collections.unmodifiableList(modules);269}270return modules;271}272273private static byte[] getDigest(X509Certificate cert, String algorithm) {274try {275MessageDigest md = MessageDigest.getInstance(algorithm);276return md.digest(cert.getEncoded());277} catch (GeneralSecurityException e) {278throw new ProviderException(e);279}280}281282boolean isTrusted(X509Certificate cert, TrustType trustType) {283Bytes bytes = new Bytes(getDigest(cert, "SHA-1"));284TrustAttributes attr = getModuleTrust(ModuleType.KEYSTORE, bytes);285if (attr == null) {286attr = getModuleTrust(ModuleType.FIPS, bytes);287if (attr == null) {288attr = getModuleTrust(ModuleType.TRUSTANCHOR, bytes);289}290}291return (attr == null) ? false : attr.isTrusted(trustType);292}293294private TrustAttributes getModuleTrust(ModuleType type, Bytes bytes) {295Module module = getModule(type);296TrustAttributes t = (module == null) ? null : module.getTrust(bytes);297return t;298}299300/**301* Constants describing the different types of NSS modules.302* For this API, NSS modules are classified as either one303* of the internal modules delivered as part of NSS or304* as an external module provided by a 3rd party.305*/306public static enum ModuleType {307/**308* The NSS Softtoken crypto module. This is the first309* slot of the softtoken object.310* This module provides311* implementations for cryptographic algorithms but no KeyStore.312*/313CRYPTO,314/**315* The NSS Softtoken KeyStore module. This is the second316* slot of the softtoken object.317* This module provides318* implementations for cryptographic algorithms (after login)319* and the KeyStore.320*/321KEYSTORE,322/**323* The NSS Softtoken module in FIPS mode. Note that in FIPS mode the324* softtoken presents only one slot, not separate CRYPTO and KEYSTORE325* slots as in non-FIPS mode.326*/327FIPS,328/**329* The NSS builtin trust anchor module. This is the330* NSSCKBI object. It provides no crypto functions.331*/332TRUSTANCHOR,333/**334* An external module.335*/336EXTERNAL,337}338339/**340* Returns the first module of the specified type. If no such341* module exists, this method returns null.342*343* @throws IllegalStateException if this Secmod is misconfigured344* or not initialized345*/346public Module getModule(ModuleType type) {347for (Module module : getModules()) {348if (module.getType() == type) {349return module;350}351}352return null;353}354355static final String TEMPLATE_EXTERNAL =356"library = %s\n"357+ "name = \"%s\"\n"358+ "slotListIndex = %d\n";359360static final String TEMPLATE_TRUSTANCHOR =361"library = %s\n"362+ "name = \"NSS Trust Anchors\"\n"363+ "slotListIndex = 0\n"364+ "enabledMechanisms = { KeyStore }\n"365+ "nssUseSecmodTrust = true\n";366367static final String TEMPLATE_CRYPTO =368"library = %s\n"369+ "name = \"NSS SoftToken Crypto\"\n"370+ "slotListIndex = 0\n"371+ "disabledMechanisms = { KeyStore }\n";372373static final String TEMPLATE_KEYSTORE =374"library = %s\n"375+ "name = \"NSS SoftToken KeyStore\"\n"376+ "slotListIndex = 1\n"377+ "nssUseSecmodTrust = true\n";378379static final String TEMPLATE_FIPS =380"library = %s\n"381+ "name = \"NSS FIPS SoftToken\"\n"382+ "slotListIndex = 0\n"383+ "nssUseSecmodTrust = true\n";384385/**386* A representation of one PKCS#11 slot in a PKCS#11 module.387*/388public static final class Module {389// path of the native library390final String libraryName;391// descriptive name used by NSS392final String commonName;393final int slot;394final ModuleType type;395396private String config;397private SunPKCS11 provider;398399// trust attributes. Used for the KEYSTORE and TRUSTANCHOR modules only400private Map<Bytes,TrustAttributes> trust;401402Module(String libraryDir, String libraryName, String commonName,403int slotIndex, int slotId) {404ModuleType type;405406if ((libraryName == null) || (libraryName.length() == 0)) {407// must be softtoken408libraryName = System.mapLibraryName(SOFTTOKEN_LIB_NAME);409if (slotId == NETSCAPE_SLOT_ID) {410type = ModuleType.CRYPTO;411} else if (slotId == PRIVATE_KEY_SLOT_ID) {412type = ModuleType.KEYSTORE;413} else if (slotId == FIPS_SLOT_ID) {414type = ModuleType.FIPS;415} else {416throw new RuntimeException("Unexpected slot ID " + slotId +417" in the NSS Internal Module");418}419} else {420if (libraryName.endsWith(System.mapLibraryName(TRUST_LIB_NAME))421|| commonName.equals("Builtin Roots Module")) {422type = ModuleType.TRUSTANCHOR;423} else {424type = ModuleType.EXTERNAL;425}426}427// On Ubuntu the libsoftokn3 library is located in a subdirectory428// of the system libraries directory. (Since Ubuntu 11.04.)429File libraryFile = new File(libraryDir, libraryName);430if (!libraryFile.isFile()) {431File failover = new File(libraryDir, "nss/" + libraryName);432if (failover.isFile()) {433libraryFile = failover;434}435}436this.libraryName = libraryFile.getPath();437this.commonName = commonName;438this.slot = slotIndex;439this.type = type;440initConfiguration();441}442443private void initConfiguration() {444switch (type) {445case EXTERNAL:446config = String.format(TEMPLATE_EXTERNAL, libraryName,447commonName + " " + slot, slot);448break;449case CRYPTO:450config = String.format(TEMPLATE_CRYPTO, libraryName);451break;452case KEYSTORE:453config = String.format(TEMPLATE_KEYSTORE, libraryName);454break;455case FIPS:456config = String.format(TEMPLATE_FIPS, libraryName);457break;458case TRUSTANCHOR:459config = String.format(TEMPLATE_TRUSTANCHOR, libraryName);460break;461default:462throw new RuntimeException("Unknown module type: " + type);463}464}465466/**467* Get the configuration for this module. This is a string468* in the SunPKCS11 configuration format. It can be469* customized with additional options and then made470* current using the setConfiguration() method.471*/472@Deprecated473public synchronized String getConfiguration() {474return config;475}476477/**478* Set the configuration for this module.479*480* @throws IllegalStateException if the associated provider481* instance has already been created.482*/483@Deprecated484public synchronized void setConfiguration(String config) {485if (provider != null) {486throw new IllegalStateException("Provider instance already created");487}488this.config = config;489}490491/**492* Return the pathname of the native library that implements493* this module. For example, /usr/lib/libpkcs11.so.494*/495public String getLibraryName() {496return libraryName;497}498499/**500* Returns the type of this module.501*/502public ModuleType getType() {503return type;504}505506/**507* Returns the provider instance that is associated with this508* module. The first call to this method creates the provider509* instance.510*/511@Deprecated512public synchronized Provider getProvider() {513if (provider == null) {514provider = newProvider();515}516return provider;517}518519synchronized boolean hasInitializedProvider() {520return provider != null;521}522523void setProvider(SunPKCS11 p) {524if (provider != null) {525throw new ProviderException("Secmod provider already initialized");526}527provider = p;528}529530private SunPKCS11 newProvider() {531try {532return new SunPKCS11(new Config("--" + config));533} catch (Exception e) {534// XXX535throw new ProviderException(e);536}537}538539synchronized void setTrust(Token token, X509Certificate cert) {540Bytes bytes = new Bytes(getDigest(cert, "SHA-1"));541TrustAttributes attr = getTrust(bytes);542if (attr == null) {543attr = new TrustAttributes(token, cert, bytes, CKT_NETSCAPE_TRUSTED_DELEGATOR);544trust.put(bytes, attr);545} else {546// does it already have the correct trust settings?547if (attr.isTrusted(TrustType.ALL) == false) {548// XXX not yet implemented549throw new ProviderException("Cannot change existing trust attributes");550}551}552}553554TrustAttributes getTrust(Bytes hash) {555if (trust == null) {556// If provider is not set, create a temporary provider to557// retrieve the trust information. This can happen if we need558// to get the trust information for the trustanchor module559// because we need to look for user customized settings in the560// keystore module (which may not have a provider created yet).561// Creating a temporary provider and then dropping it on the562// floor immediately is flawed, but it's the best we can do563// for now.564synchronized (this) {565SunPKCS11 p = provider;566if (p == null) {567p = newProvider();568}569try {570trust = Secmod.getTrust(p);571} catch (PKCS11Exception e) {572throw new RuntimeException(e);573}574}575}576return trust.get(hash);577}578579public String toString() {580return581commonName + " (" + type + ", " + libraryName + ", slot " + slot + ")";582}583584}585586/**587* Constants representing NSS trust categories.588*/589public static enum TrustType {590/** Trusted for all purposes */591ALL,592/** Trusted for SSL client authentication */593CLIENT_AUTH,594/** Trusted for SSL server authentication */595SERVER_AUTH,596/** Trusted for code signing */597CODE_SIGNING,598/** Trusted for email protection */599EMAIL_PROTECTION,600}601602public static enum DbMode {603READ_WRITE("NSS_InitReadWrite"),604READ_ONLY ("NSS_Init"),605NO_DB ("NSS_NoDB_Init");606607final String functionName;608DbMode(String functionName) {609this.functionName = functionName;610}611}612613/**614* A LoadStoreParameter for use with the NSS Softtoken or615* NSS TrustAnchor KeyStores.616* <p>617* It allows the set of trusted certificates that are returned by618* the KeyStore to be specified.619*/620public static final class KeyStoreLoadParameter implements LoadStoreParameter {621final TrustType trustType;622final ProtectionParameter protection;623public KeyStoreLoadParameter(TrustType trustType, char[] password) {624this(trustType, new PasswordProtection(password));625626}627public KeyStoreLoadParameter(TrustType trustType, ProtectionParameter prot) {628if (trustType == null) {629throw new NullPointerException("trustType must not be null");630}631this.trustType = trustType;632this.protection = prot;633}634public ProtectionParameter getProtectionParameter() {635return protection;636}637public TrustType getTrustType() {638return trustType;639}640}641642static class TrustAttributes {643final long handle;644final long clientAuth, serverAuth, codeSigning, emailProtection;645final byte[] shaHash;646TrustAttributes(Token token, X509Certificate cert, Bytes bytes, long trustValue) {647Session session = null;648try {649session = token.getOpSession();650// XXX use KeyStore TrustType settings to determine which651// attributes to set652CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {653new CK_ATTRIBUTE(CKA_TOKEN, true),654new CK_ATTRIBUTE(CKA_CLASS, CKO_NETSCAPE_TRUST),655new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_SERVER_AUTH, trustValue),656new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CODE_SIGNING, trustValue),657new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_EMAIL_PROTECTION, trustValue),658new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CLIENT_AUTH, trustValue),659new CK_ATTRIBUTE(CKA_NETSCAPE_CERT_SHA1_HASH, bytes.b),660new CK_ATTRIBUTE(CKA_NETSCAPE_CERT_MD5_HASH, getDigest(cert, "MD5")),661new CK_ATTRIBUTE(CKA_ISSUER, cert.getIssuerX500Principal().getEncoded()),662new CK_ATTRIBUTE(CKA_SERIAL_NUMBER, cert.getSerialNumber().toByteArray()),663// XXX per PKCS#11 spec, the serial number should be in ASN.1664};665handle = token.p11.C_CreateObject(session.id(), attrs);666shaHash = bytes.b;667clientAuth = trustValue;668serverAuth = trustValue;669codeSigning = trustValue;670emailProtection = trustValue;671} catch (PKCS11Exception e) {672throw new ProviderException("Could not create trust object", e);673} finally {674token.releaseSession(session);675}676}677TrustAttributes(Token token, Session session, long handle)678throws PKCS11Exception {679this.handle = handle;680CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {681new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_SERVER_AUTH),682new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CODE_SIGNING),683new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_EMAIL_PROTECTION),684new CK_ATTRIBUTE(CKA_NETSCAPE_CERT_SHA1_HASH),685};686687token.p11.C_GetAttributeValue(session.id(), handle, attrs);688serverAuth = attrs[0].getLong();689codeSigning = attrs[1].getLong();690emailProtection = attrs[2].getLong();691shaHash = attrs[3].getByteArray();692693attrs = new CK_ATTRIBUTE[] {694new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CLIENT_AUTH),695};696long c;697try {698token.p11.C_GetAttributeValue(session.id(), handle, attrs);699c = attrs[0].getLong();700} catch (PKCS11Exception e) {701// trust anchor module does not support this attribute702c = serverAuth;703}704clientAuth = c;705}706Bytes getHash() {707return new Bytes(shaHash);708}709boolean isTrusted(TrustType type) {710switch (type) {711case CLIENT_AUTH:712return isTrusted(clientAuth);713case SERVER_AUTH:714return isTrusted(serverAuth);715case CODE_SIGNING:716return isTrusted(codeSigning);717case EMAIL_PROTECTION:718return isTrusted(emailProtection);719case ALL:720return isTrusted(TrustType.CLIENT_AUTH)721&& isTrusted(TrustType.SERVER_AUTH)722&& isTrusted(TrustType.CODE_SIGNING)723&& isTrusted(TrustType.EMAIL_PROTECTION);724default:725return false;726}727}728729private boolean isTrusted(long l) {730// XXX CKT_TRUSTED?731return (l == CKT_NETSCAPE_TRUSTED_DELEGATOR);732}733734}735736private static class Bytes {737final byte[] b;738Bytes(byte[] b) {739this.b = b;740}741public int hashCode() {742return Arrays.hashCode(b);743}744public boolean equals(Object o) {745if (this == o) {746return true;747}748if (o instanceof Bytes == false) {749return false;750}751Bytes other = (Bytes)o;752return Arrays.equals(this.b, other.b);753}754}755756private static Map<Bytes,TrustAttributes> getTrust(SunPKCS11 provider)757throws PKCS11Exception {758Map<Bytes,TrustAttributes> trustMap = new HashMap<Bytes,TrustAttributes>();759Token token = provider.getToken();760Session session = null;761boolean exceptionOccurred = true;762try {763session = token.getOpSession();764int MAX_NUM = 8192;765CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {766new CK_ATTRIBUTE(CKA_CLASS, CKO_NETSCAPE_TRUST),767};768token.p11.C_FindObjectsInit(session.id(), attrs);769long[] handles = token.p11.C_FindObjects(session.id(), MAX_NUM);770token.p11.C_FindObjectsFinal(session.id());771if (DEBUG) System.out.println("handles: " + handles.length);772773for (long handle : handles) {774try {775TrustAttributes trust = new TrustAttributes(token, session, handle);776trustMap.put(trust.getHash(), trust);777} catch (PKCS11Exception e) {778// skip put on pkcs11 error779}780}781exceptionOccurred = false;782} finally {783if (exceptionOccurred) {784token.killSession(session);785} else {786token.releaseSession(session);787}788}789return trustMap;790}791792private static native long nssGetLibraryHandle(String libraryName);793794private static native long nssLoadLibrary(String name) throws IOException;795796private static native boolean nssVersionCheck(long handle, String minVersion);797798private static native boolean nssInitialize(String functionName, long handle, String configDir, boolean nssOptimizeSpace);799800private static native Object nssGetModuleList(long handle, String libDir);801802}803804805