Search in sources :

Example 1 with TrustStoreManager

use of org.apache.airavata.security.util.TrustStoreManager in project airavata by apache.

the class OAuthTokenRetrievalClient method retrieveAccessToken.

/**
 * Retrieve the OAuth Access token via the specified grant type.
 * @param consumerId
 * @param consumerSecret
 * @param userName
 * @param password
 * @param grantType
 * @return
 * @throws SecurityException
 */
public String retrieveAccessToken(String consumerId, String consumerSecret, String userName, String password, int grantType) throws AiravataSecurityException {
    HttpPost postMethod = null;
    try {
        // initialize trust store to handle SSL handshake with WSO2 IS properly.
        TrustStoreManager trustStoreManager = new TrustStoreManager();
        SSLContext sslContext = trustStoreManager.initializeTrustStoreManager(Properties.TRUST_STORE_PATH, Properties.TRUST_STORE_PASSWORD);
        // create https scheme with the trust store
        org.apache.http.conn.ssl.SSLSocketFactory sf = new org.apache.http.conn.ssl.SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, Properties.authzServerPort);
        HttpClient httpClient = new DefaultHttpClient();
        // set the https scheme in the httpclient
        httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
        postMethod = new HttpPost(Properties.oauthTokenEndPointURL);
        // build the HTTP request with relevant params for resource owner credential grant type
        String authInfo = consumerId + ":" + consumerSecret;
        String authHeader = new String(Base64.encodeBase64(authInfo.getBytes()));
        postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.setHeader("Authorization", "Basic " + authHeader);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        if (grantType == 1) {
            urlParameters.add(new BasicNameValuePair("grant_type", "password"));
            urlParameters.add(new BasicNameValuePair("username", userName));
            urlParameters.add(new BasicNameValuePair("password", password));
        } else if (grantType == 2) {
            urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
        }
        postMethod.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse response = httpClient.execute(postMethod);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(result.toString());
        return (String) jsonObject.get("access_token");
    } catch (ClientProtocolException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (IOException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Scheme(org.apache.http.conn.scheme.Scheme) ArrayList(java.util.ArrayList) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSLContext(javax.net.ssl.SSLContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) JSONObject(org.json.simple.JSONObject) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException)

Example 2 with TrustStoreManager

use of org.apache.airavata.security.util.TrustStoreManager 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 3 with TrustStoreManager

use of org.apache.airavata.security.util.TrustStoreManager in project airavata by apache.

the class DefaultAiravataSecurityManager method initializeSecurityInfra.

@Override
public void initializeSecurityInfra() throws AiravataSecurityException {
    /* in the default security manager, this method checks if the xacml authorization policy is published,
         * and if not, publish the policy to the PDP (of WSO2 Identity Server)
         */
    try {
        if (ServerSettings.isAPISecured()) {
            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());
            List<GatewayResourceProfile> gwProfiles = getRegistryServiceClient().getAllGatewayResourceProfiles();
            // read the policy as a string
            BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(ServerSettings.getAuthorizationPoliyName() + ".xml")));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String defaultXACMLPolicy = stringBuilder.toString();
            CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
            for (GatewayResourceProfile gwrp : gwProfiles) {
                if (gwrp.getIdentityServerPwdCredToken() != null && gwrp.getIdentityServerTenant() != null) {
                    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();
                    DefaultPAPClient PAPClient = new DefaultPAPClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
                    boolean policyAdded = PAPClient.isPolicyAdded(ServerSettings.getAuthorizationPoliyName());
                    if (policyAdded) {
                        logger.debug("Authorization policy is already added in the authorization server.");
                    } else {
                        // publish the policy and enable it in a separate thread
                        PAPClient.addPolicy(defaultXACMLPolicy);
                        logger.debug("Authorization policy is published in the authorization server.");
                    }
                } else {
                    logger.warn("Identity Server configuration missing for gateway : " + gwrp.getGatewayID());
                }
            }
        }
    } catch (AxisFault axisFault) {
        logger.error(axisFault.getMessage(), axisFault);
        throw new AiravataSecurityException("Error in initializing the configuration context for creating the " + "PAP client.");
    } catch (ApplicationSettingsException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading configuration when creating the PAP client.");
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading authorization policy.");
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading the authorization policy.");
    } catch (RegistryServiceException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading the Gateway Profiles from App Catalog.");
    } 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) 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) DefaultPAPClient(org.apache.airavata.service.security.xacml.DefaultPAPClient) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) CredentialStoreService(org.apache.airavata.credential.store.cpi.CredentialStoreService)

Example 4 with TrustStoreManager

use of org.apache.airavata.security.util.TrustStoreManager in project airavata by apache.

the class KeyCloakSecurityManager method initializeSecurityInfra.

/**
 * Implement this method in your SecurityManager to perform necessary initializations at the server startup.
 *
 * @throws AiravataSecurityException
 */
@Override
public void initializeSecurityInfra() throws AiravataSecurityException {
    try {
        // 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());
    } catch (Exception e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    }
}
Also used : TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) RegistryServiceException(org.apache.airavata.registry.api.exception.RegistryServiceException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) CredentialStoreException(org.apache.airavata.credential.store.exception.CredentialStoreException) TException(org.apache.thrift.TException) ApplicationSettingsException(org.apache.airavata.common.exception.ApplicationSettingsException)

Example 5 with TrustStoreManager

use of org.apache.airavata.security.util.TrustStoreManager in project airavata by apache.

the class OAuthAppRegisteringClient method registerApplication.

public OAuthConsumerAppDTO registerApplication(String appName, String consumerId, String consumerSecret) throws AiravataSecurityException {
    try {
        OAuthConsumerAppDTO consumerAppDTO = new OAuthConsumerAppDTO();
        consumerAppDTO.setApplicationName(appName);
        // consumer key and secret is set by the application.
        consumerAppDTO.setOauthConsumerKey(consumerId);
        consumerAppDTO.setOauthConsumerSecret(consumerSecret);
        // consumerAppDTO.setUsername(adminUserName);
        // initialize trust store for SSL handshake
        TrustStoreManager trustStoreManager = new TrustStoreManager();
        trustStoreManager.initializeTrustStoreManager(Properties.TRUST_STORE_PATH, Properties.TRUST_STORE_PASSWORD);
        stub.registerOAuthApplicationData(consumerAppDTO);
        // After registration application is retrieve
        return stub.getOAuthApplicationDataByAppName(appName);
    } catch (AxisFault axisFault) {
        axisFault.printStackTrace();
        throw new AiravataSecurityException("Error in registering the OAuth application.");
    } catch (RemoteException e) {
        e.printStackTrace();
        throw new AiravataSecurityException("Error in registering the OAuth application.");
    } catch (OAuthAdminServiceException e) {
        e.printStackTrace();
        throw new AiravataSecurityException("Error in registering the OAuth application.");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) OAuthAdminServiceException(org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) RemoteException(java.rmi.RemoteException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException)

Aggregations

AiravataSecurityException (org.apache.airavata.security.AiravataSecurityException)5 TrustStoreManager (org.apache.airavata.security.util.TrustStoreManager)5 ApplicationSettingsException (org.apache.airavata.common.exception.ApplicationSettingsException)3 RegistryServiceException (org.apache.airavata.registry.api.exception.RegistryServiceException)3 AxisFault (org.apache.axis2.AxisFault)3 TException (org.apache.thrift.TException)3 CredentialStoreService (org.apache.airavata.credential.store.cpi.CredentialStoreService)2 GatewayResourceProfile (org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile)2 PasswordCredential (org.apache.airavata.model.credential.store.PasswordCredential)2 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 RemoteException (java.rmi.RemoteException)1 ArrayList (java.util.ArrayList)1 SSLContext (javax.net.ssl.SSLContext)1 CredentialStoreException (org.apache.airavata.credential.store.exception.CredentialStoreException)1 DefaultOAuthClient (org.apache.airavata.service.security.oauth.DefaultOAuthClient)1 DefaultPAPClient (org.apache.airavata.service.security.xacml.DefaultPAPClient)1