Search in sources :

Example 41 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method addURITemplates.

/**
 * Add URI templates for the API.
 *
 * @param apiId    API Id
 * @param api      API
 * @param tenantId Tenant Id
 * @throws APIManagementException if fails to add URI templates for the API
 */
private void addURITemplates(int apiId, API api, int tenantId) throws APIManagementException {
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    apiMgtDAO.addURITemplates(apiId, api, tenantId);
    Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
    for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
        KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
        if (keyManager != null) {
            try {
                keyManager.attachResourceScopes(api, api.getUriTemplates());
            } catch (APIManagementException e) {
                log.error("Error while Attaching Resource to scope in Key Manager " + keyManagerDtoEntry.getKey(), e);
            }
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 42 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method addSharedScope.

/**
 * Add Shared Scope by registering it in the KM and adding the scope as a Shared Scope in AM DB.
 *
 * @param scope        Shared Scope
 * @param tenantDomain Tenant domain
 * @return UUId of the added Shared Scope object
 * @throws APIManagementException if failed to add a scope
 */
@Override
public String addSharedScope(Scope scope, String tenantDomain) throws APIManagementException {
    Set<Scope> scopeSet = new HashSet<>();
    scopeSet.add(scope);
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    addScopes(scopeSet, tenantId);
    Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
    for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
        KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
        if (keyManager != null) {
            try {
                keyManager.registerScope(scope);
            } catch (APIManagementException e) {
                log.error("Error occurred while registering Scope in Key Manager " + keyManagerDtoEntry.getKey(), e);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Adding shared scope mapping: " + scope.getKey() + " to  Key Manager : " + keyManagerDtoEntry.getKey());
        }
    }
    return ApiMgtDAO.getInstance().addSharedScope(scope, tenantDomain);
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 43 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project wso2-synapse by wso2.

the class SynapseConfigUtils method getHttpsURLConnection.

/**
 * Helper method to create a HttpSURLConnection with provided KeyStores
 *
 * @param url Https URL
 * @param synapseProperties properties for extracting info
 * @param proxy if there is a proxy
 * @return gives out the connection created
 */
private static HttpsURLConnection getHttpsURLConnection(URL url, Properties synapseProperties, Proxy proxy) {
    if (log.isDebugEnabled()) {
        log.debug("Creating a HttpsURL Connection from given URL : " + url);
    }
    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;
    IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory.createIdentityKeyStoreInformation(synapseProperties);
    if (identityInformation != null) {
        KeyManagerFactory keyManagerFactory = identityInformation.getIdentityKeyManagerFactoryInstance();
        if (keyManagerFactory != null) {
            keyManagers = keyManagerFactory.getKeyManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no private key entry store configuration." + " Will use JDK's default one");
        }
    }
    TrustKeyStoreInformation trustInformation = KeyStoreInformationFactory.createTrustKeyStoreInformation(synapseProperties);
    if (trustInformation != null) {
        TrustManagerFactory trustManagerFactory = trustInformation.getTrustManagerFactoryInstance();
        if (trustManagerFactory != null) {
            trustManagers = trustManagerFactory.getTrustManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no trusted certificate store configuration." + " Will use JDK's default one");
        }
    }
    try {
        HttpsURLConnection connection;
        if (proxy != null) {
            connection = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpsURLConnection) url.openConnection();
        }
        // Create a SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        connection.setSSLSocketFactory(sslContext.getSocketFactory());
        if (trustInformation != null) {
            // Determine is it need to overwrite default Host Name verifier
            boolean enableHostnameVerifier = true;
            String value = trustInformation.getParameter(KeyStoreInformation.ENABLE_HOST_NAME_VERIFIER);
            if (value != null) {
                enableHostnameVerifier = Boolean.parseBoolean(value);
            }
            if (!enableHostnameVerifier) {
                if (log.isDebugEnabled()) {
                    log.debug("Overriding default HostName Verifier." + "HostName verification disabled");
                }
                connection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {

                    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
                        if (log.isTraceEnabled()) {
                            log.trace("HostName verification disabled");
                            log.trace("Host:   " + hostname);
                            log.trace("Peer Host:  " + session.getPeerHost());
                        }
                        return true;
                    }
                });
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using default HostName verifier...");
                }
            }
        }
        return connection;
    } catch (NoSuchAlgorithmException e) {
        handleException("Error loading SSLContext ", e);
    } catch (KeyManagementException e) {
        handleException("Error initiation SSLContext with KeyManagers", e);
    } catch (IOException e) {
        handleException("Error opening a https connection from URL : " + url, e);
    }
    return null;
}
Also used : TrustKeyStoreInformation(org.wso2.securevault.definition.TrustKeyStoreInformation) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) SSLSession(javax.net.ssl.SSLSession) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) IdentityKeyStoreInformation(org.wso2.securevault.definition.IdentityKeyStoreInformation) HostnameVerifier(javax.net.ssl.HostnameVerifier) KeyManager(javax.net.ssl.KeyManager) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 44 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project wso2-synapse by wso2.

the class ClientConnFactoryBuilder method createSSLContext.

private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert) throws AxisFault {
    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;
    SecretResolver resolver;
    if (configurationContext != null && configurationContext.getAxisConfiguration() != null) {
        resolver = configurationContext.getAxisConfiguration().getSecretResolver();
    } else {
        resolver = SecretResolverFactory.create(keyStoreElt, false);
    }
    if (keyStoreElt != null) {
        String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
        OMElement passwordElement = keyStoreElt.getFirstChildWithName(new QName("Password"));
        OMElement keyPasswordElement = keyStoreElt.getFirstChildWithName(new QName("KeyPassword"));
        if (passwordElement == null) {
            throw new AxisFault("Cannot proceed because Password element is missing in KeyStore");
        }
        if (keyPasswordElement == null) {
            throw new AxisFault("Cannot proceed because KeyPassword element is missing in KeyStore");
        }
        String storePassword = SecureVaultValueReader.getSecureVaultValue(resolver, passwordElement);
        String keyPassword = SecureVaultValueReader.getSecureVaultValue(resolver, keyPasswordElement);
        FileInputStream fis = null;
        try {
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isDebugEnabled()) {
                log.debug(name + " Loading Identity Keystore from : " + location);
            }
            keyStore.load(fis, storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();
        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Keystore : " + location, gse);
            throw new AxisFault("Error loading Keystore : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Keystore : " + location, ioe);
            throw new AxisFault("Error opening Keystore : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }
    if (trustStoreElt != null) {
        if (novalidatecert && log.isWarnEnabled()) {
            log.warn(name + " Ignoring novalidatecert parameter since a truststore has been specified");
        }
        String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
        OMElement passwordElement = trustStoreElt.getFirstChildWithName(new QName("Password"));
        if (passwordElement == null) {
            throw new AxisFault("Cannot proceed because Password element is missing in TrustStore");
        }
        String storePassword = SecureVaultValueReader.getSecureVaultValue(resolver, passwordElement);
        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isDebugEnabled()) {
                log.debug(name + " Loading Trust Keystore from : " + location);
            }
            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();
        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    } else if (novalidatecert) {
        if (log.isWarnEnabled()) {
            log.warn(name + " Server certificate validation (trust) has been disabled. " + "DO NOT USE IN PRODUCTION!");
        }
        trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
    }
    try {
        final Parameter sslpParameter = transportOut.getParameter("SSLProtocol");
        final String sslProtocol = sslpParameter != null ? sslpParameter.getValue().toString() : "TLS";
        SSLContext sslcontext = SSLContext.getInstance(sslProtocol);
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;
    } catch (GeneralSecurityException gse) {
        log.error(name + " Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) QName(javax.xml.namespace.QName) GeneralSecurityException(java.security.GeneralSecurityException) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) TrustManager(javax.net.ssl.TrustManager) NoValidateCertTrustManager(org.apache.synapse.transport.nhttp.NoValidateCertTrustManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) NoValidateCertTrustManager(org.apache.synapse.transport.nhttp.NoValidateCertTrustManager) SecretResolver(org.wso2.securevault.SecretResolver) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Parameter(org.apache.axis2.description.Parameter) KeyManager(javax.net.ssl.KeyManager)

Example 45 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testUpdateScopeToApi.

@Test(description = "update existing Scope to API")
public void testUpdateScopeToApi() throws APIManagementException, IOException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    API api = SampleTestObjectCreator.createDefaultAPI().build();
    String uuid = api.getId();
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, gatewaySourceGenerator, gateway, keyManager);
    String oldSwagger = IOUtils.toString(new FileInputStream("src" + File.separator + "test" + File.separator + "resources" + File.separator + "swagger" + File.separator + "swaggerWithAuthorization" + ".yaml"));
    Scope scope = new Scope("apim:api_create", "apim:api_create");
    Mockito.when(apiDAO.getApiSwaggerDefinition(uuid)).thenReturn(oldSwagger);
    Mockito.when(keyManager.updateScope(scope)).thenReturn(true);
    Mockito.when(keyManager.retrieveScope("apim:api_create")).thenReturn(new Scope("apim:api_create", "Create " + "API"));
    apiPublisher.updateScopeOfTheApi(api.getId(), scope);
}
Also used : Scope(org.wso2.carbon.apimgt.core.models.Scope) API(org.wso2.carbon.apimgt.core.models.API) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) FileInputStream(java.io.FileInputStream) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Test(org.testng.annotations.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)38 Test (org.junit.Test)29 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 HashMap (java.util.HashMap)21 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 FileInputStream (java.io.FileInputStream)16 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)16 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)16 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)16 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)16 Map (java.util.Map)14 API (org.wso2.carbon.apimgt.core.models.API)14 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)13 Scope (org.wso2.carbon.apimgt.core.models.Scope)13 KeyManagerDto (org.wso2.carbon.apimgt.impl.dto.KeyManagerDto)13 TreeMap (java.util.TreeMap)11 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)11