org.wso2.carbon.identity.sso.agent.SSOAgentException Java Examples

The following examples show how to use org.wso2.carbon.identity.sso.agent.SSOAgentException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 7 votes vote down vote up
/**
 * Sign the SAML AuthnRequest message
 *
 * @param logoutRequest
 * @param signatureAlgorithm
 * @param cred
 * @return
 * @throws SSOAgentException
 */
public static LogoutRequest setSignature(LogoutRequest logoutRequest, String signatureAlgorithm,
                                         X509Credential cred) throws SSOAgentException {
    try {
        Signature signature = setSignatureRaw(signatureAlgorithm,cred);

        logoutRequest.setSignature(signature);

        List<Signature> signatureList = new ArrayList<Signature>();
        signatureList.add(signature);

        // Marshall and Sign
        MarshallerFactory marshallerFactory =
                org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(logoutRequest);

        marshaller.marshall(logoutRequest);

        org.apache.xml.security.Init.init();
        Signer.signObjects(signatureList);
        return logoutRequest;

    } catch (Exception e) {
        throw new SSOAgentException("Error while signing the Logout Request message", e);
    }
}
 
Example #2
Source File: SSOConfigurationReader.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Read {@link Constants#JKS_FILE_NAME} JKS file and return X509Credential of Identity Provider.
 * @return X509Credential of Identity Server.
 * @throws TestGridException if an error occur while reading JKS file.
 */
public SSOAgentX509Credential getIdPX509Credential() throws TestGridException {
    Properties properties = getSSOProperties();
    try {
        java.nio.file.Path configPath = Paths.
                get(TestGridUtil.getTestGridHomePath(), Constants.SSO_DIRECTORY, Constants.JKS_FILE_NAME);

        InputStream keyStoreInputStream = Files.newInputStream(configPath);
        SSOAgentX509Credential credential;

        credential = new SSOAgentX509KeyStoreCredential(keyStoreInputStream,
                properties.getProperty(Constants.PROPERTYNAME_KEYSTORE_PASSWORD).toCharArray(),
                properties.getProperty(Constants.PROPERTYNAME_IDP_PUBLIC_KEY_ALIAS),
                properties.getProperty(Constants.PROPERTYNAME_PRIVATE_KEY_ALIAS),
                properties.getProperty(Constants.PROPERTYNAME_PRIVATE_KEY_PASSWORD).toCharArray());
        return credential;
    } catch (IOException | SSOAgentException e) {
        throw new TestGridException("Error occurred while reading JKS file to fetch IdP's credential.", e);
    }
}
 
Example #3
Source File: LoggedInSessionBean.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void readObject(java.io.ObjectInputStream stream)
        throws IOException, ClassNotFoundException, SSOAgentException {

    subjectId = (String) stream.readObject();

    responseString = (String) stream.readObject();
    if (responseString != null && !EMPTY_STRING.equals(responseString)) {
        response = (Response) SSOAgentUtils.unmarshall(responseString);
    }

    assertionString = (String) stream.readObject();
    if (responseString != null && !EMPTY_STRING.equals(assertionString)) {
        assertion = (Assertion) SSOAgentUtils.unmarshall(assertionString);
    }

    sessionIndex = (String) stream.readObject();
    String accessTokenResponseBeanString = (String) stream.readObject();
    if (!EMPTY_STRING.equals(accessTokenResponseBeanString)) {
        accessTokenResponseBean = accessTokenResponseBean.deSerialize(accessTokenResponseBeanString);
    } else {
        accessTokenResponseBean = null;
    }
    subjectAttributes = (Map) stream.readObject();
}
 
Example #4
Source File: SSOAgentConfig.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * get the key store instance
 *
 * @param is            KeyStore InputStream
 * @param storePassword password of key store
 * @return KeyStore instant
 * @throws org.wso2.carbon.identity.sso.agent.exception.SSOAgentException if fails to load key store
 */
private KeyStore readKeyStore(InputStream is, String storePassword) throws
                                                                           org.wso2.carbon.identity.sso.agent.exception.SSOAgentException {

    if (storePassword == null) {
        throw new org.wso2.carbon.identity.sso.agent.exception.SSOAgentException("KeyStore password can not be null");
    }

    try {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, storePassword.toCharArray());
        return keyStore;
    } catch (Exception e) {

        throw new org.wso2.carbon.identity.sso.agent.exception.SSOAgentException("Error while loading key store file", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignored) {

                throw new org.wso2.carbon.identity.sso.agent.exception.SSOAgentException("Error while closing input stream of key store", ignored);
            }
        }
    }
}
 
Example #5
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static void addDeflateSignatureToHTTPQueryString(StringBuilder httpQueryString,
                                                        X509Credential cred) throws SSOAgentException {
    doBootstrap();
    try {
        httpQueryString.append("&SigAlg="
                + URLEncoder.encode(XMLSignature.ALGO_ID_SIGNATURE_RSA, "UTF-8").trim());

        java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
        signature.initSign(cred.getPrivateKey());
        signature.update(httpQueryString.toString().getBytes(Charset.forName("UTF-8")));
        byte[] signatureByteArray = signature.sign();

        String signatureBase64encodedString = Base64.encodeBytes(signatureByteArray,
                Base64.DONT_BREAK_LINES);
        httpQueryString.append("&Signature="
                + URLEncoder.encode(signatureBase64encodedString, "UTF-8").trim());
    } catch (Exception e) {
        throw new SSOAgentException("Error applying SAML2 Redirect Binding signature", e);
    }
}
 
Example #6
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private static Signature setSignatureRaw(String signatureAlgorithm, X509Credential cred) throws SSOAgentException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        org.opensaml.xml.signature.X509Certificate cert =
                (org.opensaml.xml.signature.X509Certificate) buildXMLObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
        String value =
                org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
        return signature;

    } catch (CertificateEncodingException e) {
        throw new SSOAgentException("Error getting certificate", e);
    }
}
 
Example #7
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void processResponse(HttpServletRequest request, HttpServletResponse response)
        throws SSOAgentException {

    String saml2SSOResponse = request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP);

    if (saml2SSOResponse != null) {
        String decodedResponse = new String(Base64.decode(saml2SSOResponse), Charset.forName("UTF-8"));
        XMLObject samlObject = SSOAgentUtils.unmarshall(decodedResponse);
        if (samlObject instanceof LogoutResponse) {
            //This is a SAML response for a single logout request from the SP
            doSLO(request);
        } else {
            processSSOResponse(request);
        }
        String relayState = request.getParameter(RelayState.DEFAULT_ELEMENT_LOCAL_NAME);

        if (relayState != null && !relayState.isEmpty() && !"null".equalsIgnoreCase(relayState)) { //additional
            // checks for incompetent IdPs
            ssoAgentConfig.getSAML2().setRelayState(relayState);
        }

    } else {
        throw new SSOAgentException("Invalid SAML2 Response. SAML2 Response can not be null.");
    }
}
 
Example #8
Source File: SSOAgentX509KeyStoreCredential.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
protected void readX509Credentials(InputStream keyStoreInputStream, char[] keyStorePassword,
                                   String publicCertAlias, String privateKeyAlias,
                                   char[] privateKeyPassword)
        throws SSOAgentException {

    try {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(keyStoreInputStream, keyStorePassword);
        readX509Credentials(keyStore, publicCertAlias, privateKeyAlias, privateKeyPassword);
    } catch (Exception e) {
        throw new SSOAgentException("Error while loading key store file", e);
    } finally {
        if (keyStoreInputStream != null) {
            try {
                keyStoreInputStream.close();
            } catch (IOException ignored) {
                if (log.isDebugEnabled()){
                    log.debug("Ignoring IO Exception : ", ignored);
                }
                throw new SSOAgentException("Error while closing input stream of key store");
            }
        }
    }
}
 
Example #9
Source File: SSOContextEventListener.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch relevant details from
 * {@link org.wso2.testgrid.web.utils.Constants#SSO_PROPERTY_FILE_NAME} property file and
 * {@link org.wso2.testgrid.web.utils.Constants#JKS_FILE_NAME} JKS file.
 */
public void contextInitialized(ServletContextEvent servletContextEvent) {
    String isSsoEnabled = ConfigurationContext.getProperty(ConfigurationContext.ConfigurationProperties.ENABLE_SSO);
    if (!Boolean.valueOf(isSsoEnabled)) {
        return;
    }
    SSOConfigurationReader ssoConfigurationReader = new SSOConfigurationReader();
    try {
        SSOAgentX509Credential credential = ssoConfigurationReader.getIdPX509Credential();
        SSOAgentConfig config = new SSOAgentConfig();
        config.initConfig(ssoConfigurationReader.getSSOProperties());
        config.getSAML2().setSSOAgentX509Credential(credential);
        servletContextEvent.getServletContext().
                setAttribute(SSOAgentConstants.CONFIG_BEAN_NAME, config);
    } catch (SSOAgentException | TestGridException e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example #10
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the AudienceRestriction of SAML2 Response
 *
 * @param assertion SAML2 Assertion
 * @return validity
 */
protected void validateAudienceRestriction(Assertion assertion) throws SSOAgentException {

    if (assertion != null) {
        Conditions conditions = assertion.getConditions();
        if (conditions != null) {
            List<AudienceRestriction> audienceRestrictions = conditions.getAudienceRestrictions();
            if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
                boolean audienceFound = false;
                for (AudienceRestriction audienceRestriction : audienceRestrictions) {
                    if (audienceRestriction.getAudiences() != null && !audienceRestriction.getAudiences().isEmpty()
                            ) {
                        for (Audience audience : audienceRestriction.getAudiences()) {
                            if (ssoAgentConfig.getSAML2().getSPEntityId().equals(audience.getAudienceURI())) {
                                audienceFound = true;
                                break;
                            }
                        }
                    }
                    if (audienceFound) {
                        break;
                    }
                }
                if (!audienceFound) {
                    throw new SSOAgentException("SAML2 Assertion Audience Restriction validation failed");
                }
            } else {
                throw new SSOAgentException("SAML2 Response doesn't contain AudienceRestrictions");
            }
        } else {
            throw new SSOAgentException("SAML2 Response doesn't contain Conditions");
        }
    }
}
 
Example #11
Source File: SAML2GrantManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void getAccessToken(HttpServletRequest request, HttpServletResponse response)
        throws SSOAgentException {


    String samlAssertionString = ((LoggedInSessionBean) request.getSession(false).
            getAttribute(SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().
            getAssertionString();

    String clientLogin = ssoAgentConfig.getOAuth2().getClientId() + ":" +
            ssoAgentConfig.getOAuth2().getClientSecret();
    String queryParam = "grant_type=" + SSOAgentConstants.OAuth2.SAML2_BEARER_GRANT_TYPE + "&assertion=" +
                        URLEncoder.encode(Base64.encodeBytes(
                                samlAssertionString.getBytes(Charset.forName("UTF-8"))).replaceAll("\n", ""));
    String additionalQueryParam = ssoAgentConfig.getRequestQueryParameters();
    if (additionalQueryParam != null) {
        queryParam = queryParam + additionalQueryParam;
    }
    String accessTokenResponse = executePost(queryParam,
                                             Base64.encodeBytes(clientLogin.getBytes(Charset.forName("UTF-8")))
                                                   .replace("\n", ""));

    Gson gson = new Gson();
    LoggedInSessionBean.AccessTokenResponseBean accessTokenResp =
            gson.fromJson(accessTokenResponse, LoggedInSessionBean.AccessTokenResponseBean.class);

    ((LoggedInSessionBean) request.getSession(false).getAttribute(
            SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO()
            .setAccessTokenResponseBean(accessTokenResp);
}
 
Example #12
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Builds SAML Elements
 *
 * @param objectQName
 * @return
 * @throws SSOAgentException
 */
private static XMLObject buildXMLObject(QName objectQName) throws SSOAgentException {
    doBootstrap();
    XMLObjectBuilder builder =
            org.opensaml.xml.Configuration.getBuilderFactory()
                    .getBuilder(objectQName);
    if (builder == null) {
        throw new SSOAgentException("Unable to retrieve builder for object QName " +
                objectQName);
    }
    return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(),
            objectQName.getPrefix());
}
 
Example #13
Source File: OpenIDManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private ConsumerManager getConsumerManagerInstance() throws SSOAgentException {

        HttpFetcherFactory httpFetcherFactory = null;
        try {
            httpFetcherFactory = new HttpFetcherFactory(SSLContext.getDefault(), null);
        } catch (NoSuchAlgorithmException e) {
            throw new SSOAgentException("Error while getting default SSL Context", e);
        }
        return new ConsumerManager(
                new RealmVerifierFactory(new YadisResolver(httpFetcherFactory)),
                new Discovery(), httpFetcherFactory);
    }
 
Example #14
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Sign the SAML AuthnRequest message
 *
 * @param authnRequest
 * @param signatureAlgorithm
 * @param cred
 * @return
 * @throws org.wso2.carbon.identity.sso.agent.SSOAgentException
 */
public static AuthnRequest setSignature(AuthnRequest authnRequest, String signatureAlgorithm,
                                    X509Credential cred) throws SSOAgentException {
    doBootstrap();
    try {
        Signature signature = setSignatureRaw(signatureAlgorithm,cred);


        authnRequest.setSignature(signature);

        List<Signature> signatureList = new ArrayList<Signature>();
        signatureList.add(signature);

        // Marshall and Sign
        MarshallerFactory marshallerFactory =
                org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(authnRequest);

        marshaller.marshall(authnRequest);

        org.apache.xml.security.Init.init();
        Signer.signObjects(signatureList);
        return authnRequest;

    } catch (Exception e) {
        throw new SSOAgentException("Error while signing the SAML Request message", e);
    }
}
 
Example #15
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static void doBootstrap() throws SSOAgentException {
    if (!isBootStrapped) {
        try {
            DefaultBootstrap.bootstrap();
            isBootStrapped = true;
        } catch (ConfigurationException e) {
            throw new SSOAgentException("Error in bootstrapping the OpenSAML2 library", e);
        }
    }
}
 
Example #16
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected LogoutRequest buildLogoutRequest(String user, String sessionIdx) throws SSOAgentException {

        LogoutRequest logoutReq = new LogoutRequestBuilder().buildObject();

        logoutReq.setID(SSOAgentUtils.createID());
        logoutReq.setDestination(ssoAgentConfig.getSAML2().getIdPURL());

        DateTime issueInstant = new DateTime();
        logoutReq.setIssueInstant(issueInstant);
        logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject();
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());
        logoutReq.setIssuer(issuer);

        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
        nameId.setValue(user);
        logoutReq.setNameID(nameId);

        SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
        sessionIndex.setSessionIndex(sessionIdx);
        logoutReq.getSessionIndexes().add(sessionIndex);

        logoutReq.setReason("Single Logout");

        return logoutReq;
    }
 
Example #17
Source File: SSOAgentX509KeyStoreCredential.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public SSOAgentX509KeyStoreCredential(InputStream keyStoreInputStream, char[] keyStorePassword,
                                      String publicCertAlias, String privateKeyAlias,
                                      char[] privateKeyPassword)
        throws SSOAgentException {

    readX509Credentials(keyStoreInputStream, keyStorePassword, publicCertAlias,
            privateKeyAlias, privateKeyPassword);
}
 
Example #18
Source File: SSOAgentCarbonX509Credential.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public SSOAgentCarbonX509Credential(int tenantId, String tenantDomain)
        throws SSOAgentException {

    readCarbonX509Credentials(tenantId, tenantDomain);
}
 
Example #19
Source File: SSOAgentX509KeyStoreCredential.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public PublicKey getPublicKey() throws SSOAgentException {
    return publicKey;
}
 
Example #20
Source File: OpenIDManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public OpenIDManager(SSOAgentConfig ssoAgentConfig) throws SSOAgentException {
    SSOAgentDataHolder.getInstance().setConsumerManager(getConsumerManagerInstance());
    this.ssoAgentConfig = ssoAgentConfig;
}
 
Example #21
Source File: SSOAgentConfig.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public void verifyConfig() throws SSOAgentException {

        if (isSAML2SSOLoginEnabled && saml2SSOURL == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.SAML2_SSO_URL + "\' not configured");
        }

        if (isOpenIdLoginEnabled && openIdURL == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.OPENID_URL + "\' not configured");
        }

        if (!isSAML2SSOLoginEnabled && isOAuth2SAML2GrantEnabled) {
            throw new SSOAgentException(
                    "SAML2 SSO Login is disabled. Cannot use SAML2 Bearer Grant type for OAuth2");
        }

        if (isSAML2SSOLoginEnabled && isOAuth2SAML2GrantEnabled && oauth2SAML2GrantURL == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.OAUTH2_SAML2_GRANT_URL + "\' not configured");
        }

        if (isSAML2SSOLoginEnabled && saml2.spEntityId == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.SAML2.SP_ENTITY_ID + "\' not configured");
        }

        if (isSAML2SSOLoginEnabled && saml2.acsURL == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.SAML2.ACS_URL + "\' not configured");
        }

        if (isSAML2SSOLoginEnabled && saml2.idPEntityId == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.SAML2.IDP_ENTITY_ID + "\' not configured");
        }

        if (isSAML2SSOLoginEnabled && saml2.idPURL == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.SAML2.IDP_URL + "\' not configured");
        }

        if (isSAML2SSOLoginEnabled && saml2.attributeConsumingServiceIndex == null) {
            LOGGER.log(Level.FINE,
                    "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.ATTRIBUTE_CONSUMING_SERVICE_INDEX +
                            "\' not configured. " + "No attributes of the Subject will be requested");
        }

        if (isSAML2SSOLoginEnabled && saml2.isSLOEnabled && saml2.sloURL == null) {
            throw new SSOAgentException("Single Logout enabled, but SLO URL not configured");
        }

        if (isSAML2SSOLoginEnabled &&
                (saml2.isAssertionSigned || saml2.isAssertionEncrypted || saml2.isResponseSigned ||
                        saml2.isRequestSigned) && saml2.ssoAgentX509Credential == null) {
            LOGGER.log(Level.FINE,
                    "\'SSOAgentX509Credential\' not configured. Defaulting to " +
                            SSOAgentCarbonX509Credential.class.getName());
        }

        if (isSAML2SSOLoginEnabled &&
                (saml2.isAssertionSigned || saml2.isResponseSigned) &&
                saml2.ssoAgentX509Credential.getEntityCertificate() == null) {
            throw new SSOAgentException("Public certificate of IdP not configured");
        }

        if (isSAML2SSOLoginEnabled &&
                (saml2.isRequestSigned || saml2.isAssertionEncrypted) &&
                saml2.ssoAgentX509Credential.getPrivateKey() == null) {
            throw new SSOAgentException("Private key of SP not configured");
        }

        if (isOpenIdLoginEnabled && openId.providerURL == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.OpenID.PROVIDER_URL + "\' not configured");
        }

        if (isOpenIdLoginEnabled && openId.returnToURL == null) {
            throw new SSOAgentException("\'" +
                    SSOAgentConstants.SSOAgentConfig.OpenID.RETURN_TO_URL + "\' not configured");
        }

        if (isOpenIdLoginEnabled && openId.attributesRequestor == null) {
            LOGGER.log(Level.FINE, "\'" +
                    SSOAgentConstants.SSOAgentConfig.OpenID.PROVIDER_URL +
                    "\' not configured. " + "No attributes of the Subject will be fetched");
        }

        if (isSAML2SSOLoginEnabled && isOAuth2SAML2GrantEnabled && oauth2.tokenURL == null) {
            throw new SSOAgentException("OAuth2 Token endpoint not configured");
        }

        if (isSAML2SSOLoginEnabled && isOAuth2SAML2GrantEnabled && oauth2.clientId == null) {
            throw new SSOAgentException("OAuth2 Client Id not configured");
        }

        if (isSAML2SSOLoginEnabled && isOAuth2SAML2GrantEnabled && oauth2.clientSecret == null) {
            throw new SSOAgentException("OAuth2 Client Secret not configured");
        }

    }
 
Example #22
Source File: SSOAgentConfig.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public KeyStore getKeyStore() throws org.wso2.carbon.identity.sso.agent.exception.SSOAgentException {
    if (keyStore == null) {
        setKeyStore(readKeyStore(getKeyStoreStream(), getKeyStorePassword()));
    }
    return keyStore;
}
 
Example #23
Source File: SSOAgentX509KeyStoreCredential.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public PrivateKey getPrivateKey() throws SSOAgentException {
    return privateKey;
}
 
Example #24
Source File: SSOAgentX509KeyStoreCredential.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public X509Certificate getEntityCertificate() throws SSOAgentException {
    return entityCertificate;
}
 
Example #25
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Handles the request for http post binding
 *
 * @param request  The HTTP request with SAML2 message
 * @param response The HTTP response
 * @param isLogout Whether the request is a logout request
 * @throws SSOAgentException
 */
public String buildPostRequest(HttpServletRequest request, HttpServletResponse response,
                               boolean isLogout) throws SSOAgentException {

    RequestAbstractType requestMessage = null;
    if (!isLogout) {
        requestMessage = buildAuthnRequest(request);
        if (ssoAgentConfig.getSAML2().isRequestSigned()) {
            requestMessage = SSOAgentUtils.setSignature((AuthnRequest) requestMessage,
                    XMLSignature.ALGO_ID_SIGNATURE_RSA,
                    new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential()));
        }

    } else {
        LoggedInSessionBean sessionBean = (LoggedInSessionBean) request.getSession(false).
                getAttribute(SSOAgentConstants.SESSION_BEAN_NAME);
        if (sessionBean != null) {
            requestMessage = buildLogoutRequest(sessionBean.getSAML2SSO()
                    .getSubjectId(), sessionBean.getSAML2SSO().getSessionIndex());
            if (ssoAgentConfig.getSAML2().isRequestSigned()) {
                requestMessage = SSOAgentUtils.setSignature((LogoutRequest) requestMessage,
                        XMLSignature.ALGO_ID_SIGNATURE_RSA,
                        new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential()));
            }
        } else {
            throw new SSOAgentException("SLO Request can not be built. SSO Session is null");
        }
    }
    String encodedRequestMessage = encodeRequestMessage(requestMessage, SAMLConstants.SAML2_POST_BINDING_URI);

    Map<String, String[]> paramsMap = new HashMap<String, String[]>();
    paramsMap.put(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ,
            new String[]{encodedRequestMessage});
    if (ssoAgentConfig.getSAML2().getRelayState() != null) {
        paramsMap.put(RelayState.DEFAULT_ELEMENT_LOCAL_NAME,
                new String[]{ssoAgentConfig.getSAML2().getRelayState()});
    }

    //Add any additional parameters defined
    if (ssoAgentConfig.getQueryParams() != null && !ssoAgentConfig.getQueryParams().isEmpty()) {
        paramsMap.putAll(ssoAgentConfig.getQueryParams());
    }

    StringBuilder htmlParams = new StringBuilder();
    for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {
        if (entry.getKey() != null && entry.getValue() != null && entry.getValue().length > 0) {
            for (String param : entry.getValue()) {
                htmlParams.append("<input type='hidden' name='").append(entry.getKey())
                        .append("' value='").append(param).append("'>\n");
            }
        }

    }
    String htmlPayload = ssoAgentConfig.getSAML2().getPostBindingRequestHTMLPayload();
    if (htmlPayload == null || !htmlPayload.contains("<!--$saml_params-->")) {
        htmlPayload = "<html>\n" +
                "<body>\n" +
                "<p>You are now redirected back to " + ssoAgentConfig.getSAML2().getIdPURL() + " \n" +
                "If the redirection fails, please click the post button.</p>\n" +
                "<form method='post' action='" + ssoAgentConfig.getSAML2().getIdPURL() + "'>\n" +
                "<p>\n" +
                htmlParams.toString() +
                "<button type='submit'>POST</button>\n" +
                "</p>\n" +
                "</form>\n" +
                "<script type='text/javascript'>\n" +
                "document.forms[0].submit();\n" +
                "</script>\n" +
                "</body>\n" +
                "</html>";
    } else {
        htmlPayload = htmlPayload.replace("<!--$saml_params-->",
                htmlParams.toString());
    }
    return htmlPayload;

}
 
Example #26
Source File: X509CredentialImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public X509CredentialImpl(SSOAgentX509Credential credential) throws SSOAgentException {
    publicKey = credential.getPublicKey();
    this.entityCertificate = credential.getEntityCertificate();
    this.privateKey = credential.getPrivateKey();
}
 
Example #27
Source File: SSOAgentX509KeyStoreCredential.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public SSOAgentX509KeyStoreCredential(KeyStore keyStore, String publicCertAlias,
                                      String privateKeyAlias, char[] privateKeyPassword)
        throws SSOAgentException {

    readX509Credentials(keyStore, publicCertAlias, privateKeyAlias, privateKeyPassword);
}
 
Example #28
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected AuthnRequest buildAuthnRequest(HttpServletRequest request) throws SSOAgentException {

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer =
                issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "Issuer", "samlp");
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());

		/* NameIDPolicy */
        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
        nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
        nameIdPolicy.setSPNameQualifier("Issuer");
        nameIdPolicy.setAllowCreate(true);

		/* AuthnContextClass */
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef =
                authnContextClassRefBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "AuthnContextClassRef",
                        "saml");
        authnContextClassRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

		/* AuthnContex */
        RequestedAuthnContextBuilder requestedAuthnContextBuilder =
                new RequestedAuthnContextBuilder();
        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

        DateTime issueInstant = new DateTime();

		/* Creation of AuthRequestObject */
        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
        AuthnRequest authRequest =
                authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
                        "AuthnRequest", "samlp");

        authRequest.setForceAuthn(ssoAgentConfig.getSAML2().isForceAuthn());
        authRequest.setIsPassive(ssoAgentConfig.getSAML2().isPassiveAuthn());
        authRequest.setIssueInstant(issueInstant);
        authRequest.setProtocolBinding(ssoAgentConfig.getSAML2().getHttpBinding());
        authRequest.setAssertionConsumerServiceURL(ssoAgentConfig.getSAML2().getACSURL());
        authRequest.setIssuer(issuer);
        authRequest.setNameIDPolicy(nameIdPolicy);
        authRequest.setRequestedAuthnContext(requestedAuthnContext);
        authRequest.setID(SSOAgentUtils.createID());
        authRequest.setVersion(SAMLVersion.VERSION_20);
        authRequest.setDestination(ssoAgentConfig.getSAML2().getIdPURL());
        if (request.getAttribute(Extensions.LOCAL_NAME) != null) {
            authRequest.setExtensions((Extensions) request.getAttribute(Extensions.LOCAL_NAME));
        }

		/* Requesting Attributes. This Index value is registered in the IDP */
        if (ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex() != null &&
                ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex().trim().length() > 0) {
            authRequest.setAttributeConsumingServiceIndex(Integer.parseInt(
                    ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex()));
        }

        return authRequest;
    }
 
Example #29
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the redirection URL with the appended SAML2
 * Request message
 *
 * @param request SAML 2 request
 * @return redirectionUrl
 */
public String buildRedirectRequest(HttpServletRequest request, boolean isLogout) throws SSOAgentException {

    RequestAbstractType requestMessage = null;
    if (!isLogout) {
        requestMessage = buildAuthnRequest(request);
    } else {
        LoggedInSessionBean sessionBean = (LoggedInSessionBean) request.getSession(false).
                getAttribute(SSOAgentConstants.SESSION_BEAN_NAME);
        if (sessionBean != null) {
            requestMessage = buildLogoutRequest(sessionBean.getSAML2SSO().getSubjectId(),
                    sessionBean.getSAML2SSO().getSessionIndex());
        } else {
            throw new SSOAgentException("SLO Request can not be built. SSO Session is NULL");
        }
    }
    String idpUrl = null;

    String encodedRequestMessage = encodeRequestMessage(
            requestMessage, SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    StringBuilder httpQueryString = new StringBuilder(
            SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ +
                    "=" + encodedRequestMessage);

    String relayState = ssoAgentConfig.getSAML2().getRelayState();
    if (relayState != null) {
        try {
            httpQueryString.append("&" + RelayState.DEFAULT_ELEMENT_LOCAL_NAME + "=" +
                    URLEncoder.encode(relayState, "UTF-8").trim());
        } catch (UnsupportedEncodingException e) {
            throw new SSOAgentException("Error occurred while URLEncoding " +
                    RelayState.DEFAULT_ELEMENT_LOCAL_NAME, e);
        }
    }

    if (ssoAgentConfig.getSAML2().isRequestSigned()) {
        SSOAgentUtils.addDeflateSignatureToHTTPQueryString(httpQueryString,
                new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential()));
    }

    if (ssoAgentConfig.getQueryParams() != null && !ssoAgentConfig.getQueryParams().isEmpty()) {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String[]> entry : ssoAgentConfig.getQueryParams().entrySet()) {
            if (entry.getKey() != null && entry.getValue() != null && entry.getValue().length > 0) {
                for (String param : entry.getValue()) {
                    builder.append("&").append(entry.getKey()).append("=").append(param);
                }
            }
        }
        httpQueryString.append(builder);
    }



    if (ssoAgentConfig.getSAML2().getIdPURL().indexOf("?") > -1) {
        idpUrl = ssoAgentConfig.getSAML2().getIdPURL().concat("&").concat(httpQueryString.toString());
    } else {
        idpUrl = ssoAgentConfig.getSAML2().getIdPURL().concat("?").concat(httpQueryString.toString());
    }
    return idpUrl;
}
 
Example #30
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void processSSOResponse(HttpServletRequest request) throws SSOAgentException {

        LoggedInSessionBean sessionBean = new LoggedInSessionBean();
        sessionBean.setSAML2SSO(sessionBean.new SAML2SSO());

        String saml2ResponseString =
                new String(Base64.decode(request.getParameter(
                        SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP)), Charset.forName("UTF-8"));
        Response saml2Response = (Response) SSOAgentUtils.unmarshall(saml2ResponseString);
        sessionBean.getSAML2SSO().setResponseString(saml2ResponseString);
        sessionBean.getSAML2SSO().setSAMLResponse(saml2Response);

        Assertion assertion = null;
        if (ssoAgentConfig.getSAML2().isAssertionEncrypted()) {
            List<EncryptedAssertion> encryptedAssertions = saml2Response.getEncryptedAssertions();
            EncryptedAssertion encryptedAssertion = null;
            if (!CollectionUtils.isEmpty(encryptedAssertions)) {
                encryptedAssertion = encryptedAssertions.get(0);
                try {
                    assertion = getDecryptedAssertion(encryptedAssertion);
                } catch (Exception e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Assertion decryption failure : ", e);
                    }
                    throw new SSOAgentException("Unable to decrypt the SAML2 Assertion");
                }
            }
        } else {
            List<Assertion> assertions = saml2Response.getAssertions();
            if (assertions != null && !assertions.isEmpty()) {
                assertion = assertions.get(0);
            }
        }
        if (assertion == null) {
            if (isNoPassive(saml2Response)) {
                LOGGER.log(Level.FINE, "Cannot authenticate in passive mode");
                return;
            }
            throw new SSOAgentException("SAML2 Assertion not found in the Response");
        }

        String idPEntityIdValue = assertion.getIssuer().getValue();
        if (idPEntityIdValue == null || idPEntityIdValue.isEmpty()) {
            throw new SSOAgentException("SAML2 Response does not contain an Issuer value");
        } else if (!idPEntityIdValue.equals(ssoAgentConfig.getSAML2().getIdPEntityId())) {
            throw new SSOAgentException("SAML2 Response Issuer verification failed");
        }
        sessionBean.getSAML2SSO().setAssertion(assertion);
        // Cannot marshall SAML assertion here, before signature validation due to a weird issue in OpenSAML

        // Get the subject name from the Response Object and forward it to login_action.jsp
        String subject = null;
        if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
            subject = assertion.getSubject().getNameID().getValue();
        }

        if (subject == null) {
            throw new SSOAgentException("SAML2 Response does not contain the name of the subject");
        }


        sessionBean.getSAML2SSO().setSubjectId(subject); // set the subject
        request.getSession().setAttribute(SSOAgentConstants.SESSION_BEAN_NAME, sessionBean);

        // validate audience restriction
        validateAudienceRestriction(assertion);

        // validate signature
        validateSignature(saml2Response, assertion);

        // Marshalling SAML2 assertion after signature validation due to a weird issue in OpenSAML
        sessionBean.getSAML2SSO().setAssertionString(marshall(assertion));

        ((LoggedInSessionBean) request.getSession().getAttribute(
                SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().
                setSubjectAttributes(getAssertionStatements(assertion));

        //For removing the session when the single sign out request made by the SP itself
        if (ssoAgentConfig.getSAML2().isSLOEnabled()) {
            String sessionId = assertion.getAuthnStatements().get(0).getSessionIndex();
            if (sessionId == null) {
                throw new SSOAgentException("Single Logout is enabled but IdP Session ID not found in SAML2 Assertion");
            }
            ((LoggedInSessionBean) request.getSession().getAttribute(
                    SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().setSessionIndex(sessionId);
            SSOAgentSessionManager.addAuthenticatedSession(request.getSession(false));
        }

        request.getSession().setAttribute(SSOAgentConstants.SESSION_BEAN_NAME, sessionBean);

    }