Search in sources :

Example 1 with SecurityConfigException

use of org.wso2.carbon.security.SecurityConfigException in project carbon-identity-framework by wso2.

the class KeyStoreAdmin method addTrustStore.

public void addTrustStore(byte[] content, String filename, String password, String provider, String type) throws SecurityConfigException {
    if (filename == null) {
        throw new SecurityConfigException("Key Store name can't be null");
    }
    try {
        if (KeyStoreUtil.isPrimaryStore(filename)) {
            throw new SecurityConfigException("Key store " + filename + " already available");
        }
        String path = SecurityConstants.KEY_STORES + "/" + filename;
        if (registry.resourceExists(path)) {
            throw new SecurityConfigException("Key store " + filename + " already available");
        }
        KeyStore keyStore = KeyStore.getInstance(type);
        keyStore.load(new ByteArrayInputStream(content), password.toCharArray());
        CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
        Resource resource = registry.newResource();
        resource.addProperty(SecurityConstants.PROP_PASSWORD, cryptoUtil.encryptAndBase64Encode(password.getBytes()));
        resource.addProperty(SecurityConstants.PROP_PROVIDER, provider);
        resource.addProperty(SecurityConstants.PROP_TYPE, type);
        resource.setContent(content);
        registry.put(path, resource);
    } catch (SecurityConfigException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Error when adding a trustStore";
        log.error(msg, e);
        throw new SecurityConfigException(msg, e);
    }
}
Also used : SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) ByteArrayInputStream(java.io.ByteArrayInputStream) Resource(org.wso2.carbon.registry.core.Resource) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 2 with SecurityConfigException

use of org.wso2.carbon.security.SecurityConfigException in project carbon-identity-framework by wso2.

the class KeyStoreAdmin method getPaginatedKeystoreInfo.

/**
 * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a
 * given keystore.
 *
 * @param keyStoreName The name of the keystore
 * @param pageNumber   page number
 * @return Instance of KeyStoreData
 * @throws SecurityConfigException will be thrown
 */
public PaginatedKeyStoreData getPaginatedKeystoreInfo(String keyStoreName, int pageNumber) throws SecurityConfigException {
    try {
        if (keyStoreName == null) {
            throw new Exception("keystore name cannot be null");
        }
        KeyStore keyStore;
        String keyStoreType;
        String keyStorePassword = null;
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = keyMan.getPrimaryKeyStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig.getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
            keyStorePassword = serverConfig.getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
        } else if (isTrustStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = getTrustStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig.getFirstProperty(SERVER_TRUSTSTORE_TYPE);
            keyStorePassword = serverConfig.getFirstProperty(SERVER_TRUSTSTORE_PASSWORD);
        } else {
            String path = SecurityConstants.KEY_STORES + "/" + keyStoreName;
            if (!registry.resourceExists(path)) {
                throw new SecurityConfigException("Key Store not found");
            }
            Resource resource = registry.get(path);
            KeyStoreManager manager = KeyStoreManager.getInstance(tenantId);
            keyStore = getKeyStore(keyStoreName);
            keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE);
            String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS);
            if (encpass != null) {
                CryptoUtil util = CryptoUtil.getDefaultCryptoUtil();
                keyStorePassword = new String(util.base64DecodeAndDecrypt(encpass));
            }
        }
        // Fill the information about the certificates
        Enumeration<String> aliases = keyStore.aliases();
        List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                certDataList.add(fillCertData(cert, alias, formatter));
            }
        }
        // Create a cert array
        CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]);
        // Create a KeyStoreData bean, set the name and fill in the cert information
        PaginatedKeyStoreData keyStoreData = new PaginatedKeyStoreData();
        keyStoreData.setKeyStoreName(keyStoreName);
        keyStoreData.setPaginatedCertData(doPaging(pageNumber, certs));
        keyStoreData.setKeyStoreType(keyStoreType);
        List<CertData> keyDataList = new ArrayList<>();
        aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isKeyEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                keyDataList.add(fillCertData(cert, alias, formatter));
            }
        }
        // Create a cert array.
        CertData[] keyCerts = keyDataList.toArray(new CertData[keyDataList.size()]);
        // Create a KeyStoreData bean, set the name and fill in the cert information.
        keyStoreData.setPaginatedKeyData(doPaging(pageNumber, keyCerts));
        return keyStoreData;
    } catch (Exception e) {
        String msg = "Error has encounted while loading the keystore to the given keystore name " + keyStoreName;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
}
Also used : PaginatedCertData(org.wso2.carbon.security.keystore.service.PaginatedCertData) CertData(org.wso2.carbon.security.keystore.service.CertData) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) Resource(org.wso2.carbon.registry.core.Resource) ArrayList(java.util.ArrayList) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate) KeyStoreManager(org.wso2.carbon.core.util.KeyStoreManager) SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) PaginatedKeyStoreData(org.wso2.carbon.security.keystore.service.PaginatedKeyStoreData) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with SecurityConfigException

use of org.wso2.carbon.security.SecurityConfigException in project carbon-identity-framework by wso2.

the class KeyStoreAdmin method extractCertificate.

/**
 * Extract the encoded certificate into {@link X509Certificate}.
 *
 * @param certData encoded certificate.
 * @return {@link X509Certificate} object.
 * @throws SecurityConfigException if extracting the certificate fails.
 */
public X509Certificate extractCertificate(String certData) throws SecurityConfigException {
    byte[] bytes = Base64.decode(certData);
    X509Certificate cert;
    try {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes));
    } catch (CertificateException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
        throw new SecurityConfigException("Invalid format of the provided certificate file");
    }
    return cert;
}
Also used : SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 4 with SecurityConfigException

use of org.wso2.carbon.security.SecurityConfigException in project carbon-identity-framework by wso2.

the class KeyStoreAdmin method removeCertFromStore.

public void removeCertFromStore(String alias, String keyStoreName) throws SecurityConfigException {
    try {
        if (keyStoreName == null) {
            throw new SecurityConfigException("Key Store name can't be null");
        }
        KeyStore ks = getKeyStore(keyStoreName);
        if (ks.getCertificate(alias) == null) {
            return;
        }
        ks.deleteEntry(alias);
        updateKeyStore(keyStoreName, ks);
        if (isTrustStore(keyStoreName)) {
            System.setProperty(IdentityUtil.PROP_TRUST_STORE_UPDATE_REQUIRED, Boolean.TRUE.toString());
        }
    } catch (SecurityConfigException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Error when removing cert from store";
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
}
Also used : SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 5 with SecurityConfigException

use of org.wso2.carbon.security.SecurityConfigException in project carbon-identity-framework by wso2.

the class KeyStoreAdmin method getKeyStores.

/**
 * Method to retrive keystore data.
 *
 * @param isSuperTenant - Indication whether the querying super tennat data
 * @return
 * @throws SecurityConfigException
 */
public KeyStoreData[] getKeyStores(boolean isSuperTenant) throws SecurityConfigException {
    CarbonUtils.checkSecurity();
    KeyStoreData[] names = new KeyStoreData[0];
    try {
        if (registry.resourceExists(SecurityConstants.KEY_STORES)) {
            Collection collection = (Collection) registry.get(SecurityConstants.KEY_STORES);
            String[] ks = collection.getChildren();
            List<KeyStoreData> lst = new ArrayList<>();
            for (int i = 0; i < ks.length; i++) {
                String fullname = ks[i];
                if (RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE.equals(fullname)) {
                    continue;
                }
                Resource store = registry.get(ks[i]);
                int lastIndex = fullname.lastIndexOf("/");
                String name = fullname.substring(lastIndex + 1);
                String type = store.getProperty(SecurityConstants.PROP_TYPE);
                String provider = store.getProperty(SecurityConstants.PROP_PROVIDER);
                KeyStoreData data = new KeyStoreData();
                data.setKeyStoreName(name);
                data.setKeyStoreType(type);
                data.setProvider(provider);
                String alias = store.getProperty(SecurityConstants.PROP_PRIVATE_KEY_ALIAS);
                if (alias != null) {
                    data.setPrivateStore(true);
                } else {
                    data.setPrivateStore(false);
                }
                // Dump the generated public key to the file system for sub tenants
                if (!isSuperTenant) {
                    Association[] associations = registry.getAssociations(ks[i], SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY);
                    if (associations != null && associations.length > 0) {
                        Resource pubKeyResource = registry.get(associations[0].getDestinationPath());
                        String fileName = generatePubCertFileName(ks[i], pubKeyResource.getProperty(SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER));
                        if (MessageContext.getCurrentMessageContext() != null) {
                            String pubKeyFilePath = KeyStoreMgtUtil.dumpCert(MessageContext.getCurrentMessageContext().getConfigurationContext(), (byte[]) pubKeyResource.getContent(), fileName);
                            data.setPubKeyFilePath(pubKeyFilePath);
                        }
                    }
                }
                lst.add(data);
            }
            names = new KeyStoreData[lst.size() + 1];
            Iterator<KeyStoreData> ite = lst.iterator();
            int count = 0;
            while (ite.hasNext()) {
                names[count] = ite.next();
                count++;
            }
            if (isSuperTenant) {
                KeyStoreData data = new KeyStoreData();
                ServerConfiguration config = ServerConfiguration.getInstance();
                String fileName = config.getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_FILE);
                String type = config.getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
                String name = KeyStoreUtil.getKeyStoreFileName(fileName);
                data.setKeyStoreName(name);
                data.setKeyStoreType(type);
                data.setProvider(" ");
                data.setPrivateStore(true);
                names[count] = data;
            }
        }
        return names;
    } catch (RegistryException e) {
        String msg = "Error when getting keyStore data";
        log.error(msg, e);
        throw new SecurityConfigException(msg, e);
    }
}
Also used : ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.core.Resource) PaginatedKeyStoreData(org.wso2.carbon.security.keystore.service.PaginatedKeyStoreData) KeyStoreData(org.wso2.carbon.security.keystore.service.KeyStoreData) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) SecurityConfigException(org.wso2.carbon.security.SecurityConfigException) Association(org.wso2.carbon.registry.core.Association) Collection(org.wso2.carbon.registry.core.Collection)

Aggregations

SecurityConfigException (org.wso2.carbon.security.SecurityConfigException)16 KeyStore (java.security.KeyStore)10 KeyStoreException (java.security.KeyStoreException)10 CertificateException (java.security.cert.CertificateException)10 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)10 IOException (java.io.IOException)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)8 KeyStoreAdmin (org.wso2.carbon.security.keystore.KeyStoreAdmin)6 X509Certificate (java.security.cert.X509Certificate)5 ServerConfiguration (org.wso2.carbon.base.ServerConfiguration)5 Resource (org.wso2.carbon.registry.core.Resource)5 KeyStoreData (org.wso2.carbon.security.keystore.service.KeyStoreData)5 ArrayList (java.util.ArrayList)4 CryptoUtil (org.wso2.carbon.core.util.CryptoUtil)4 PaginatedKeyStoreData (org.wso2.carbon.security.keystore.service.PaginatedKeyStoreData)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 KeyStoreManager (org.wso2.carbon.core.util.KeyStoreManager)3 Format (java.text.Format)2 SimpleDateFormat (java.text.SimpleDateFormat)2