Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/pkcs11/Secmod.java
38919 views
/*1* Copyright (c) 2005, 2013, 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", "/usr/sfw/lib/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 final static boolean DEBUG = false;6162private final static Secmod INSTANCE;6364static {65sun.security.pkcs11.wrapper.PKCS11.loadNative();66INSTANCE = new Secmod();67}6869private final static String NSS_LIB_NAME = "nss3";7071private final static String SOFTTOKEN_LIB_NAME = "softokn3";7273private final static String TRUST_LIB_NAME = "nssckbi";7475// handle to be passed to the native code, 0 means not initialized76private long nssHandle;7778// whether this is a supported version of NSS79private boolean supported;8081// list of the modules82private List<Module> modules;8384private String configDir;8586private String nssLibDir;8788private Secmod() {89// empty90}9192/**93* Return the singleton Secmod instance.94*/95public static Secmod getInstance() {96return INSTANCE;97}9899private boolean isLoaded() {100if (nssHandle == 0) {101nssHandle = nssGetLibraryHandle(System.mapLibraryName(NSS_LIB_NAME));102if (nssHandle != 0) {103fetchVersions();104}105}106return (nssHandle != 0);107}108109private void fetchVersions() {110supported = nssVersionCheck(nssHandle, "3.7");111}112113/**114* Test whether this Secmod has been initialized. Returns true115* if NSS has been initialized using either the initialize() method116* or by directly calling the native NSS APIs. The latter may be117* the case if the current process contains components that use118* NSS directly.119*120* @throws IOException if an incompatible version of NSS121* has been loaded122*/123public synchronized boolean isInitialized() throws IOException {124// NSS does not allow us to check if it is initialized already125// assume that if it is loaded it is also initialized126if (isLoaded() == false) {127return false;128}129if (supported == false) {130throw new IOException131("An incompatible version of NSS is already loaded, "132+ "3.7 or later required");133}134return true;135}136137String getConfigDir() {138return configDir;139}140141String getLibDir() {142return nssLibDir;143}144145/**146* Initialize this Secmod.147*148* @param configDir the directory containing the NSS configuration149* files such as secmod.db150* @param nssLibDir the directory containing the NSS libraries151* (libnss3.so or nss3.dll) or null if the library is on152* the system default shared library path153*154* @throws IOException if NSS has already been initialized,155* the specified directories are invalid, or initialization156* fails for any other reason157*/158public void initialize(String configDir, String nssLibDir)159throws IOException {160initialize(DbMode.READ_WRITE, configDir, nssLibDir, false);161}162163public void initialize(DbMode dbMode, String configDir, String nssLibDir)164throws IOException {165initialize(dbMode, configDir, nssLibDir, false);166}167168public synchronized void initialize(DbMode dbMode, String configDir,169String nssLibDir, boolean nssOptimizeSpace) throws IOException {170171if (isInitialized()) {172throw new IOException("NSS is already initialized");173}174175if (dbMode == null) {176throw new NullPointerException();177}178if ((dbMode != DbMode.NO_DB) && (configDir == null)) {179throw new NullPointerException();180}181String platformLibName = System.mapLibraryName("nss3");182String platformPath;183if (nssLibDir == null) {184platformPath = platformLibName;185} else {186File base = new File(nssLibDir);187if (base.isDirectory() == false) {188throw new IOException("nssLibDir must be a directory:" + nssLibDir);189}190File platformFile = new File(base, platformLibName);191if (platformFile.isFile() == false) {192throw new FileNotFoundException(platformFile.getPath());193}194platformPath = platformFile.getPath();195}196197if (configDir != null) {198String configDirPath = null;199String sqlPrefix = "sql:/";200if (!configDir.startsWith(sqlPrefix)) {201configDirPath = configDir;202} else {203StringBuilder configDirPathSB = new StringBuilder(configDir);204configDirPath = configDirPathSB.substring(sqlPrefix.length());205}206File configBase = new File(configDirPath);207if (configBase.isDirectory() == false ) {208throw new IOException("configDir must be a directory: " + configDirPath);209}210if (!configDir.startsWith(sqlPrefix)) {211File secmodFile = new File(configBase, "secmod.db");212if (secmodFile.isFile() == false) {213throw new FileNotFoundException(secmodFile.getPath());214}215}216}217218if (DEBUG) System.out.println("lib: " + platformPath);219nssHandle = nssLoadLibrary(platformPath);220if (DEBUG) System.out.println("handle: " + nssHandle);221fetchVersions();222if (supported == false) {223throw new IOException224("The specified version of NSS is incompatible, "225+ "3.7 or later required");226}227228if (DEBUG) System.out.println("dir: " + configDir);229boolean initok = nssInitialize(dbMode.functionName, nssHandle,230configDir, nssOptimizeSpace);231if (DEBUG) System.out.println("init: " + initok);232if (initok == false) {233throw new IOException("NSS initialization failed");234}235236this.configDir = configDir;237this.nssLibDir = nssLibDir;238}239240/**241* Return an immutable list of all available modules.242*243* @throws IllegalStateException if this Secmod is misconfigured244* or not initialized245*/246public synchronized List<Module> getModules() {247try {248if (isInitialized() == false) {249throw new IllegalStateException("NSS not initialized");250}251} catch (IOException e) {252// IOException if misconfigured253throw new IllegalStateException(e);254}255if (modules == null) {256@SuppressWarnings("unchecked")257List<Module> modules = (List<Module>)nssGetModuleList(nssHandle,258nssLibDir);259this.modules = Collections.unmodifiableList(modules);260}261return modules;262}263264private static byte[] getDigest(X509Certificate cert, String algorithm) {265try {266MessageDigest md = MessageDigest.getInstance(algorithm);267return md.digest(cert.getEncoded());268} catch (GeneralSecurityException e) {269throw new ProviderException(e);270}271}272273boolean isTrusted(X509Certificate cert, TrustType trustType) {274Bytes bytes = new Bytes(getDigest(cert, "SHA-1"));275TrustAttributes attr = getModuleTrust(ModuleType.KEYSTORE, bytes);276if (attr == null) {277attr = getModuleTrust(ModuleType.FIPS, bytes);278if (attr == null) {279attr = getModuleTrust(ModuleType.TRUSTANCHOR, bytes);280}281}282return (attr == null) ? false : attr.isTrusted(trustType);283}284285private TrustAttributes getModuleTrust(ModuleType type, Bytes bytes) {286Module module = getModule(type);287TrustAttributes t = (module == null) ? null : module.getTrust(bytes);288return t;289}290291/**292* Constants describing the different types of NSS modules.293* For this API, NSS modules are classified as either one294* of the internal modules delivered as part of NSS or295* as an external module provided by a 3rd party.296*/297public static enum ModuleType {298/**299* The NSS Softtoken crypto module. This is the first300* slot of the softtoken object.301* This module provides302* implementations for cryptographic algorithms but no KeyStore.303*/304CRYPTO,305/**306* The NSS Softtoken KeyStore module. This is the second307* slot of the softtoken object.308* This module provides309* implementations for cryptographic algorithms (after login)310* and the KeyStore.311*/312KEYSTORE,313/**314* The NSS Softtoken module in FIPS mode. Note that in FIPS mode the315* softtoken presents only one slot, not separate CRYPTO and KEYSTORE316* slots as in non-FIPS mode.317*/318FIPS,319/**320* The NSS builtin trust anchor module. This is the321* NSSCKBI object. It provides no crypto functions.322*/323TRUSTANCHOR,324/**325* An external module.326*/327EXTERNAL,328}329330/**331* Returns the first module of the specified type. If no such332* module exists, this method returns null.333*334* @throws IllegalStateException if this Secmod is misconfigured335* or not initialized336*/337public Module getModule(ModuleType type) {338for (Module module : getModules()) {339if (module.getType() == type) {340return module;341}342}343return null;344}345346static final String TEMPLATE_EXTERNAL =347"library = %s\n"348+ "name = \"%s\"\n"349+ "slotListIndex = %d\n";350351static final String TEMPLATE_TRUSTANCHOR =352"library = %s\n"353+ "name = \"NSS Trust Anchors\"\n"354+ "slotListIndex = 0\n"355+ "enabledMechanisms = { KeyStore }\n"356+ "nssUseSecmodTrust = true\n";357358static final String TEMPLATE_CRYPTO =359"library = %s\n"360+ "name = \"NSS SoftToken Crypto\"\n"361+ "slotListIndex = 0\n"362+ "disabledMechanisms = { KeyStore }\n";363364static final String TEMPLATE_KEYSTORE =365"library = %s\n"366+ "name = \"NSS SoftToken KeyStore\"\n"367+ "slotListIndex = 1\n"368+ "nssUseSecmodTrust = true\n";369370static final String TEMPLATE_FIPS =371"library = %s\n"372+ "name = \"NSS FIPS SoftToken\"\n"373+ "slotListIndex = 0\n"374+ "nssUseSecmodTrust = true\n";375376/**377* A representation of one PKCS#11 slot in a PKCS#11 module.378*/379public static final class Module {380// path of the native library381final String libraryName;382// descriptive name used by NSS383final String commonName;384final int slot;385final ModuleType type;386387private String config;388private SunPKCS11 provider;389390// trust attributes. Used for the KEYSTORE and TRUSTANCHOR modules only391private Map<Bytes,TrustAttributes> trust;392393Module(String libraryDir, String libraryName, String commonName,394boolean fips, int slot) {395ModuleType type;396397if ((libraryName == null) || (libraryName.length() == 0)) {398// must be softtoken399libraryName = System.mapLibraryName(SOFTTOKEN_LIB_NAME);400if (fips == false) {401type = (slot == 0) ? ModuleType.CRYPTO : ModuleType.KEYSTORE;402} else {403type = ModuleType.FIPS;404if (slot != 0) {405throw new RuntimeException406("Slot index should be 0 for FIPS slot");407}408}409} else {410if (libraryName.endsWith(System.mapLibraryName(TRUST_LIB_NAME))411|| commonName.equals("Builtin Roots Module")) {412type = ModuleType.TRUSTANCHOR;413} else {414type = ModuleType.EXTERNAL;415}416}417// On Ubuntu the libsoftokn3 library is located in a subdirectory418// of the system libraries directory. (Since Ubuntu 11.04.)419File libraryFile = new File(libraryDir, libraryName);420if (!libraryFile.isFile()) {421File failover = new File(libraryDir, "nss/" + libraryName);422if (failover.isFile()) {423libraryFile = failover;424}425}426this.libraryName = libraryFile.getPath();427this.commonName = commonName;428this.slot = slot;429this.type = type;430initConfiguration();431}432433private void initConfiguration() {434switch (type) {435case EXTERNAL:436config = String.format(TEMPLATE_EXTERNAL, libraryName,437commonName + " " + slot, slot);438break;439case CRYPTO:440config = String.format(TEMPLATE_CRYPTO, libraryName);441break;442case KEYSTORE:443config = String.format(TEMPLATE_KEYSTORE, libraryName);444break;445case FIPS:446config = String.format(TEMPLATE_FIPS, libraryName);447break;448case TRUSTANCHOR:449config = String.format(TEMPLATE_TRUSTANCHOR, libraryName);450break;451default:452throw new RuntimeException("Unknown module type: " + type);453}454}455456/**457* Get the configuration for this module. This is a string458* in the SunPKCS11 configuration format. It can be459* customized with additional options and then made460* current using the setConfiguration() method.461*/462@Deprecated463public synchronized String getConfiguration() {464return config;465}466467/**468* Set the configuration for this module.469*470* @throws IllegalStateException if the associated provider471* instance has already been created.472*/473@Deprecated474public synchronized void setConfiguration(String config) {475if (provider != null) {476throw new IllegalStateException("Provider instance already created");477}478this.config = config;479}480481/**482* Return the pathname of the native library that implements483* this module. For example, /usr/lib/libpkcs11.so.484*/485public String getLibraryName() {486return libraryName;487}488489/**490* Returns the type of this module.491*/492public ModuleType getType() {493return type;494}495496/**497* Returns the provider instance that is associated with this498* module. The first call to this method creates the provider499* instance.500*/501@Deprecated502public synchronized Provider getProvider() {503if (provider == null) {504provider = newProvider();505}506return provider;507}508509synchronized boolean hasInitializedProvider() {510return provider != null;511}512513void setProvider(SunPKCS11 p) {514if (provider != null) {515throw new ProviderException("Secmod provider already initialized");516}517provider = p;518}519520private SunPKCS11 newProvider() {521try {522InputStream in = new ByteArrayInputStream(config.getBytes("UTF8"));523return new SunPKCS11(in);524} catch (Exception e) {525// XXX526throw new ProviderException(e);527}528}529530synchronized void setTrust(Token token, X509Certificate cert) {531Bytes bytes = new Bytes(getDigest(cert, "SHA-1"));532TrustAttributes attr = getTrust(bytes);533if (attr == null) {534attr = new TrustAttributes(token, cert, bytes, CKT_NETSCAPE_TRUSTED_DELEGATOR);535trust.put(bytes, attr);536} else {537// does it already have the correct trust settings?538if (attr.isTrusted(TrustType.ALL) == false) {539// XXX not yet implemented540throw new ProviderException("Cannot change existing trust attributes");541}542}543}544545TrustAttributes getTrust(Bytes hash) {546if (trust == null) {547// If provider is not set, create a temporary provider to548// retrieve the trust information. This can happen if we need549// to get the trust information for the trustanchor module550// because we need to look for user customized settings in the551// keystore module (which may not have a provider created yet).552// Creating a temporary provider and then dropping it on the553// floor immediately is flawed, but it's the best we can do554// for now.555synchronized (this) {556SunPKCS11 p = provider;557if (p == null) {558p = newProvider();559}560try {561trust = Secmod.getTrust(p);562} catch (PKCS11Exception e) {563throw new RuntimeException(e);564}565}566}567return trust.get(hash);568}569570public String toString() {571return572commonName + " (" + type + ", " + libraryName + ", slot " + slot + ")";573}574575}576577/**578* Constants representing NSS trust categories.579*/580public static enum TrustType {581/** Trusted for all purposes */582ALL,583/** Trusted for SSL client authentication */584CLIENT_AUTH,585/** Trusted for SSL server authentication */586SERVER_AUTH,587/** Trusted for code signing */588CODE_SIGNING,589/** Trusted for email protection */590EMAIL_PROTECTION,591}592593public static enum DbMode {594READ_WRITE("NSS_InitReadWrite"),595READ_ONLY ("NSS_Init"),596NO_DB ("NSS_NoDB_Init");597598final String functionName;599DbMode(String functionName) {600this.functionName = functionName;601}602}603604/**605* A LoadStoreParameter for use with the NSS Softtoken or606* NSS TrustAnchor KeyStores.607* <p>608* It allows the set of trusted certificates that are returned by609* the KeyStore to be specified.610*/611public static final class KeyStoreLoadParameter implements LoadStoreParameter {612final TrustType trustType;613final ProtectionParameter protection;614public KeyStoreLoadParameter(TrustType trustType, char[] password) {615this(trustType, new PasswordProtection(password));616617}618public KeyStoreLoadParameter(TrustType trustType, ProtectionParameter prot) {619if (trustType == null) {620throw new NullPointerException("trustType must not be null");621}622this.trustType = trustType;623this.protection = prot;624}625public ProtectionParameter getProtectionParameter() {626return protection;627}628public TrustType getTrustType() {629return trustType;630}631}632633static class TrustAttributes {634final long handle;635final long clientAuth, serverAuth, codeSigning, emailProtection;636final byte[] shaHash;637TrustAttributes(Token token, X509Certificate cert, Bytes bytes, long trustValue) {638Session session = null;639try {640session = token.getOpSession();641// XXX use KeyStore TrustType settings to determine which642// attributes to set643CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {644new CK_ATTRIBUTE(CKA_TOKEN, true),645new CK_ATTRIBUTE(CKA_CLASS, CKO_NETSCAPE_TRUST),646new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_SERVER_AUTH, trustValue),647new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CODE_SIGNING, trustValue),648new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_EMAIL_PROTECTION, trustValue),649new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CLIENT_AUTH, trustValue),650new CK_ATTRIBUTE(CKA_NETSCAPE_CERT_SHA1_HASH, bytes.b),651new CK_ATTRIBUTE(CKA_NETSCAPE_CERT_MD5_HASH, getDigest(cert, "MD5")),652new CK_ATTRIBUTE(CKA_ISSUER, cert.getIssuerX500Principal().getEncoded()),653new CK_ATTRIBUTE(CKA_SERIAL_NUMBER, cert.getSerialNumber().toByteArray()),654// XXX per PKCS#11 spec, the serial number should be in ASN.1655};656handle = token.p11.C_CreateObject(session.id(), attrs);657shaHash = bytes.b;658clientAuth = trustValue;659serverAuth = trustValue;660codeSigning = trustValue;661emailProtection = trustValue;662} catch (PKCS11Exception e) {663throw new ProviderException("Could not create trust object", e);664} finally {665token.releaseSession(session);666}667}668TrustAttributes(Token token, Session session, long handle)669throws PKCS11Exception {670this.handle = handle;671CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {672new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_SERVER_AUTH),673new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CODE_SIGNING),674new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_EMAIL_PROTECTION),675new CK_ATTRIBUTE(CKA_NETSCAPE_CERT_SHA1_HASH),676};677678token.p11.C_GetAttributeValue(session.id(), handle, attrs);679serverAuth = attrs[0].getLong();680codeSigning = attrs[1].getLong();681emailProtection = attrs[2].getLong();682shaHash = attrs[3].getByteArray();683684attrs = new CK_ATTRIBUTE[] {685new CK_ATTRIBUTE(CKA_NETSCAPE_TRUST_CLIENT_AUTH),686};687long c;688try {689token.p11.C_GetAttributeValue(session.id(), handle, attrs);690c = attrs[0].getLong();691} catch (PKCS11Exception e) {692// trust anchor module does not support this attribute693c = serverAuth;694}695clientAuth = c;696}697Bytes getHash() {698return new Bytes(shaHash);699}700boolean isTrusted(TrustType type) {701switch (type) {702case CLIENT_AUTH:703return isTrusted(clientAuth);704case SERVER_AUTH:705return isTrusted(serverAuth);706case CODE_SIGNING:707return isTrusted(codeSigning);708case EMAIL_PROTECTION:709return isTrusted(emailProtection);710case ALL:711return isTrusted(TrustType.CLIENT_AUTH)712&& isTrusted(TrustType.SERVER_AUTH)713&& isTrusted(TrustType.CODE_SIGNING)714&& isTrusted(TrustType.EMAIL_PROTECTION);715default:716return false;717}718}719720private boolean isTrusted(long l) {721// XXX CKT_TRUSTED?722return (l == CKT_NETSCAPE_TRUSTED_DELEGATOR);723}724725}726727private static class Bytes {728final byte[] b;729Bytes(byte[] b) {730this.b = b;731}732public int hashCode() {733return Arrays.hashCode(b);734}735public boolean equals(Object o) {736if (this == o) {737return true;738}739if (o instanceof Bytes == false) {740return false;741}742Bytes other = (Bytes)o;743return Arrays.equals(this.b, other.b);744}745}746747private static Map<Bytes,TrustAttributes> getTrust(SunPKCS11 provider)748throws PKCS11Exception {749Map<Bytes,TrustAttributes> trustMap = new HashMap<Bytes,TrustAttributes>();750Token token = provider.getToken();751Session session = null;752try {753session = token.getOpSession();754int MAX_NUM = 8192;755CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {756new CK_ATTRIBUTE(CKA_CLASS, CKO_NETSCAPE_TRUST),757};758token.p11.C_FindObjectsInit(session.id(), attrs);759long[] handles = token.p11.C_FindObjects(session.id(), MAX_NUM);760token.p11.C_FindObjectsFinal(session.id());761if (DEBUG) System.out.println("handles: " + handles.length);762763for (long handle : handles) {764try {765TrustAttributes trust = new TrustAttributes(token, session, handle);766trustMap.put(trust.getHash(), trust);767} catch (PKCS11Exception e) {768// skip put on pkcs11 error769}770}771} finally {772token.releaseSession(session);773}774return trustMap;775}776777private static native long nssGetLibraryHandle(String libraryName);778779private static native long nssLoadLibrary(String name) throws IOException;780781private static native boolean nssVersionCheck(long handle, String minVersion);782783private static native boolean nssInitialize(String functionName, long handle, String configDir, boolean nssOptimizeSpace);784785private static native Object nssGetModuleList(long handle, String libDir);786787}788789790