Search in sources :

Example 21 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store 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 22 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project kubernetes by ballerinax.

the class KubernetesAnnotationProcessor method processSecureSocketAnnotation.

/**
 * Extract key-store/trust-store file location from endpoint.
 *
 * @param endpointName          Endpoint name
 * @param secureSocketKeyValues secureSocket annotation struct
 * @return List of @{@link SecretModel} objects
 */
Set<SecretModel> processSecureSocketAnnotation(String endpointName, List<BLangRecordLiteral.BLangRecordKeyValue> secureSocketKeyValues) throws KubernetesPluginException {
    Set<SecretModel> secrets = new HashSet<>();
    String keyStoreFile = null;
    String trustStoreFile = null;
    for (BLangRecordLiteral.BLangRecordKeyValue keyValue : secureSocketKeyValues) {
        // extract file paths.
        String key = keyValue.getKey().toString();
        if ("keyStore".equals(key)) {
            keyStoreFile = extractFilePath(keyValue);
        } else if ("trustStore".equals(key)) {
            trustStoreFile = extractFilePath(keyValue);
        }
    }
    if (keyStoreFile != null && trustStoreFile != null) {
        if (getMountPath(keyStoreFile).equals(getMountPath(trustStoreFile))) {
            // trust-store and key-store mount to same path
            String keyStoreContent = readSecretFile(keyStoreFile);
            String trustStoreContent = readSecretFile(trustStoreFile);
            SecretModel secretModel = new SecretModel();
            secretModel.setName(getValidName(endpointName) + "-secure-socket");
            secretModel.setMountPath(getMountPath(keyStoreFile));
            Map<String, String> dataMap = new HashMap<>();
            dataMap.put(String.valueOf(Paths.get(keyStoreFile).getFileName()), keyStoreContent);
            dataMap.put(String.valueOf(Paths.get(trustStoreFile).getFileName()), trustStoreContent);
            secretModel.setData(dataMap);
            secrets.add(secretModel);
            return secrets;
        }
    }
    if (keyStoreFile != null) {
        String keyStoreContent = readSecretFile(keyStoreFile);
        SecretModel secretModel = new SecretModel();
        secretModel.setName(getValidName(endpointName) + "-keystore");
        secretModel.setMountPath(getMountPath(keyStoreFile));
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put(String.valueOf(Paths.get(keyStoreFile).getFileName()), keyStoreContent);
        secretModel.setData(dataMap);
        secrets.add(secretModel);
    }
    if (trustStoreFile != null) {
        String trustStoreContent = readSecretFile(trustStoreFile);
        SecretModel secretModel = new SecretModel();
        secretModel.setName(getValidName(endpointName) + "-truststore");
        secretModel.setMountPath(getMountPath(trustStoreFile));
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put(String.valueOf(Paths.get(trustStoreFile).getFileName()), trustStoreContent);
        secretModel.setData(dataMap);
        secrets.add(secretModel);
    }
    return secrets;
}
Also used : HashMap(java.util.HashMap) SecretModel(org.ballerinax.kubernetes.models.SecretModel) BLangRecordLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral) HashSet(java.util.HashSet)

Example 23 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project airavata by apache.

the class Wso2IdentityServerClient method getAdminServiceClient.

public static RemoteUserStoreManagerServiceStub getAdminServiceClient(String adminUserName, String adminPassword, String adminService) {
    /**
     * trust store path.  this must contains server's  certificate or Server's CA chain
     */
    /* The below code snippet is intentionally commented for the build to pass,
         * because the private key and certificate file are not committed to GitHub,
         * which are needed to run the client */
    // String trustStore = System.getProperty("user.dir") + File.separator +
    // "modules" + File.separator + "user-profile-migration" + File.separator +
    // "src" + File.separator + "main" + File.separator +
    // "resources" + File.separator + "wso2carbon.jks";
    // System.out.println("file path : " + trustStore);
    /**
     * Call to https://localhost:9443/services/   uses HTTPS protocol.
     * Therefore we to validate the server certificate or CA chain. The server certificate is looked up in the
     * trust store.
     * Following code sets what trust-store to look for and its JKs password.
     */
    // System.setProperty("javax.net.ssl.trustStore",  trustStore );
    // System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
    // idp.scigap.org:9443 certificate has expired, so the following disables checking the certificate
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLContext.setDefault(sc);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    /**
     * Axis2 configuration context
     */
    ConfigurationContext configContext;
    RemoteUserStoreManagerServiceStub adminStub;
    try {
        /**
         * Create a configuration context. A configuration context contains information for
         * axis2 environment. This is needed to create an axis2 service client
         */
        configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
        /**
         * end point url with service name
         */
        // String serviceEndPoint = SEVER_URL + "RemoteUserStoreManagerService";
        String serviceEndPoint = SEVER_URL + adminService;
        /**
         * create stub and service client
         */
        adminStub = new RemoteUserStoreManagerServiceStub(configContext, serviceEndPoint);
        ServiceClient client = adminStub._getServiceClient();
        Options option = client.getOptions();
        /**
         * Setting a authenticated cookie that is received from Carbon server.
         * If you have authenticated with Carbon server earlier, you can use that cookie, if
         * it has not been expired
         */
        option.setProperty(HTTPConstants.COOKIE_STRING, null);
        /**
         * Setting basic auth headers for authentication for carbon server
         */
        HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
        auth.setUsername(adminUserName);
        auth.setPassword(adminPassword);
        auth.setPreemptiveAuthentication(true);
        option.setProperty(HTTPConstants.AUTHENTICATE, auth);
        option.setManageSession(true);
        return adminStub;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) Options(org.apache.axis2.client.Options) HttpTransportProperties(org.apache.axis2.transport.http.HttpTransportProperties) RemoteUserStoreManagerServiceStub(org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) ServiceClient(org.apache.axis2.client.ServiceClient)

Example 24 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project airavata by apache.

the class DefaultAiravataSecurityManager method isUserAuthorized.

public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException {
    try {
        String subject = authzToken.getClaimsMap().get(Constants.USER_NAME);
        String accessToken = authzToken.getAccessToken();
        String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
        String action = metaData.get(Constants.API_METHOD_NAME);
        // if the authz cache is enabled, check in the cache if the authz decision is cached and if so, what the status is
        if (ServerSettings.isAuthzCacheEnabled()) {
            // obtain an instance of AuthzCacheManager implementation.
            AuthzCacheManager authzCacheManager = AuthzCacheManagerFactory.getAuthzCacheManager();
            // check in the cache
            AuthzCachedStatus authzCachedStatus = authzCacheManager.getAuthzCachedStatus(new AuthzCacheIndex(subject, gatewayId, accessToken, action));
            if (AuthzCachedStatus.AUTHORIZED.equals(authzCachedStatus)) {
                logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
                return true;
            } else if (AuthzCachedStatus.NOT_AUTHORIZED.equals(authzCachedStatus)) {
                logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
                return false;
            } else if (AuthzCachedStatus.NOT_CACHED.equals(authzCachedStatus)) {
                logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is not in the cache. " + "Obtaining it from the authorization server.");
                CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
                GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
                PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
                String username = credential.getLoginUserName();
                if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
                    username = username + "@" + gwrp.getIdentityServerTenant();
                String password = credential.getPassword();
                // talk to Authorization Server, obtain the decision, cache it and return the result.
                ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
                // initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
                TrustStoreManager trustStoreManager = new TrustStoreManager();
                trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
                DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
                OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
                if (validationResponse.getValid()) {
                    String authorizedUserName = validationResponse.getAuthorizedUser();
                    if (authorizedUserName.contains("@")) {
                        authorizedUserName = authorizedUserName.split("@")[0];
                    }
                    if (subject.contains("@")) {
                        subject = subject.split("@")[0];
                    }
                    // cannot impersonate users
                    if (!authorizedUserName.toLowerCase().equals(subject.toLowerCase()))
                        return false;
                    long expiryTimestamp = validationResponse.getExpiryTime();
                    // check for fine grained authorization for the API invocation, based on XACML.
                    DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
                    boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
                    // cache the authorization decision
                    authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), new AuthzCacheEntry(authorizationDecision, expiryTimestamp, System.currentTimeMillis()));
                    return authorizationDecision;
                } else {
                    return false;
                }
            } else {
                // undefined status returned from the authz cache manager
                throw new AiravataSecurityException("Error in reading from the authorization cache.");
            }
        } else {
            CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
            GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
            PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
            String username = credential.getLoginUserName();
            if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
                username = username + "@" + gwrp.getIdentityServerTenant();
            String password = credential.getPassword();
            // talk to Authorization Server, obtain the decision and return the result (authz cache is not enabled).
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            // initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
            TrustStoreManager trustStoreManager = new TrustStoreManager();
            trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
            DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
            OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
            boolean isOAuthTokenValid = validationResponse.getValid();
            // if XACML based authorization is enabled, check for role based authorization for the API invocation
            DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
            boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
            return (isOAuthTokenValid && authorizationDecision);
        }
    } catch (AxisFault axisFault) {
        logger.error(axisFault.getMessage(), axisFault);
        throw new AiravataSecurityException("Error in initializing the configuration context for creating the OAuth validation client.");
    } catch (ApplicationSettingsException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading OAuth server configuration.");
    } catch (RegistryServiceException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in accessing AppCatalog.");
    } catch (TException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in connecting to Credential Store Service.");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) TException(org.apache.thrift.TException) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) DefaultXACMLPEP(org.apache.airavata.service.security.xacml.DefaultXACMLPEP) ApplicationSettingsException(org.apache.airavata.common.exception.ApplicationSettingsException) GatewayResourceProfile(org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile) RegistryServiceException(org.apache.airavata.registry.api.exception.RegistryServiceException) PasswordCredential(org.apache.airavata.model.credential.store.PasswordCredential) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO) DefaultOAuthClient(org.apache.airavata.service.security.oauth.DefaultOAuthClient) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) CredentialStoreService(org.apache.airavata.credential.store.cpi.CredentialStoreService)

Example 25 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project ballerina by ballerina-lang.

the class CodeGenerator method generateURILookupInstructions.

private void generateURILookupInstructions(Map<Name, BXMLNSSymbol> namespaces, RegIndex localNameRegIndex, RegIndex uriRegIndex, RegIndex targetQNameRegIndex, DiagnosticPos pos, SymbolEnv symbolEnv) {
    if (namespaces.isEmpty()) {
        createQNameWithoutPrefix(localNameRegIndex, uriRegIndex, targetQNameRegIndex);
        return;
    }
    Stack<Operand> endJumpInstrStack = new Stack<>();
    String prefix;
    for (Entry<Name, BXMLNSSymbol> keyValues : namespaces.entrySet()) {
        prefix = keyValues.getKey().getValue();
        // skip the default namespace
        if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
            continue;
        }
        // Below section creates the condition to compare the namespace URIs
        // store the comparing uri as string
        BXMLNSSymbol nsSymbol = keyValues.getValue();
        int opcode = getOpcode(TypeTags.STRING, InstructionCodes.IEQ);
        RegIndex conditionExprIndex = getRegIndex(TypeTags.BOOLEAN);
        emit(opcode, uriRegIndex, getNamespaceURIIndex(nsSymbol, symbolEnv), conditionExprIndex);
        Operand ifCondJumpAddr = getOperand(-1);
        emit(InstructionCodes.BR_FALSE, conditionExprIndex, ifCondJumpAddr);
        // Below section creates instructions to be executed, if the above condition succeeds (then body)
        // create the prefix literal
        RegIndex prefixIndex = createStringLiteral(prefix, null, env);
        // create a qname
        emit(InstructionCodes.NEWQNAME, localNameRegIndex, uriRegIndex, prefixIndex, targetQNameRegIndex);
        Operand endJumpAddr = getOperand(-1);
        emit(InstructionCodes.GOTO, endJumpAddr);
        endJumpInstrStack.add(endJumpAddr);
        ifCondJumpAddr.value = nextIP();
    }
    // else part. create a qname with empty prefix
    createQNameWithoutPrefix(localNameRegIndex, uriRegIndex, targetQNameRegIndex);
    while (!endJumpInstrStack.isEmpty()) {
        endJumpInstrStack.pop().value = nextIP();
    }
}
Also used : BXMLNSSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BXMLNSSymbol) Operand(org.wso2.ballerinalang.programfile.Instruction.Operand) BLangXMLQuotedString(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQuotedString) BLangEndpoint(org.wso2.ballerinalang.compiler.tree.BLangEndpoint) Stack(java.util.Stack) BLangXMLQName(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQName) Name(org.ballerinalang.model.Name) RegIndex(org.wso2.ballerinalang.programfile.Instruction.RegIndex)

Aggregations

HashMap (java.util.HashMap)25 Test (org.testng.annotations.Test)21 ArrayList (java.util.ArrayList)18 CharonException (org.wso2.charon3.core.exceptions.CharonException)18 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)18 UserManager (org.wso2.charon3.core.extensions.UserManager)15 Produces (javax.ws.rs.Produces)14 ApiOperation (io.swagger.annotations.ApiOperation)12 ApiResponses (io.swagger.annotations.ApiResponses)12 Path (javax.ws.rs.Path)10 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 Map (java.util.Map)9 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)8 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)8 UserStoreException (org.wso2.carbon.user.api.UserStoreException)8 Consumes (javax.ws.rs.Consumes)7 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)7 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)7 Response (feign.Response)6 IOException (java.io.IOException)6