diff --git a/.gitignore b/.gitignore index e100e3e..29bd2a8 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ *.iws *.ipr .idea +*.DS_Store # Mobile Tools for Java (J2ME) .mtj.tmp/ diff --git a/components/org.wso2.carbon.identity.sso.agent/pom.xml b/components/org.wso2.carbon.identity.sso.agent/pom.xml deleted file mode 100644 index 3a05cb3..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/pom.xml +++ /dev/null @@ -1,180 +0,0 @@ - - - - - - org.wso2.carbon.identity.agent.sso.java - identity-agent-sso - ../../pom.xml - 5.5.9-SNAPSHOT - - - 4.0.0 - org.wso2.carbon.identity.sso.agent - bundle - WSO2 Carbon - SAML2-OpenID SSO Agent - http://www.wso2.com - - - - org.bouncycastle - bcprov-jdk15on - - - commons-collections.wso2 - commons-collections - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.core - provided - true - - - org.wso2.carbon - org.wso2.carbon.logging - - - - - org.wso2.carbon.identity.saml.common - org.wso2.carbon.identity.saml.common.util - - - org.wso2.orbit.org.opensaml - opensaml - - - org.bouncycastle - bcprov-ext-jdk15 - - - org.wso2.orbit.joda-time - joda-time - - - - - org.ops4j.pax.logging - pax-logging-api - ${pax.logging.api.version} - - - org.wso2.orbit.joda-time - joda-time - - - org.openid4java - openid4java - - - javax.servlet - javax.servlet-api - - - org.apache.oltu.oauth2 - org.apache.oltu.oauth2.client - - - com.google.code.gson - gson - - - org.wso2.orbit.org.owasp.encoder - encoder - - - org.wso2.apache.httpcomponents - httpclient - - - org.apache.felix - org.apache.felix.scr.ds-annotations - provided - - - - - src/main/java - - - org.apache.felix - maven-scr-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - 2.0 - - 1.8 - 1.8 - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - - org.wso2.carbon.identity.sso.agent.internal, - - - javax.crypto, - javax.net.ssl, - javax.servlet;version="${imp.pkg.version.javax.servlet}", - javax.servlet.http;version="${imp.pkg.version.javax.servlet}", - javax.xml.namespace, - javax.xml.parsers; version="${javax.xml.parsers.import.pkg.version}", - com.google.gson;version="${com.google.code.gson.osgi.version.range}", - org.apache.http.conn.ssl; version="${httpcomponents-httpclient.imp.pkg.version.range}", - org.apache.xerces.util;resolution:=optional, - org.apache.xerces.impl;resolution:=optional, - org.apache.xml.security.*; version="${wss4j.xml.security.imp.pkg.version.range}", - org.joda.time;version="${joda.wso2.osgi.version.range}", - org.openid4java.*;version="${openid4java.wso2.osgi.version.range}";resolution:=optional, - org.opensaml.*; version="${opensaml2.wso2.osgi.version.range}", - net.shibboleth.utilities.java.support.*; version="${opensaml2.wso2.osgi.version.range}", - org.w3c.dom.*, - org.xml.sax, - org.wso2.carbon.core.util; version="${carbon.kernel.package.import.version.range}", - org.wso2.carbon.user.core.*; version="${carbon.kernel.package.import.version.range}", - org.wso2.carbon.user.api; version="${carbon.user.api.imp.pkg.version.range}", - org.wso2.carbon.identity.core.util; - version="${identity.framework.import.version.range}", - org.wso2.carbon.identity.saml.common.util.*; version="${saml.common.util.version.range}", - org.apache.commons.collections; version="${commons-collections.wso2.osgi.version.range}", - org.bouncycastle.*; version="[1.60, 2.0.0)", - - - !org.wso2.carbon.identity.sso.agent.internal, - org.wso2.carbon.identity.sso.agent.*; version="${identity.sso.agent.package.export.version}", - - * - - - - - - - diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/AESDecryptor.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/AESDecryptor.java deleted file mode 100644 index 41b534b..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/AESDecryptor.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent; - -import org.apache.commons.codec.binary.Base64; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; -import org.bouncycastle.crypto.params.KeyParameter; - -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.StandardCharsets; -import javax.crypto.Cipher; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; - -/** - * Class for decrypt the encrypted values using AES algorithm. - */ -public class AESDecryptor { - - private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; - private static final String SALT = "84B03D034B409D4E"; - private static final int KEY_DERIVATION_ITERATION_COUNT = 4096; - private static final int KEY_SIZE = 128; - - /** - * Decrypt and decrypt the encrypted values. - * - * @param encryptedSecret encrypted value. - * @param cipherKey password used for encryption. - * @return - * @throws SSOAgentException If an error occurred. - */ - public static String decrypt(String encryptedSecret, char[] cipherKey) throws SSOAgentException { - - try { - - // Change char array to byte array. - ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(cipherKey)); - byte[] secretKey = new byte[buf.limit()]; - buf.get(secretKey); - - PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); - gen.init(secretKey, SALT.getBytes(StandardCharsets.UTF_8), KEY_DERIVATION_ITERATION_COUNT); - byte[] dk = ((KeyParameter) gen.generateDerivedParameters(KEY_SIZE)).getKey(); - - SecretKey key = new SecretKeySpec(dk, "AES"); - Cipher cipher = Cipher.getInstance(ALGORITHM); - - // Create an initialization vector with Cipher's block size. - byte[] iv = new byte[cipher.getBlockSize()]; - IvParameterSpec ivParams = new IvParameterSpec(iv); - cipher.init(Cipher.DECRYPT_MODE, key, ivParams); - - // Decode the encrypted value. - byte[] decodedValue = new Base64().decode(encryptedSecret.getBytes(StandardCharsets.UTF_8)); - - // Decrypt the encrypted value and get the plain text password. - byte[] decryptedValue = cipher.doFinal(decodedValue); - return new String(decryptedValue, StandardCharsets.UTF_8); - } catch (Exception ex) { - throw new SSOAgentException("Error while decoding the encrypted value.", ex); - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/OIDCSSOAgentFilter.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/OIDCSSOAgentFilter.java deleted file mode 100644 index 0742beb..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/OIDCSSOAgentFilter.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent; - -/** - * @deprecated Please use {@link org.wso2.carbon.identity.sso.agent.OpenIdSSOAgentFilter} instead. - */ -@Deprecated -public class OIDCSSOAgentFilter extends OpenIdSSOAgentFilter { -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/OpenIdSSOAgentFilter.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/OpenIdSSOAgentFilter.java deleted file mode 100644 index 1f7c7e6..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/OpenIdSSOAgentFilter.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent; - -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.exception.InvalidSessionException; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.openid.OpenIDManager; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentFilterUtils; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentRequestResolver; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Servlet Filter implementation class OpenIdSSOAgentFilter. - */ -public class OpenIdSSOAgentFilter implements Filter { - - private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); - protected FilterConfig filterConfig = null; - - /** - * @see Filter#init(FilterConfig) - */ - @Override - public void init(FilterConfig fConfig) throws ServletException { - this.filterConfig = fConfig; - } - - /** - * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) - */ - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, - FilterChain chain) throws IOException, ServletException { - - HttpServletRequest request = (HttpServletRequest) servletRequest; - HttpServletResponse response = (HttpServletResponse) servletResponse; - - try { - SSOAgentConfig ssoAgentConfig = SSOAgentFilterUtils.getSSOAgentConfig(filterConfig); - - SSOAgentRequestResolver resolver = - new SSOAgentRequestResolver(request, response, ssoAgentConfig); - - if (resolver.isURLToSkip()) { - chain.doFilter(servletRequest, servletResponse); - return; - } - - OpenIDManager openIdManager; - - if (resolver.isOpenIdLoginResponse()) { - - openIdManager = new OpenIDManager(ssoAgentConfig); - try { - openIdManager.processOpenIDLoginResponse(request, response); - } catch (SSOAgentException e) { - handleException(request, e); - } - - } else if (resolver.isOpenIdURL()) { - - openIdManager = new OpenIDManager(ssoAgentConfig); - response.sendRedirect(openIdManager.doOpenIDLogin(request, response)); - return; - } - - // pass the request along the filter chain - chain.doFilter(request, response); - - } catch (InvalidSessionException e) { - // Redirect to the index page when session is expired or user already logged out. - request.setAttribute(SSOAgentConstants.SHOULD_GO_TO_WELCOME_PAGE, "true"); - - // pass the request along the filter chain - chain.doFilter(request, response); - } catch (SSOAgentException e) { - throw e; - } - } - - /** - * @see Filter#destroy() - */ - @Override - public void destroy() { - return; - } - - protected void handleException(HttpServletRequest request, SSOAgentException e) - throws SSOAgentException { - - if (request.getSession(false) != null) { - request.getSession(false).removeAttribute(SSOAgentConstants.SESSION_BEAN_NAME); - } - throw e; - } - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SAML2SSOAgentFilter.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SAML2SSOAgentFilter.java deleted file mode 100644 index 4efea57..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SAML2SSOAgentFilter.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent; - -import org.opensaml.saml.saml2.core.LogoutResponse; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.exception.InvalidSessionException; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.oauth2.SAML2GrantManager; -import org.wso2.carbon.identity.sso.agent.openid.OpenIDManager; -import org.wso2.carbon.identity.sso.agent.saml.SAML2SSOManager; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentFilterUtils; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentRequestResolver; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentUtils; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Servlet Filter implementation class SAML2SSOAgentFilter. - */ -public class SAML2SSOAgentFilter implements Filter { - - private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); - protected FilterConfig filterConfig = null; - - /** - * @see Filter#init(FilterConfig) - */ - @Override - public void init(FilterConfig fConfig) throws ServletException { - this.filterConfig = fConfig; - } - - /** - * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) - */ - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, - FilterChain chain) throws IOException, ServletException { - - HttpServletRequest request = (HttpServletRequest) servletRequest; - HttpServletResponse response = (HttpServletResponse) servletResponse; - - try { - SSOAgentConfig ssoAgentConfig = SSOAgentFilterUtils.getSSOAgentConfig(filterConfig); - - SSOAgentRequestResolver resolver = - new SSOAgentRequestResolver(request, response, ssoAgentConfig); - - if (resolver.isURLToSkip()) { - chain.doFilter(servletRequest, servletResponse); - return; - } - - SAML2SSOManager samlSSOManager; - SAML2GrantManager saml2GrantManager; - - if (resolver.isSLORequest()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - LogoutResponse logoutResponse = samlSSOManager.doSLO(request); - String encodedRequestMessage = samlSSOManager.buildPostResponse(logoutResponse); - SSOAgentUtils.sendPostResponse(request, response, encodedRequestMessage); - return; - } else if (resolver.isSAML2SSOResponse()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - try { - samlSSOManager.processResponse(request, response); - } catch (SSOAgentException e) { - handleException(request, e); - } - - } else if (resolver.isSAML2ArtifactResponse()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - try { - samlSSOManager.processArtifactResponse(request); - } catch (SSOAgentException e) { - handleException(request, e); - } - } else if (resolver.isOpenIdLoginResponse()) { - - OpenIDManager openIdManager = new OpenIDManager(ssoAgentConfig); - try { - openIdManager.processOpenIDLoginResponse(request, response); - } catch (SSOAgentException e) { - handleException(request, e); - } - - } else if (resolver.isSLOURL()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - if (resolver.isHttpPostBinding()) { - - boolean isPassiveAuth = ssoAgentConfig.getSAML2().isPassiveAuthn(); - ssoAgentConfig.getSAML2().setPassiveAuthn(false); - String htmlPayload = samlSSOManager.buildPostRequest(request, response, true); - ssoAgentConfig.getSAML2().setPassiveAuthn(isPassiveAuth); - SSOAgentUtils.sendPostResponse(request, response, htmlPayload); - - } else { - //if "SSOAgentConstants.HTTP_BINDING_PARAM" is not defined, default to redirect - boolean isPassiveAuth = ssoAgentConfig.getSAML2().isPassiveAuthn(); - ssoAgentConfig.getSAML2().setPassiveAuthn(false); - String redirectUrl = samlSSOManager.buildRedirectRequest(request, true); - ssoAgentConfig.getSAML2().setPassiveAuthn(isPassiveAuth); - response.sendRedirect(redirectUrl); - } - return; - - } else if (resolver.isSAML2SSOURL()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - if (resolver.isHttpPostBinding()) { - String htmlPayload = samlSSOManager.buildPostRequest(request, response, false); - SSOAgentUtils.sendPostResponse(request, response, htmlPayload); - return; - } - response.sendRedirect(samlSSOManager.buildRedirectRequest(request, false)); - return; - - } else if (resolver.isPassiveAuthnRequest()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - boolean isPassiveAuth = ssoAgentConfig.getSAML2().isPassiveAuthn(); - ssoAgentConfig.getSAML2().setPassiveAuthn(true); - String redirectUrl = samlSSOManager.buildRedirectRequest(request, false); - ssoAgentConfig.getSAML2().setPassiveAuthn(isPassiveAuth); - response.sendRedirect(redirectUrl); - return; - - } else if (resolver.isSAML2OAuth2GrantRequest()) { - - saml2GrantManager = new SAML2GrantManager(ssoAgentConfig); - saml2GrantManager.getAccessToken(request, response); - - } - - // pass the request along the filter chain - chain.doFilter(request, response); - - } catch (InvalidSessionException e) { - // Redirect to the index page when session is expired or user already logged out. - LOGGER.log(Level.FINE, "Invalid Session!", e); - response.sendRedirect(filterConfig.getServletContext().getContextPath()); - } - } - - - /** - * @see Filter#destroy() - */ - @Override - public void destroy() { - return; - } - - protected void handleException(HttpServletRequest request, SSOAgentException e) - throws SSOAgentException { - - if (request.getSession(false) != null) { - request.getSession(false).removeAttribute(SSOAgentConstants.SESSION_BEAN_NAME); - } - throw e; - } - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SSOAgentConstants.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SSOAgentConstants.java deleted file mode 100644 index ee1a32b..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SSOAgentConstants.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent; - -/** - * @deprecated This class is duplicated by {@link org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants} - */ -@Deprecated -public class SSOAgentConstants { - - public static final String LOGGER_NAME = "org.wso2.carbon.identity.sso.agent"; - - public static final String SESSION_BEAN_NAME = - - "org.wso2.carbon.identity.sso.agent.LoggedInSessionBean"; - public static final String CONFIG_BEAN_NAME = "org.wso2.carbon.identity.sso.agent.SSOAgentConfig"; - - public static class SAML2SSO { - - public static final String SUCCESS_CODE = "urn:oasis:names:tc:SAML:2.0:status:Success"; - - private SAML2SSO() { - } - - public static final String HTTP_POST_PARAM_SAML2_AUTH_REQ = "SAMLRequest"; - public static final String HTTP_POST_PARAM_SAML2_RESP = "SAMLResponse"; - } - - public static class OpenID { - - public static final String OPENID_MODE = "openid.mode"; - private OpenID() { - } - - } - - public static class OAuth2 { - public static final String SAML2_BEARER_GRANT_TYPE = - "urn:ietf:params:oauth:grant-type:saml2-bearer"; - - private OAuth2() { - } - } - - private SSOAgentConstants() { - } - - public static class SSOAgentConfig { - - public static final String ENABLE_SAML2_SSO_LOGIN = "EnableSAML2SSOLogin"; - public static final String ENABLE_OPENID_SSO_LOGIN = "EnableOpenIDLogin"; - public static final String ENABLE_OAUTH2_SAML2_OAUTH2_GRANT = "EnableOAuth2SAML2Grant"; - public static final String SAML2_SSO_URL = "SAML2SSOURL"; - public static final String OPENID_URL = "OpenIdURL"; - public static final String OAUTH2_SAML2_GRANT_URL = "OAuth2SAML2GrantURL"; - public static final String SKIP_URIS = "SkipURIs"; - public static final String QUERY_PARAMS = "QueryParams"; - public static final String PASSWORD_FILEPATH = "/conf/password_temp.txt"; - - private SSOAgentConfig() { - } - - public static class SAML2 { - - public static final String HTTP_BINDING = "SAML2.HTTPBinding"; - public static final String SP_ENTITY_ID = "SAML2.SPEntityId"; - public static final String ACS_URL = "SAML2.AssertionConsumerURL"; - public static final String IDP_ENTITY_ID = "SAML2.IdPEntityId"; - public static final String IDP_URL = "SAML2.IdPURL"; - public static final String ATTRIBUTE_CONSUMING_SERVICE_INDEX = - "SAML2.AttributeConsumingServiceIndex"; - public static final String ENABLE_SLO = "SAML2.EnableSLO"; - public static final String SLO_URL = "SAML2.SLOURL"; - public static final String ENABLE_ASSERTION_SIGNING = - "SAML2.EnableAssertionSigning"; - public static final String ENABLE_ASSERTION_ENCRYPTION = - "SAML2.EnableAssertionEncryption"; - public static final String ENABLE_RESPONSE_SIGNING = - "SAML2.EnableResponseSigning"; - public static final String ENABLE_REQUEST_SIGNING = "SAML2.EnableRequestSigning"; - public static final String IS_PASSIVE_AUTHN = "SAML2.IsPassiveAuthn"; - public static final String IS_FORCE_AUTHN = "SAML2.IsForceAuthn"; - public static final String RELAY_STATE = "SAML2.RelayState"; - public static final String POST_BINDING_REQUEST_HTML_PAYLOAD = - "SAML2.PostBindingRequestHTMLPayload"; - public static final String POST_BINDING_REQUEST_HTML_FILE_PATH = - "SAML2.PostBindingRequestHTMLFilePath"; - public static final String SIGNATURE_VALIDATOR = "SAML2.SignatureValidatorImplClass"; - public static final String TIME_STAMP_SKEW = "SAML2.TimestampSkew"; - - private SAML2() { - } - } - - public static class OpenID { - - public static final String PROVIDER_URL = "OpenId.ProviderURL"; - public static final String RETURN_TO_URL = "OpenId.ReturnToURL"; - public static final String CLAIMED_ID = "OpenId.ClaimedId"; - public static final String ENABLE_ATTRIBUTE_EXCHANGE = "OpenId.EnableAttributeExchange"; - public static final String ENABLE_DUMB_MODE = "OpenId.EnableDumbMode"; - - private OpenID() { - } - } - - public static class OAuth2 { - - public static final String CLIENT_ID = "OAuth2.ClientId"; - public static final String CLIENT_SECRET = "OAuth2.ClientSecret"; - public static final String TOKEN_URL = "OAuth2.TokenURL"; - - private OAuth2() { - } - } - - } - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SSOAgentContextEventListener.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SSOAgentContextEventListener.java deleted file mode 100644 index 5f0d5fd..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/SSOAgentContextEventListener.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent; - -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.security.SSOAgentX509Credential; -import org.wso2.carbon.identity.sso.agent.security.SSOAgentX509KeyStoreCredential; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -/** - * Context EventListner Class for SAML2 SSO. - */ -public class SSOAgentContextEventListener implements ServletContextListener { - - private static Logger logger = Logger.getLogger(SSOAgentContextEventListener.class.getName()); - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - Properties properties = new Properties(); - try { - - ServletContext servletContext = servletContextEvent.getServletContext(); - - // Load the client property-file, if not specified throw SSOAgentException - String propertyFileName = servletContext.getInitParameter(SSOAgentConstants.PROPERTY_FILE_PARAMETER_NAME); - if (StringUtils.isNotBlank(propertyFileName)) { - properties.load(servletContextEvent.getServletContext(). - getResourceAsStream("/WEB-INF/classes/" + propertyFileName)); - } else { - throw new SSOAgentException(SSOAgentConstants.PROPERTY_FILE_PARAMETER_NAME - + " context-param is not specified in the web.xml"); - } - - // Load the client security certificate, if not specified throw SSOAgentException. - String certificateFileName = servletContext.getInitParameter(SSOAgentConstants - .CERTIFICATE_FILE_PARAMETER_NAME); - InputStream keyStoreInputStream; - if (StringUtils.isNotBlank(certificateFileName)) { - keyStoreInputStream = servletContext.getResourceAsStream("/WEB-INF/classes/" - + certificateFileName); - } else { - throw new SSOAgentException(SSOAgentConstants.CERTIFICATE_FILE_PARAMETER_NAME - + " context-param is not specified in the web.xml"); - } - - SSOAgentX509Credential credential = new SSOAgentX509KeyStoreCredential(keyStoreInputStream, - properties.getProperty(SSOAgentConstants.KEY_STORE_PASSWORD).toCharArray(), - properties.getProperty(SSOAgentConstants.IDP_PUBLIC_CERT), - properties.getProperty(SSOAgentConstants.PRIVATE_KEY_ALIAS), - properties.getProperty(SSOAgentConstants.PRIVATE_KEY_PASSWORD).toCharArray()); - - SSOAgentConfig config = new SSOAgentConfig(); - config.initConfig(properties); - config.getSAML2().setSSOAgentX509Credential(credential); - servletContext.setAttribute(SSOAgentConstants.CONFIG_BEAN_NAME, config); - - } catch (IOException | SSOAgentException e) { - logger.log(Level.SEVERE, e.getMessage(), e); - } - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - - } - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/LoggedInSessionBean.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/LoggedInSessionBean.java deleted file mode 100644 index 22b25ff..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/LoggedInSessionBean.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.bean; - -import com.google.gson.Gson; -import com.google.gson.annotations.SerializedName; -import org.openid4java.discovery.DiscoveryInformation; -import org.opensaml.saml.saml2.core.Assertion; -import org.opensaml.saml.saml2.core.Response; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentUtils; - -import javax.xml.bind.annotation.XmlAttribute; -import java.io.IOException; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -public class LoggedInSessionBean implements Serializable { - - private static final long serialVersionUID = 7762835859870143767L; - - private OpenID openId; - - private SAML2SSO saml2SSO; - - public SAML2SSO getSAML2SSO() { - return saml2SSO; - } - - public void setSAML2SSO(SAML2SSO saml2SSO) { - this.saml2SSO = saml2SSO; - } - - public OpenID getOpenId() { - return openId; - } - - public void setOpenId(OpenID openId) { - this.openId = openId; - } - - public static class AccessTokenResponseBean implements Serializable{ - - @XmlAttribute(name="access_token") - @SerializedName("access_token") - private String accessToken; - - @XmlAttribute(name="refresh_token") - @SerializedName("refresh_token") - private String refreshToken; - - @XmlAttribute(name="token_type") - @SerializedName("token_type") - private String tokenType; - - @XmlAttribute(name="expires_in") - @SerializedName("expires_in") - private String expiresIn; - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public String getRefreshToken() { - return refreshToken; - } - - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - } - - public String getTokenType() { - return tokenType; - } - - public void setTokenType(String tokenType) { - this.tokenType = tokenType; - } - - public String getExpiresIn() { - return expiresIn; - } - - public void setExpiresIn(String expiresIn) { - this.expiresIn = expiresIn; - } - - @Override - public String toString() { - Gson gson = new Gson(); - return gson.toJson(this); - } - - public AccessTokenResponseBean deSerialize(String accessTokenResponseBeanString) { - Gson gson = new Gson(); - return gson.fromJson(accessTokenResponseBeanString, AccessTokenResponseBean.class); - } - } - - public class OpenID implements Serializable { - - private DiscoveryInformation discoveryInformation; - - private String claimedId; - - private Map> subjectAttributes; - - public DiscoveryInformation getDiscoveryInformation() { - return discoveryInformation; - } - - public void setDiscoveryInformation(DiscoveryInformation discoveryInformation) { - this.discoveryInformation = discoveryInformation; - } - - public String getClaimedId() { - return claimedId; - } - - public void setClaimedId(String claimedId) { - this.claimedId = claimedId; - } - - public Map> getSubjectAttributes() { - return subjectAttributes; - } - - public void setSubjectAttributes(Map> subjectAttributes) { - this.subjectAttributes = subjectAttributes; - } - } - - public class SAML2SSO implements Serializable{ - - public static final String EMPTY_STRING = ""; - private String subjectId; - - private Response response; - - private String responseString; - - private Assertion assertion; - - private String assertionString; - - private AccessTokenResponseBean accessTokenResponseBean; - - private String sessionIndex; - - private Map subjectAttributes; - - private void writeObject(java.io.ObjectOutputStream stream) - throws IOException { - - stream.writeObject(subjectId); - - stream.writeObject(responseString); - - stream.writeObject(assertionString); - - stream.writeObject(sessionIndex); - if (accessTokenResponseBean != null) { - stream.writeObject(accessTokenResponseBean.toString()); - } else { - stream.writeObject(EMPTY_STRING); - } - stream.writeObject(subjectAttributes); - } - - 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(); - } - - public String getSubjectId() { - return subjectId; - } - - public void setSubjectId(String subjectId) { - this.subjectId = subjectId; - } - - public Map getSubjectAttributes() { - return subjectAttributes; - } - - public void setSubjectAttributes(Map samlSSOAttributes) { - this.subjectAttributes = samlSSOAttributes; - } - - public String getSessionIndex() { - return sessionIndex; - } - - public void setSessionIndex(String sessionIndex) { - this.sessionIndex = sessionIndex; - } - - public Response getSAMLResponse() { - return response; - } - - public void setSAMLResponse(Response samlResponse) { - this.response = samlResponse; - } - - public String getResponseString() { - return responseString; - } - - public void setResponseString(String responseString) { - this.responseString = responseString; - } - - public Assertion getAssertion() { - return assertion; - } - - public void setAssertion(Assertion samlAssertion) { - this.assertion = samlAssertion; - } - - public String getAssertionString() { - return assertionString; - } - - public void setAssertionString(String samlAssertionString) { - this.assertionString = samlAssertionString; - } - - public AccessTokenResponseBean getAccessTokenResponseBean() { - return accessTokenResponseBean; - } - - public void setAccessTokenResponseBean(AccessTokenResponseBean accessTokenResponseBean) { - this.accessTokenResponseBean = accessTokenResponseBean; - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/SSOAgentConfig.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/SSOAgentConfig.java deleted file mode 100644 index 3f6c941..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/SSOAgentConfig.java +++ /dev/null @@ -1,1110 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.bean; - -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.opensaml.saml.common.xml.SAMLConstants; -import org.wso2.carbon.identity.sso.agent.AESDecryptor; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.openid.AttributesRequestor; -import org.wso2.carbon.identity.sso.agent.security.SSOAgentCarbonX509Credential; -import org.wso2.carbon.identity.sso.agent.security.SSOAgentX509Credential; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.KeyStore; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -public class SSOAgentConfig { - - private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); - private static final String ARGUMENT = "sun.java.command"; - - private Boolean isSAML2SSOLoginEnabled = false; - private Boolean isOpenIdLoginEnabled = false; - private Boolean isOAuth2SAML2GrantEnabled = false; - - private String saml2SSOURL = null; - private String openIdURL = null; - private String oauth2SAML2GrantURL = null; - private Set skipURIs = new HashSet(); - - private Map queryParams = new HashMap(); - - private SAML2 saml2 = new SAML2(); - private OpenID openId = new OpenID(); - private OIDC oidc = new OIDC(); - private OAuth2 oauth2 = new OAuth2(); - private String requestQueryParameters; - private Boolean enableHostNameVerification = false; - private Boolean enableSSLVerification = false; - private InputStream keyStoreStream; - private String keyStorePassword; - private KeyStore keyStore; - private String privateKeyPassword; - private String privateKeyAlias; - private String idpPublicCertAlias; - - public Boolean getEnableHostNameVerification() { - return enableHostNameVerification; - } - - public Boolean getEnableSSLVerification() { - return enableSSLVerification; - } - - public String getRequestQueryParameters() { - return requestQueryParameters; - } - - public Boolean isSAML2SSOLoginEnabled() { - return isSAML2SSOLoginEnabled; - } - - public Boolean isOpenIdLoginEnabled() { - return isOpenIdLoginEnabled; - } - - public Boolean isOAuth2SAML2GrantEnabled() { - return isOAuth2SAML2GrantEnabled; - } - - public String getSAML2SSOURL() { - return saml2SSOURL; - } - - public void setSAML2SSOURL(String saml2SSOURL) { - this.saml2SSOURL = saml2SSOURL; - } - - public String getOpenIdURL() { - return openIdURL; - } - - public void setOpenIdURL(String openIdURL) { - this.openIdURL = openIdURL; - } - - public String getOAuth2SAML2GrantURL() { - return oauth2SAML2GrantURL; - } - - public void setOAuth2SAML2GrantURL(String oauth2SAML2GrantURL) { - this.oauth2SAML2GrantURL = oauth2SAML2GrantURL; - } - - public Set getSkipURIs() { - return skipURIs; - } - - public void setSkipURIs(Set skipURIs) { - this.skipURIs = skipURIs; - } - - public Map getQueryParams() { - return queryParams; - } - - public void setQueryParams(Map queryParams) { - this.queryParams = queryParams; - } - - public SAML2 getSAML2() { - return saml2; - } - - public OAuth2 getOAuth2() { - return oauth2; - } - - public OpenID getOpenId() { - return openId; - } - - public OIDC getOidc() { return oidc; } - - public void setSAML2SSOLoginEnabled(Boolean isSAML2SSOLoginEnabled) { - this.isSAML2SSOLoginEnabled = isSAML2SSOLoginEnabled; - } - - public void setOpenIdLoginEnabled(Boolean isOpenIdLoginEnabled) { - this.isOpenIdLoginEnabled = isOpenIdLoginEnabled; - } - - public void setOAuth2SAML2GrantEnabled(Boolean isOAuth2SAML2GrantEnabled) { - this.isOAuth2SAML2GrantEnabled = isOAuth2SAML2GrantEnabled; - } - - private InputStream getKeyStoreStream() { - return keyStoreStream; - } - - public void setKeyStoreStream(InputStream keyStoreStream) { - if (this.keyStoreStream == null) { - this.keyStoreStream = keyStoreStream; - } - } - - public String getPrivateKeyPassword() { - return privateKeyPassword; - } - - public String getPrivateKeyAlias() { - return privateKeyAlias; - } - - public String getIdPPublicCertAlias() { - return idpPublicCertAlias; - } - - public String getKeyStorePassword() { - return keyStorePassword; - } - - public void setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - } - - public KeyStore getKeyStore() throws org.wso2.carbon.identity.sso.agent.exception.SSOAgentException { - if (keyStore == null) { - setKeyStore(readKeyStore(getKeyStoreStream(), getKeyStorePassword())); - } - return keyStore; - } - - public void setKeyStore(KeyStore keyStore) { - this.keyStore = keyStore; - } - - public void initConfig(Properties properties) throws SSOAgentException { - - String decodedPassword; - boolean isReadpassword = false; - char[] password = null; - - // Get copy of properties for looping in order to avoid ConcurrentModificationException. - Properties copyOfProperties = new Properties(); - copyOfProperties.putAll(properties); - - // Path of the password file. - String filePath = System.getProperty("catalina.home") + SSOAgentConstants.SSOAgentConfig.PASSWORD_FILEPATH; - - // Looping through properties to check the encrypted property value by checking the prefix Enc:. - for (Map.Entry entry : copyOfProperties.entrySet()) { - if (String.valueOf(entry.getValue()).startsWith("Enc:")) { - if (!System.getProperty(ARGUMENT).contains("password")) { - - // Check whether the password has been already read. - if (!isReadpassword) { - Path path = Paths.get(filePath); - try (BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"))) { - StringBuilder currentLine = new StringBuilder(); - - // Read the password from the password file. - currentLine.append(reader.readLine()); - if (currentLine.length() > 0) { - password = new char[currentLine.length()]; - currentLine.getChars(0, currentLine.length(), password, 0); - currentLine = null; - } - isReadpassword = true; - if (Files.deleteIfExists(path)) { - LOGGER.info("Deleted the temporary password file at " + path); - } - } catch (IOException ex) { - throw new SSOAgentException("Error while reading the file ", ex); - } - } - } else if (!isReadpassword) { - - // Read password from the console. - System.out.print("Enter password for decryption:"); - password = System.console().readPassword(); - isReadpassword = true; - } - if (ArrayUtils.isEmpty(password)) { - LOGGER.log(Level.SEVERE, "Can't find the password to decrypt the encrypted values."); - return; - } - - // Get the encrypted property value. - String encryptedValue = String.valueOf(entry.getValue()); - - // Remove the Enc: prefix and get the actual encrypted value. - if (encryptedValue.split(":").length > 1) { - decodedPassword = AESDecryptor.decrypt(String.valueOf(entry.getValue()).split - (":")[1].trim(), password); - - // Remove the encrypted property value and replace with decrypted property value (plain text) - properties.remove(String.valueOf(entry.getKey())); - properties.setProperty(String.valueOf(entry.getKey()), decodedPassword); - } else { - LOGGER.log(Level.SEVERE, "Encrypted value is not in the correct format. Encrypted value " + - "must contain the encrypted value with Enc: as prefix."); - return; - } - } - } - - // Delete the stored password from memory by filling with zeros. - if (password != null) { - Arrays.fill(password, (char) 0); - } - privateKeyPassword = properties.getProperty("PrivateKeyPassword"); - privateKeyAlias = properties.getProperty("PrivateKeyAlias"); - idpPublicCertAlias = properties.getProperty("IdPPublicCertAlias"); - requestQueryParameters = properties.getProperty("SAML.Request.Query.Param"); - if (properties.getProperty("SSL.EnableSSLVerification") != null) { - enableSSLVerification = Boolean.parseBoolean(properties.getProperty("SSL.EnableSSLVerification")); - } - if (properties.getProperty("SSL.EnableSSLHostNameVerification") != null) { - enableHostNameVerification = - Boolean.parseBoolean(properties.getProperty("SSL.EnableSSLHostNameVerification")); - } - String isSAML2SSOLoginEnabledString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.ENABLE_SAML2_SSO_LOGIN); - if (isSAML2SSOLoginEnabledString != null) { - isSAML2SSOLoginEnabled = Boolean.parseBoolean(isSAML2SSOLoginEnabledString); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.ENABLE_SAML2_SSO_LOGIN + - " not configured. Defaulting to \'false\'"); - isSAML2SSOLoginEnabled = false; - } - - String isOpenIdLoginEnabledString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.ENABLE_OPENID_SSO_LOGIN); - if (isOpenIdLoginEnabledString != null) { - isOpenIdLoginEnabled = Boolean.parseBoolean(isOpenIdLoginEnabledString); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.ENABLE_OPENID_SSO_LOGIN + - " not configured. Defaulting to \'false\'"); - isOpenIdLoginEnabled = false; - } - - String isSAML2OAuth2GrantEnabledString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.ENABLE_OAUTH2_SAML2_OAUTH2_GRANT); - if (isSAML2OAuth2GrantEnabledString != null) { - isOAuth2SAML2GrantEnabled = Boolean.parseBoolean(isSAML2OAuth2GrantEnabledString); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.ENABLE_OAUTH2_SAML2_OAUTH2_GRANT + - " not configured. Defaulting to \'false\'"); - isOAuth2SAML2GrantEnabled = false; - } - - saml2SSOURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2_SSO_URL); - openIdURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OPENID_URL); - oauth2SAML2GrantURL = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.OAUTH2_SAML2_GRANT_URL); - - String skipURIsString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SKIP_URIS); - if (!StringUtils.isBlank(skipURIsString)) { - String[] skipURIArray = skipURIsString.split(","); - for (String skipURI : skipURIArray) { - skipURIs.add(skipURI); - } - } - - String queryParamsString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.QUERY_PARAMS); - if (!StringUtils.isBlank(queryParamsString)) { - String[] queryParamsArray = queryParamsString.split("&"); - Map> queryParamMap = new HashMap>(); - if (queryParamsArray.length > 0) { - for (String queryParam : queryParamsArray) { - String[] splitParam = queryParam.split("="); - if (splitParam.length == 2) { - if (queryParamMap.get(splitParam[0]) != null) { - queryParamMap.get(splitParam[0]).add(splitParam[1]); - } else { - List newList = new ArrayList(); - newList.add(splitParam[1]); - queryParamMap.put(splitParam[0], newList); - } - } - - } - for (Map.Entry> entry : queryParamMap.entrySet()) { - String[] valueArray = entry.getValue().toArray(new String[entry.getValue().size()]); - queryParams.put(entry.getKey(), valueArray); - } - } - } - - saml2.httpBinding = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING); - if (saml2.httpBinding == null || saml2.httpBinding.isEmpty()) { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING + - " not configured. Defaulting to \'" + SAMLConstants.SAML2_POST_BINDING_URI + "\'"); - saml2.httpBinding = SAMLConstants.SAML2_POST_BINDING_URI; - } - saml2.spEntityId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.SP_ENTITY_ID); - saml2.acsURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ACS_URL); - saml2.idPEntityId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IDP_ENTITY_ID); - saml2.idPURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IDP_URL); - saml2.attributeConsumingServiceIndex = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.ATTRIBUTE_CONSUMING_SERVICE_INDEX); - - String isSLOEnabledString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_SLO); - if (isSLOEnabledString != null) { - saml2.isSLOEnabled = Boolean.parseBoolean(isSLOEnabledString); - } else { - LOGGER.info("\'" + SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_SLO + - "\' not configured. Defaulting to \'false\'"); - saml2.isSLOEnabled = false; - } - saml2.sloURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.SLO_URL); - - String isAssertionSignedString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_SIGNING); - if (isAssertionSignedString != null) { - saml2.isAssertionSigned = Boolean.parseBoolean(isAssertionSignedString); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_SIGNING + - " not configured. Defaulting to \'false\'"); - saml2.isAssertionSigned = false; - } - - String isAssertionEncryptedString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_ENCRYPTION); - if (isAssertionEncryptedString != null) { - saml2.isAssertionEncrypted = Boolean.parseBoolean(isAssertionEncryptedString); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_ENCRYPTION + - " not configured. Defaulting to \'false\'"); - saml2.isAssertionEncrypted = false; - } - - String isResponseSignedString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_RESPONSE_SIGNING); - if (isResponseSignedString != null) { - saml2.isResponseSigned = Boolean.parseBoolean(isResponseSignedString); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_RESPONSE_SIGNING + - " not configured. Defaulting to \'false\'"); - saml2.isResponseSigned = false; - } - - if (saml2.isResponseSigned() || saml2.isAssertionSigned()) { - String signatureValidatorImplClass = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.SIGNATURE_VALIDATOR); - if (signatureValidatorImplClass != null) { - saml2.signatureValidatorImplClass = signatureValidatorImplClass; - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.SIGNATURE_VALIDATOR + - " not configured."); - } - } - - String isRequestSignedString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_REQUEST_SIGNING); - if (isRequestSignedString != null) { - saml2.isRequestSigned = Boolean.parseBoolean(isRequestSignedString); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_REQUEST_SIGNING + - " not configured. Defaulting to \'false\'"); - saml2.isRequestSigned = false; - } - - String isPassiveAuthnString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.IS_PASSIVE_AUTHN); - if (isPassiveAuthnString != null) { - saml2.isPassiveAuthn = Boolean.parseBoolean(isPassiveAuthnString); - } else { - LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.IS_PASSIVE_AUTHN + - "\' not configured. Defaulting to \'false\'"); - saml2.isPassiveAuthn = false; - } - - String isForceAuthnString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.IS_FORCE_AUTHN); - if (isForceAuthnString != null) { - saml2.isForceAuthn = Boolean.parseBoolean(isForceAuthnString); - } else { - LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.IS_FORCE_AUTHN + - "\' not configured. Defaulting to \'false\'"); - saml2.isForceAuthn = false; - } - - saml2.relayState = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.RELAY_STATE); - saml2.postBindingRequestHTMLPayload = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.SAML2.POST_BINDING_REQUEST_HTML_PAYLOAD); - saml2.artifactResolveURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ARTIFACT_RESOLVE_URL); - saml2.enableArtifactResolveSigning = StringUtils.equals( - properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ARTIFACT_RESOLVE_SIGNING), "true"); - - oauth2.tokenURL = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.OAuth2.TOKEN_URL); - oauth2.clientId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OAuth2.CLIENT_ID); - oauth2.clientSecret = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OAuth2.CLIENT_SECRET); - - openId.providerURL = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.OpenID.PROVIDER_URL); - openId.returnToURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OpenID.RETURN_TO_URL); - - String isAttributeExchangeEnabledString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_ATTRIBUTE_EXCHANGE); - if (isAttributeExchangeEnabledString != null) { - openId.isAttributeExchangeEnabled = Boolean.parseBoolean(isAttributeExchangeEnabledString); - } else { - LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_ATTRIBUTE_EXCHANGE + - "\' not configured. Defaulting to \'true\'"); - openId.isAttributeExchangeEnabled = true; - } - - String isDumbModeEnabledString = properties.getProperty( - SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_DUMB_MODE); - if (isAttributeExchangeEnabledString != null) { - openId.isDumbModeEnabled = Boolean.parseBoolean(isDumbModeEnabledString); - } else { - LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_DUMB_MODE + - "\' not configured. Defaulting to \'false\'"); - openId.isDumbModeEnabled = false; - } - - oidc.setConsumerKey(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC.CONSUMER_KEY)); - oidc.setConsumerSecret(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC.CONSUMER_SECRET)); - oidc.setAuthzEndpoint(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC.OAUTH2_AUTHZ_ENDPOINT)); - oidc.setAuthzGrantType(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC.OAUTH2_GRANT_TYPE)); - oidc.setCallBackUrl(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC.CALL_BACK_URL)); - oidc.setOIDCLogoutEndpoint(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC.OIDC_LOGOUT_ENDPOINT)); - oidc.setSessionIFrameEndpoint(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC - .OIDC_SESSION_IFRAME_ENDPOINT)); - oidc.setScope(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC.SCOPE)); - oidc.setPostLogoutRedirectUri(properties.getProperty(SSOAgentConstants.SSOAgentConfig.OIDC - .POST_LOGOUT_REDIRECT_RUI)); - - if (properties.getProperty("KeyStore") != null) { - try { - keyStoreStream = new FileInputStream(properties.getProperty("KeyStore")); - } catch (FileNotFoundException e) { - throw new SSOAgentException("Cannot find file " + properties.getProperty("KeyStore"), e); - } - } - keyStorePassword = properties.getProperty("KeyStorePassword"); - - // Check if the assertion validity timeStampSkew is set in config file - // If that is set, use that as the timeskewperiod - String timeStampSkew = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.TIME_STAMP_SKEW); - if (timeStampSkew != null) { - saml2.timeStampSkewInSeconds = Integer.parseInt(timeStampSkew); - } else { - LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.TIME_STAMP_SKEW + - " not configured. Defaulting to 300s"); - } - - - SSLContext sc; - try { - // Get SSL context - sc = SSLContext.getInstance("SSL"); - doHostNameVerification(); - TrustManager[] trustManagers = doSSLVerification(); - - sc.init(null, trustManagers, new java.security.SecureRandom()); - SSLSocketFactory sslSocketFactory = sc.getSocketFactory(); - HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); - - } catch (Exception e) { - throw new SSOAgentException("An error in initializing SSL Context"); - } - } - - 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"); - } - - } - - /** - * 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); - } - } - } - } - - private void doHostNameVerification(){ - if (!this.getEnableHostNameVerification()) { - // Create empty HostnameVerifier - HostnameVerifier hv = new HostnameVerifier() { - public boolean verify(String urlHostName, SSLSession session) { - return true; - } - }; - HttpsURLConnection.setDefaultHostnameVerifier(hv); - } - } - - private TrustManager[] doSSLVerification() throws Exception { - TrustManager[] trustManagers = null; - if (this.getEnableSSLVerification()) { - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(this.getKeyStore()); - trustManagers = tmf.getTrustManagers(); - } else { - // Create a trust manager that does not validate certificate chains - trustManagers = 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) { - } - } }; - } - return trustManagers; - } - - public class SAML2 { - - private String httpBinding = null; - private String spEntityId = null; - private String acsURL = null; - private String idPEntityId = null; - private String idPURL = null; - private Boolean isSLOEnabled = false; - private String sloURL = null; - private String attributeConsumingServiceIndex = null; - private SSOAgentX509Credential ssoAgentX509Credential = null; - private Boolean isAssertionSigned = false; - private Boolean isAssertionEncrypted = false; - private Boolean isResponseSigned = false; - private Boolean isRequestSigned = false; - private Boolean isPassiveAuthn = false; - private Boolean isForceAuthn = false; - private String relayState = null; - private String signatureValidatorImplClass = null; - private int timeStampSkewInSeconds = 300; - private String artifactResolveURL = null; - private boolean enableArtifactResolveSigning; - - public void setArtifactResolveURL(String artifactResolveURL) { - - this.artifactResolveURL = artifactResolveURL; - } - - public String getArtifactResolveURL() { - - return artifactResolveURL; - } - - public void setEnableArtifactResolveSigning(boolean enableArtifactResolveSigning) { - - this.enableArtifactResolveSigning = enableArtifactResolveSigning; - } - - public boolean isEnableArtifactResolveSigning() { - - return enableArtifactResolveSigning; - } - - /** - * The html page that will auto-submit the SAML2 to the IdP. - * This should be in valid HTML syntax, with following section within the - * auto-submit form. - * "<!--$saml_params-->" - * This section will be replaced by the SAML2 parameters. - *

- * If the parameter value is empty, null or doesn't have the above - * section, the default page will be shown - */ - private String postBindingRequestHTMLPayload = null; - - public String getHttpBinding() { - return httpBinding; - } - - public void setHttpBinding(String httpBinding) { - this.httpBinding = httpBinding; - } - - public String getSPEntityId() { - return spEntityId; - } - - public void setSPEntityId(String spEntityId) { - this.spEntityId = spEntityId; - } - - public String getACSURL() { - return acsURL; - } - - public void setACSURL(String acsURL) { - this.acsURL = acsURL; - } - - public String getIdPEntityId() { - return idPEntityId; - } - - public void setIdPEntityId(String idPEntityId) { - this.idPEntityId = idPEntityId; - } - - public String getIdPURL() { - return idPURL; - } - - public void setIdPURL(String idPURL) { - this.idPURL = idPURL; - } - - public Boolean isSLOEnabled() { - return isSLOEnabled; - } - - public String getSLOURL() { - return sloURL; - } - - public void setSLOURL(String sloURL) { - this.sloURL = sloURL; - } - - public String getAttributeConsumingServiceIndex() { - return attributeConsumingServiceIndex; - } - - public void setAttributeConsumingServiceIndex(String attributeConsumingServiceIndex) { - this.attributeConsumingServiceIndex = attributeConsumingServiceIndex; - } - - public SSOAgentX509Credential getSSOAgentX509Credential() { - return ssoAgentX509Credential; - } - - public void setSSOAgentX509Credential(SSOAgentX509Credential ssoAgentX509Credential) { - this.ssoAgentX509Credential = ssoAgentX509Credential; - } - - public Boolean isAssertionSigned() { - return isAssertionSigned; - } - - public Boolean isAssertionEncrypted() { - return isAssertionEncrypted; - } - - public Boolean isResponseSigned() { - return isResponseSigned; - } - - public Boolean isRequestSigned() { - return isRequestSigned; - } - - public Boolean isPassiveAuthn() { - return isPassiveAuthn; - } - - public Boolean isForceAuthn() { - return isForceAuthn; - } - - public String getRelayState() { - return relayState; - } - - public void setRelayState(String relayState) { - this.relayState = relayState; - } - - public String getPostBindingRequestHTMLPayload() { - return postBindingRequestHTMLPayload; - } - - public void setPostBindingRequestHTMLPayload(String postBindingRequestHTMLPayload) { - this.postBindingRequestHTMLPayload = postBindingRequestHTMLPayload; - } - - public void setSLOEnabled(Boolean isSLOEnabled) { - this.isSLOEnabled = isSLOEnabled; - } - - public void setAssertionSigned(Boolean isAssertionSigned) { - this.isAssertionSigned = isAssertionSigned; - } - - public void setAssertionEncrypted(Boolean isAssertionEncrypted) { - this.isAssertionEncrypted = isAssertionEncrypted; - } - - public void setResponseSigned(Boolean isResponseSigned) { - this.isResponseSigned = isResponseSigned; - } - - public void setRequestSigned(Boolean isRequestSigned) { - this.isRequestSigned = isRequestSigned; - } - - public void setPassiveAuthn(Boolean isPassiveAuthn) { - this.isPassiveAuthn = isPassiveAuthn; - } - - public void setForceAuthn(Boolean isForceAuthn) { - this.isForceAuthn = isForceAuthn; - } - - public String getSignatureValidatorImplClass() { - return signatureValidatorImplClass; - } - - public int getTimeStampSkewInSeconds() { - return timeStampSkewInSeconds; - } - } - - public class OpenID { - - private String mode = null; - private String providerURL = null; - private String returnToURL = null; - private String claimedId = null; - private AttributesRequestor attributesRequestor = null; - private boolean isAttributeExchangeEnabled = false; - private boolean isDumbModeEnabled = false; - - public String getMode() { - return mode; - } - - public void setMode(String mode) { - this.mode = mode; - } - - public String getProviderURL() { - return providerURL; - } - - public void setProviderURL(String providerURL) { - this.providerURL = providerURL; - } - - public String getReturnToURL() { - return returnToURL; - } - - public void setReturnToURL(String returnToURL) { - this.returnToURL = returnToURL; - } - - public String getClaimedId() { - return claimedId; - } - - public void setClaimedId(String claimedId) { - this.claimedId = claimedId; - } - - public AttributesRequestor getAttributesRequestor() { - return attributesRequestor; - } - - public void setAttributesRequestor(AttributesRequestor attributesRequestor) { - this.attributesRequestor = attributesRequestor; - } - - public boolean isAttributeExchangeEnabled() { - return isAttributeExchangeEnabled; - } - - public void setAttributeExchangeEnabled(boolean isAttributeExchangeEnabled) { - this.isAttributeExchangeEnabled = isAttributeExchangeEnabled; - } - - public boolean isDumbModeEnabled() { - return isDumbModeEnabled; - } - - public void setDumbModeEnabled(boolean isDumbModeEnabled) { - this.isDumbModeEnabled = isDumbModeEnabled; - } - } - - public class OIDC { - - private String consumerKey = StringUtils.EMPTY; - private String consumerSecret = StringUtils.EMPTY; - private String authzEndpoint = StringUtils.EMPTY; - private String authzGrantType = StringUtils.EMPTY; - private String callBackUrl = StringUtils.EMPTY; - private String OIDCLogoutEndpoint = StringUtils.EMPTY; - private String sessionIFrameEndpoint = StringUtils.EMPTY; - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } - - private String scope = StringUtils.EMPTY; - private String postLogoutRedirectUri = StringUtils.EMPTY; - - public String getConsumerKey() { - return consumerKey; - } - - public void setConsumerKey(String consumerKey) { - this.consumerKey = consumerKey; - } - - public String getAuthzEndpoint() { - return authzEndpoint; - } - - public void setAuthzEndpoint(String authzEndpoint) { - this.authzEndpoint = authzEndpoint; - } - public String getAuthzGrantType() { - return authzGrantType; - } - - public void setAuthzGrantType(String authzGrantType) { - this.authzGrantType = authzGrantType; - } - - public String getCallBackUrl() { - return callBackUrl; - } - - public void setCallBackUrl(String callBackUrl) { - this.callBackUrl = callBackUrl; - } - - public String getOIDCLogoutEndpoint() { - return OIDCLogoutEndpoint; - } - - public void setOIDCLogoutEndpoint(String OIDCLogoutEndpoint) { - this.OIDCLogoutEndpoint = OIDCLogoutEndpoint; - } - - public String getSessionIFrameEndpoint() { - return sessionIFrameEndpoint; - } - - public void setSessionIFrameEndpoint(String sessionIFrameEndpoint) { - this.sessionIFrameEndpoint = sessionIFrameEndpoint; - } - - public String getConsumerSecret() { - return consumerSecret; - } - - public void setConsumerSecret(String consumerSecret) { - this.consumerSecret = consumerSecret; - } - - public String getPostLogoutRedirectUri() { - return postLogoutRedirectUri; - } - - public void setPostLogoutRedirectUri(String postLogoutRedirectUri) { - this.postLogoutRedirectUri = postLogoutRedirectUri; - } - } - - public class OAuth2 { - - private String tokenURL = null; - private String clientId = null; - private String clientSecret = null; - - public String getClientSecret() { - return clientSecret; - } - - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } - - public String getTokenURL() { - return tokenURL; - } - - public void setTokenURL(String tokenURL) { - this.tokenURL = tokenURL; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/SSOAgentSessionBean.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/SSOAgentSessionBean.java deleted file mode 100644 index d59c055..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/bean/SSOAgentSessionBean.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.bean; - -import com.google.gson.Gson; -import org.openid4java.discovery.DiscoveryInformation; -import org.opensaml.saml.saml2.core.Assertion; -import org.opensaml.saml.saml2.core.Response; - -import java.util.List; -import java.util.Map; - -public class SSOAgentSessionBean { - - private OpenIDSessionBean openIDSessionBean; - - private SAMLSSOSessionBean samlssoSessionBean; - - public SAMLSSOSessionBean getSAMLSSOSessionBean() { - return samlssoSessionBean; - } - - public void setSAMLSSOSessionBean(SAMLSSOSessionBean samlssoSessionBean) { - this.samlssoSessionBean = samlssoSessionBean; - } - - public OpenIDSessionBean getOpenIDSessionBean() { - return openIDSessionBean; - } - - public void setOpenIDSessionBean(OpenIDSessionBean openIDSessionBean) { - this.openIDSessionBean = openIDSessionBean; - } - - public static class AccessTokenResponseBean { - - private String access_token; - - private String refresh_token; - - private String token_type; - - private String expires_in; - - public String getAccess_token() { - return access_token; - } - - public void setAccess_token(String access_token) { - this.access_token = access_token; - } - - public String getRefresh_token() { - return refresh_token; - } - - public void setRefresh_token(String refresh_token) { - this.refresh_token = refresh_token; - } - - public String getToken_type() { - return token_type; - } - - public void setToken_type(String token_type) { - this.token_type = token_type; - } - - public String getExpires_in() { - return expires_in; - } - - public void setExpires_in(String expires_in) { - this.expires_in = expires_in; - } - - @Override - public String toString() { - Gson gson = new Gson(); - return gson.toJson(this); - } - } - - public class OpenIDSessionBean { - - private DiscoveryInformation discoveryInformation; - - private String claimedId; - - private Map> openIdAttributes; - - public DiscoveryInformation getDiscoveryInformation() { - return discoveryInformation; - } - - public void setDiscoveryInformation(DiscoveryInformation discoveryInformation) { - this.discoveryInformation = discoveryInformation; - } - - public String getClaimedId() { - return claimedId; - } - - public void setClaimedId(String claimedId) { - this.claimedId = claimedId; - } - - public Map> getOpenIdAttributes() { - return openIdAttributes; - } - - public void setOpenIdAttributes(Map> openIdAttributes) { - this.openIdAttributes = openIdAttributes; - } - } - - public class SAMLSSOSessionBean { - - private String subjectId; - - private Response samlResponse; - - private String samlResponseString; - - private Assertion samlAssertion; - - private String samlAssertionString; - - private AccessTokenResponseBean accessTokenResponseBean; - - private String idPSessionIndex; - - private Map samlSSOAttributes; - - public String getSubjectId() { - return subjectId; - } - - public void setSubjectId(String subjectId) { - this.subjectId = subjectId; - } - - public Map getSAMLSSOAttributes() { - return samlSSOAttributes; - } - - public void setSAMLSSOAttributes(Map samlSSOAttributes) { - this.samlSSOAttributes = samlSSOAttributes; - } - - public String getIdPSessionIndex() { - return idPSessionIndex; - } - - public void setIdPSessionIndex(String idPSessionIndex) { - this.idPSessionIndex = idPSessionIndex; - } - - public Response getSAMLResponse() { - return samlResponse; - } - - public void setSAMLResponse(Response samlResponse) { - this.samlResponse = samlResponse; - } - - public String getSAMLResponseString() { - return samlResponseString; - } - - public void setSAMLResponseString(String samlResponseString) { - this.samlResponseString = samlResponseString; - } - - public Assertion getSAMLAssertion() { - return samlAssertion; - } - - public void setSAMLAssertion(Assertion samlAssertion) { - this.samlAssertion = samlAssertion; - } - - public String getSAMLAssertionString() { - return samlAssertionString; - } - - public void setSAMLAssertionString(String samlAssertionString) { - this.samlAssertionString = samlAssertionString; - } - - public AccessTokenResponseBean getAccessTokenResponseBean() { - return accessTokenResponseBean; - } - - public void setAccessTokenResponseBean(AccessTokenResponseBean accessTokenResponseBean) { - this.accessTokenResponseBean = accessTokenResponseBean; - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/ArtifactResolutionException.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/ArtifactResolutionException.java deleted file mode 100644 index 551d4ea..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/ArtifactResolutionException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent.exception; - -/** - * This class is used to denote exceptions thrown from the SAML2 Artifact Resolution - */ -public class ArtifactResolutionException extends Exception { - - public ArtifactResolutionException(String message) { - - super(message); - } - - public ArtifactResolutionException(String message, Throwable cause) { - - super(message, cause); - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/InvalidSessionException.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/InvalidSessionException.java deleted file mode 100644 index 4eb014b..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/InvalidSessionException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent.exception; - -/** - * Invalid session exception. - */ -public class InvalidSessionException extends SSOAgentException { - - public InvalidSessionException(String message) { - super(message); - } - - public InvalidSessionException(Throwable cause) { - super(cause); - } - - public InvalidSessionException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/SSOAgentException.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/SSOAgentException.java deleted file mode 100644 index ab1d03b..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/exception/SSOAgentException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.exception; - -import javax.servlet.ServletException; - -/** - * This class is used to denote the exceptions thrown from the SSO agent module - */ -public class SSOAgentException extends ServletException { - - public SSOAgentException(String message) { - super(message); - } - - public SSOAgentException(Throwable cause) { - super(cause); - } - - public SSOAgentException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/internal/SSOAgentServiceComponent.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/internal/SSOAgentServiceComponent.java deleted file mode 100644 index 9be139d..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/internal/SSOAgentServiceComponent.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.identity.sso.agent.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.user.core.service.RealmService; - -@Component( - name = "org.wso2.carbon.identity.sso.agent", - immediate = true) -public class SSOAgentServiceComponent { - - private static final Log log = LogFactory.getLog(SSOAgentServiceComponent.class); - - private static RealmService realmService; - - public static RealmService getRealmService() { - - return SSOAgentServiceComponent.realmService; - } - - @Reference( - name = "user.realmservice.default", - service = org.wso2.carbon.user.core.service.RealmService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRealmService") - protected void setRealmService(RealmService realmService) { - - if (log.isDebugEnabled()) { - log.debug("RealmService is set in the SSO agent bundle"); - } - SSOAgentServiceComponent.realmService = realmService; - } - - @Activate - protected void activate(ComponentContext ctxt) { - - if (log.isDebugEnabled()) { - log.info("SSO Agent bundle is activated"); - } - } - - @Deactivate - protected void deactivate(ComponentContext context) { - - if (log.isDebugEnabled()) { - log.info("SSO Agent bundle is deactivated"); - } - } - - protected void unsetRealmService(RealmService realmService) { - - if (log.isDebugEnabled()) { - log.debug("RealmService is unset in the SSO Agent bundle"); - } - SSOAgentServiceComponent.realmService = null; - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/oauth2/SAML2GrantAccessTokenRequestor.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/oauth2/SAML2GrantAccessTokenRequestor.java deleted file mode 100644 index 7d504bb..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/oauth2/SAML2GrantAccessTokenRequestor.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.oauth2; - -import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import net.shibboleth.utilities.java.support.codec.Base64Support; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentSessionBean; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConfigs; - -import javax.servlet.http.HttpServletRequest; -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.Charset; - -public class SAML2GrantAccessTokenRequestor { - - private static final Log log = LogFactory.getLog(SAML2GrantAccessTokenRequestor.class); - public static final String SAML2_BEARER_ASSERTION = "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion="; - - private SAML2GrantAccessTokenRequestor() { - } - - public static void getAccessToken(HttpServletRequest request) throws SSOAgentException { - - - String samlAssertionString = ((SSOAgentSessionBean) request.getSession().getAttribute( - SSOAgentConfigs.getSessionBeanName())).getSAMLSSOSessionBean().getSAMLAssertionString(); - - try { - - String consumerKey = SSOAgentConfigs.getOAuth2ClientId(); - String consumerSecret = SSOAgentConfigs.getOAuth2ClientSecret(); - String tokenEndpoint = SSOAgentConfigs.getTokenEndpoint(); - String keySecret = consumerKey+":"+consumerSecret; - - String accessTokenResponse = executePost(tokenEndpoint, - SAML2_BEARER_ASSERTION + URLEncoder.encode(Base64Support - .encode(samlAssertionString.getBytes(Charset.forName("UTF-8")), Base64Support.UNCHUNKED).replaceAll("\n", "")), - Base64Support.encode(keySecret.getBytes(Charset.forName - ("UTF-8")), Base64Support.UNCHUNKED) - .replace("\n", - "")); - - Gson gson = new Gson(); - SSOAgentSessionBean.AccessTokenResponseBean accessTokenResp = - gson.fromJson(accessTokenResponse, SSOAgentSessionBean.AccessTokenResponseBean.class); - - ((SSOAgentSessionBean) request.getSession().getAttribute( - SSOAgentConfigs.getSessionBeanName())).getSAMLSSOSessionBean() - .setAccessTokenResponseBean(accessTokenResp); - - } catch (Exception e) { - throw new SSOAgentException("Error while retrieving OAuth2 access token using SAML2 grant type", e); - } - } - - public static String executePost(String targetURL, String urlParameters, String clientCredentials) throws SSOAgentException { - - URL url; - HttpURLConnection connection = null; - try { - - //Create connection - url = new URL(targetURL); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setRequestProperty("Authorization", "Basic " + clientCredentials); - - connection.setRequestProperty("Content-Length", "" + - Integer.toString(urlParameters.getBytes(Charset.forName("UTF-8")).length)); - - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - - //Send request - DataOutputStream wr = new DataOutputStream( - connection.getOutputStream()); - wr.writeBytes(urlParameters); - wr.flush(); - wr.close(); - - //Get Response - InputStream is = connection.getInputStream(); - BufferedReader rd = new BufferedReader(new InputStreamReader(is)); - String line; - StringBuilder response = new StringBuilder(); - while ((line = rd.readLine()) != null) { - response.append(line); - response.append('\r'); - } - rd.close(); - return response.toString(); - - } catch (Exception e) { - - throw new SSOAgentException("Exception while executiong post", e); - } finally { - - if (connection != null) { - connection.disconnect(); - } - } - } - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/oauth2/SAML2GrantManager.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/oauth2/SAML2GrantManager.java deleted file mode 100644 index 71d019f..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/oauth2/SAML2GrantManager.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.oauth2; - -import com.google.gson.Gson; -import net.shibboleth.utilities.java.support.codec.Base64Support; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; - -import javax.net.ssl.HttpsURLConnection; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.Charset; - -public class SAML2GrantManager { - - private SSOAgentConfig ssoAgentConfig = null; - - public SAML2GrantManager(SSOAgentConfig ssoAgentConfig) { - this.ssoAgentConfig = ssoAgentConfig; - } - - 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(Base64Support.encode( - samlAssertionString.getBytes(Charset.forName("UTF-8")), Base64Support.UNCHUNKED).replaceAll("\n", "")); - String additionalQueryParam = ssoAgentConfig.getRequestQueryParameters(); - if (additionalQueryParam != null) { - queryParam = queryParam + additionalQueryParam; - } - String accessTokenResponse = executePost(queryParam, - Base64Support.encode(clientLogin.getBytes(Charset.forName("UTF-8")), Base64Support.UNCHUNKED) - .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); - } - - protected String executePost(String urlParameters, String basicAuthHeader) - throws SSOAgentException { - - URL url; - HttpURLConnection connection = null; - try { - - //Create connection - url = new URL(ssoAgentConfig.getOAuth2().getTokenURL()); - if(ssoAgentConfig.getEnableSSLVerification()){ - connection = (HttpsURLConnection) url.openConnection(); - } else{ - connection = (HttpURLConnection) url.openConnection(); - } - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setRequestProperty("Authorization", "Basic " + basicAuthHeader); - - connection.setRequestProperty("Content-Length", "" + - Integer.toString(urlParameters.getBytes(Charset.forName("UTF-8")).length)); - - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - - //Send request - DataOutputStream wr = new DataOutputStream( - connection.getOutputStream()); - wr.writeBytes(urlParameters); - wr.flush(); - wr.close(); - - //Get Response - InputStream is = connection.getInputStream(); - BufferedReader rd = new BufferedReader(new InputStreamReader(is)); - String line; - StringBuilder response = new StringBuilder(); - while ((line = rd.readLine()) != null) { - response.append(line); - response.append('\r'); - } - rd.close(); - return response.toString(); - - } catch (IOException e) { - throw new SSOAgentException( - "Error occurred while executing SAML2 grant request to OAuth2 Token URL", e); - } finally { - if (connection != null) { - connection.disconnect(); - } - } - } - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/openid/AttributesRequestor.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/openid/AttributesRequestor.java deleted file mode 100644 index f1f9735..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/openid/AttributesRequestor.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.openid; - -public interface AttributesRequestor { - - void init(); - - String[] getRequestedAttributes(String claimedId); - - boolean isRequired(String claimedId, String alias); - - String getTypeURI(String claimedId, String alias); - - int getCount(String claimedId, String alias); - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/openid/OpenIDManager.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/openid/OpenIDManager.java deleted file mode 100644 index b044780..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/openid/OpenIDManager.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.openid; - -import org.apache.commons.collections.MapUtils; -import org.openid4java.association.AssociationException; -import org.openid4java.consumer.ConsumerException; -import org.openid4java.consumer.ConsumerManager; -import org.openid4java.consumer.VerificationResult; -import org.openid4java.discovery.Discovery; -import org.openid4java.discovery.DiscoveryException; -import org.openid4java.discovery.DiscoveryInformation; -import org.openid4java.discovery.Identifier; -import org.openid4java.discovery.yadis.YadisException; -import org.openid4java.discovery.yadis.YadisResolver; -import org.openid4java.message.AuthRequest; -import org.openid4java.message.AuthSuccess; -import org.openid4java.message.MessageException; -import org.openid4java.message.ParameterList; -import org.openid4java.message.ax.AxMessage; -import org.openid4java.message.ax.FetchRequest; -import org.openid4java.message.ax.FetchResponse; -import org.openid4java.server.RealmVerifierFactory; -import org.openid4java.util.HttpFetcherFactory; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentDataHolder; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; - -import javax.net.ssl.SSLContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.security.NoSuchAlgorithmException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class OpenIDManager { - - // Smart OpenID Consumer Manager - AttributesRequestor attributesRequestor = null; - private SSOAgentConfig ssoAgentConfig = null; - - public OpenIDManager(SSOAgentConfig ssoAgentConfig) throws SSOAgentException { - SSOAgentDataHolder.getInstance().setConsumerManager(getConsumerManagerInstance()); - this.ssoAgentConfig = ssoAgentConfig; - } - - 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); - } - - public String doOpenIDLogin(HttpServletRequest request, HttpServletResponse response) throws SSOAgentException { - - String claimedId = ssoAgentConfig.getOpenId().getClaimedId(); - - try { - ConsumerManager manager = SSOAgentDataHolder.getInstance().getConsumerManager(); - - if (ssoAgentConfig.getOpenId().isDumbModeEnabled()) { - // Switch the consumer manager to dumb mode - manager.setMaxAssocAttempts(0); - } - - // Discovery on the user supplied ID - List discoveries = manager.discover(claimedId); - - // Associate with the OP and share a secret - DiscoveryInformation discovered = manager.associate(discoveries); - - // Keeping necessary parameters to verify the AuthResponse - LoggedInSessionBean sessionBean = new LoggedInSessionBean(); - sessionBean.setOpenId(sessionBean.new OpenID()); - sessionBean.getOpenId().setDiscoveryInformation(discovered); // set the discovery information - request.getSession().setAttribute(SSOAgentConstants.SESSION_BEAN_NAME, sessionBean); - - manager.setImmediateAuth(true); - AuthRequest authReq = manager.authenticate(discovered, - ssoAgentConfig.getOpenId().getReturnToURL()); - - - // Request subject attributes using Attribute Exchange extension specification if AttributeExchange is enabled - if (ssoAgentConfig.getOpenId().isAttributeExchangeEnabled() && - ssoAgentConfig.getOpenId().getAttributesRequestor() != null) { - - attributesRequestor = ssoAgentConfig.getOpenId().getAttributesRequestor(); - attributesRequestor.init(); - - String[] requestedAttributes = attributesRequestor.getRequestedAttributes(claimedId); - - // Getting required attributes using FetchRequest - FetchRequest fetchRequest = FetchRequest.createFetchRequest(); - - for (String requestedAttribute : requestedAttributes) { - fetchRequest.addAttribute(requestedAttribute, - attributesRequestor.getTypeURI(claimedId, requestedAttribute), - attributesRequestor.isRequired(claimedId, requestedAttribute), - attributesRequestor.getCount(claimedId, requestedAttribute)); - } - - // Adding the AX extension to the AuthRequest message - authReq.addExtension(fetchRequest); - } - - // Returning OP Url - SSOAgentDataHolder.getInstance().setConsumerManager(manager); - StringBuilder destinationUrl = new StringBuilder(authReq.getDestinationUrl(true)); - - if (MapUtils.isNotEmpty(ssoAgentConfig.getQueryParams())) { - StringBuilder builder = new StringBuilder(); - for (Map.Entry 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); - } - } - } - destinationUrl.append(builder); - } - return destinationUrl.toString(); - - } catch (YadisException e) { - if (e.getErrorCode() == 1796) { - throw new SSOAgentException(e.getMessage(), e); - } - throw new SSOAgentException("Error while creating FetchRequest", e); - } catch (MessageException e) { - throw new SSOAgentException("Error while creating FetchRequest", e); - } catch (DiscoveryException e) { - throw new SSOAgentException("Error while doing OpenID Discovery", e); - } catch (ConsumerException e) { - throw new SSOAgentException("Error while doing OpenID Authentication", e); - } - } - - public void processOpenIDLoginResponse(HttpServletRequest request, HttpServletResponse response) throws SSOAgentException { - - try { - // Getting all parameters in request including AuthResponse - ParameterList authResponseParams = new ParameterList(request.getParameterMap()); - - // Get previously saved session bean - LoggedInSessionBean loggedInSessionBean = (LoggedInSessionBean) request.getSession(false). - getAttribute(SSOAgentConstants.SESSION_BEAN_NAME); - if (loggedInSessionBean == null) { - throw new SSOAgentException("Error while verifying OpenID response. " + - "Cannot find valid session for user"); - } - - // Previously discovered information - DiscoveryInformation discovered = loggedInSessionBean.getOpenId().getDiscoveryInformation(); - - // Verify return-to, discoveries, nonce & signature - // Signature will be verified using the shared secret - VerificationResult verificationResult = SSOAgentDataHolder.getInstance().getConsumerManager().verify( - ssoAgentConfig.getOpenId().getReturnToURL(), authResponseParams, discovered); - - Identifier verified = verificationResult.getVerifiedId(); - - // Identifier will be NULL if verification failed - if (verified != null) { - - AuthSuccess authSuccess = (AuthSuccess) verificationResult.getAuthResponse(); - - loggedInSessionBean.getOpenId().setClaimedId(authSuccess.getIdentity()); - - // Get requested attributes using AX extension - if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { - Map> attributesMap = new HashMap>(); - if (ssoAgentConfig.getOpenId().getAttributesRequestor() != null) { - attributesRequestor = ssoAgentConfig.getOpenId().getAttributesRequestor(); - String[] attrArray = attributesRequestor.getRequestedAttributes(authSuccess.getIdentity()); - FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX); - for (String attr : attrArray) { - List attributeValues = fetchResp.getAttributeValuesByTypeUri(attributesRequestor.getTypeURI(authSuccess.getIdentity(), attr)); - if (attributeValues.get(0) instanceof String && ((String) attributeValues.get(0)).split(",").length > 1) { - String[] splitString = ((String) attributeValues.get(0)).split(","); - for (String part : splitString) { - attributeValues.add(part); - } - } - if (attributeValues.get(0) != null) { - attributesMap.put(attr, attributeValues); - } - } - } - loggedInSessionBean.getOpenId().setSubjectAttributes(attributesMap); - } - - } else { - throw new SSOAgentException("OpenID verification failed"); - } - - } catch (AssociationException e) { - throw new SSOAgentException("Error while verifying OpenID response", e); - } catch (MessageException e) { - throw new SSOAgentException("Error while verifying OpenID response", e); - } catch (DiscoveryException e) { - throw new SSOAgentException("Error while verifying OpenID response", e); - } - - } - - - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/SAML2SSOManager.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/SAML2SSOManager.java deleted file mode 100644 index bce39f0..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/SAML2SSOManager.java +++ /dev/null @@ -1,1066 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.saml; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.xml.security.signature.XMLSignature; -import org.joda.time.DateTime; -import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; -import org.opensaml.saml.common.SAMLVersion; -import org.opensaml.saml.common.SignableSAMLObject; -import org.opensaml.saml.common.xml.SAMLConstants; -import org.opensaml.saml.saml2.core.Extensions; -import org.opensaml.saml.saml2.core.ArtifactResponse; -import org.opensaml.saml.saml2.core.Assertion; -import org.opensaml.saml.saml2.core.Attribute; -import org.opensaml.saml.saml2.core.AttributeStatement; -import org.opensaml.saml.saml2.core.Audience; -import org.opensaml.saml.saml2.core.AudienceRestriction; -import org.opensaml.saml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml.saml2.core.AuthnContextComparisonTypeEnumeration; -import org.opensaml.saml.saml2.core.AuthnRequest; -import org.opensaml.saml.saml2.core.Conditions; -import org.opensaml.saml.saml2.core.EncryptedAssertion; -import org.opensaml.saml.saml2.core.Issuer; -import org.opensaml.saml.saml2.core.LogoutRequest; -import org.opensaml.saml.saml2.core.LogoutResponse; -import org.opensaml.saml.saml2.core.NameID; -import org.opensaml.saml.saml2.core.NameIDPolicy; -import org.opensaml.saml.saml2.core.RequestAbstractType; -import org.opensaml.saml.saml2.core.RequestedAuthnContext; -import org.opensaml.saml.saml2.core.Response; -import org.opensaml.saml.saml2.core.SessionIndex; -import org.opensaml.saml.saml2.core.Status; -import org.opensaml.saml.saml2.core.StatusCode; -import org.opensaml.saml.saml2.core.StatusMessage; -import org.opensaml.saml.saml2.core.impl.AuthnContextClassRefBuilder; -import org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder; -import org.opensaml.saml.saml2.core.impl.IssuerBuilder; -import org.opensaml.saml.saml2.core.impl.LogoutRequestBuilder; -import org.opensaml.saml.saml2.core.impl.LogoutResponseBuilder; -import org.opensaml.saml.saml2.core.impl.NameIDBuilder; -import org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder; -import org.opensaml.saml.saml2.core.impl.RequestedAuthnContextBuilder; -import org.opensaml.saml.saml2.core.impl.SessionIndexBuilder; -import org.opensaml.saml.saml2.core.impl.StatusBuilder; -import org.opensaml.saml.saml2.core.impl.StatusCodeBuilder; -import org.opensaml.saml.saml2.core.impl.StatusMessageBuilder; -import org.opensaml.saml.saml2.ecp.RelayState; -import org.opensaml.saml.saml2.encryption.Decrypter; -import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; -import org.opensaml.core.xml.XMLObject; -import org.opensaml.xmlsec.encryption.EncryptedKey; -import org.opensaml.core.xml.io.Marshaller; -import org.opensaml.core.xml.io.MarshallerFactory; -import org.opensaml.core.xml.io.MarshallingException; -import org.opensaml.security.credential.CredentialSupport; -import org.opensaml.security.credential.Credential; -import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver; -import org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver; -import org.opensaml.xmlsec.signature.impl.SignatureImpl; -import org.opensaml.xmlsec.signature.support.SignatureValidator; -import net.shibboleth.utilities.java.support.codec.Base64Support; -import net.shibboleth.utilities.java.support.xml.SerializeSupport; -import org.opensaml.xmlsec.signature.support.SignatureException; -import org.owasp.encoder.Encode; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.w3c.dom.bootstrap.DOMImplementationRegistry; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSOutput; -import org.w3c.dom.ls.LSSerializer; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.exception.ArtifactResolutionException; -import org.wso2.carbon.identity.sso.agent.exception.InvalidSessionException; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.internal.SSOAgentServiceComponent; -import org.wso2.carbon.identity.sso.agent.saml.artifact.SAMLSSOArtifactResolutionService; -import org.wso2.carbon.identity.sso.agent.security.X509CredentialImpl; -import org.wso2.carbon.identity.sso.agent.session.management.SSOAgentSessionManager; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentDataHolder; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentUtils; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.UserStoreManager; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.Deflater; -import java.util.zip.DeflaterOutputStream; -import javax.crypto.SecretKey; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import static org.wso2.carbon.CarbonConstants.AUDIT_LOG; -import static org.wso2.carbon.identity.core.util.IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR; - -/** - * TODO: Need to have mechanism to map SP initiated SAML2 Request to SAML2 Responses and validate. - * TODO: Still however IdP initiated SSO also should be possible through configuration - */ -public class SAML2SSOManager { - - private static String DEFAULT_MULTI_ATTRIBUTE_SEPARATOR = ","; - private static final Log log = LogFactory.getLog(SAML2SSOManager.class); - - - private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); - private SSOAgentConfig ssoAgentConfig = null; - - public SAML2SSOManager(SSOAgentConfig ssoAgentConfig) throws SSOAgentException { - - /* Initializing the OpenSAML library, loading default configurations */ - this.ssoAgentConfig = ssoAgentConfig; - //load custom Signature Validator Class - String signerClassName = ssoAgentConfig.getSAML2().getSignatureValidatorImplClass(); - try { - if (signerClassName != null) { - SSOAgentDataHolder.getInstance().setSignatureValidator(Class.forName(signerClassName).newInstance()); - } - } catch (ClassNotFoundException e) { - throw new SSOAgentException("Error loading custom signature validator class", e); - } catch (IllegalAccessException e) { - throw new SSOAgentException("Error loading custom signature validator class", e); - } catch (InstantiationException e) { - throw new SSOAgentException("Error loading custom signature validator class", e); - } - SSOAgentUtils.doBootstrap(); - } - - /** - * 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 { - HttpSession httpSession = request.getSession(false); - if (httpSession == null) { - throw new InvalidSessionException("Session is expired or user already logged out."); - } - - LoggedInSessionBean sessionBean = (LoggedInSessionBean) httpSession.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 = request.getParameter(RelayState.DEFAULT_ELEMENT_LOCAL_NAME); - if (StringUtils.isNotEmpty(relayState)) { - 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 entry : ssoAgentConfig.getQueryParams().entrySet()) { - if (entry.getKey() != null && entry.getValue() != null && entry.getValue().length > 0) { - for (String param : entry.getValue()) { - try { - builder.append("&").append(entry.getKey()).append("=").append( - URLEncoder.encode(param, "UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new SSOAgentException("Error occurred while URLEncoding " + entry.getKey(), e); - } - } - } - } - 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; - } - - /** - * 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 { - HttpSession httpSession = request.getSession(false); - if (httpSession == null) { - throw new InvalidSessionException("Session is expired or user already logged out."); - } - - LoggedInSessionBean sessionBean = (LoggedInSessionBean) httpSession.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 paramsMap = new HashMap(); - paramsMap.put(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ, - new String[]{encodedRequestMessage}); - String relayState = request.getParameter(RelayState.DEFAULT_ELEMENT_LOCAL_NAME); - if (StringUtils.isNotEmpty(relayState)) { - paramsMap.put(RelayState.DEFAULT_ELEMENT_LOCAL_NAME, new String[]{relayState}); - } else 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 entry : paramsMap.entrySet()) { - if (entry.getKey() != null && entry.getValue() != null && entry.getValue().length > 0) { - for (String param : entry.getValue()) { - htmlParams.append("\n"); - } - } - - } - String htmlPayload = ssoAgentConfig.getSAML2().getPostBindingRequestHTMLPayload(); - if (htmlPayload == null || !htmlPayload.contains("")) { - htmlPayload = "\n" + - "\n" + - "

You are now redirected back to " + ssoAgentConfig.getSAML2().getIdPURL() + " \n" + - "If the redirection fails, please click the post button.

\n" + - "
\n" + - "

\n" + - htmlParams.toString() + - "\n" + - "

\n" + - "
\n" + - "\n" + - "\n" + - ""; - } else { - htmlPayload = htmlPayload.replace("", - htmlParams.toString()); - } - return htmlPayload; - - } - - public String buildPostResponse(SignableSAMLObject requestMessage) throws SSOAgentException { - - return encodeRequestMessage(requestMessage, SAMLConstants.SAML2_POST_BINDING_URI); - } - - 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(Base64Support.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); - request.setAttribute(org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants.SHOULD_GO_TO_WELCOME_PAGE, "true"); - } 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."); - } - } - - /** - * Process authentication response with SAML2 artifact. - * - * @param request Http Servlet Request object. - * @throws SSOAgentException - */ - public void processArtifactResponse(HttpServletRequest request) throws SSOAgentException { - - SAMLSSOArtifactResolutionService artifactResolutionService = - new SAMLSSOArtifactResolutionService(ssoAgentConfig); - try { - ArtifactResponse artifactResponse = artifactResolutionService.getSAMLArtifactResponse( - request.getParameter(SSOAgentConstants.SAML2SSO.SAML2_ARTIFACT_RESP)); - - if (!StringUtils.equals(artifactResponse.getStatus().getStatusCode().getValue(), StatusCode.SUCCESS)) { - throw new SSOAgentException("Received an invalid SAML response with status code: " + - artifactResponse.getStatus().getStatusCode().getValue()); - } - if (artifactResponse.getMessage() == null) { - throw new SSOAgentException("Received SAML2 Artifact response message was null."); - } - XMLObject xmlObject = artifactResponse.getMessage(); - if (xmlObject instanceof Response || xmlObject instanceof LogoutResponse) { - validateSAMLResponseInArtifactResponse(xmlObject); - executeSAMLResponse(request, xmlObject); - } else { - throw new SSOAgentException("Received incorrect Artifact Response message with type: " + - xmlObject.getClass()); - } - } catch (ArtifactResolutionException e) { - throw new SSOAgentException("Error when getting the Artifact Response.", e); - } - } - - /** - * Validate Artifact Response message content. - * - * @param response Message of the received Artifact Response. - * @throws SSOAgentException - */ - private void validateSAMLResponseInArtifactResponse(XMLObject response) throws SSOAgentException { - - // Checking for duplicate samlp:Response. This is done to thwart possible XSW attacks - NodeList responseList = response.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20P_NS, "Response"); - if (responseList != null && responseList.getLength() > 0) { - throw new SSOAgentException("Error occurred while processing SAML2 response. " + - "Invalid schema for the SAML2 response. Multiple Response elements found."); - } - - // Checking for multiple Assertions. This is done to thwart possible XSW attacks. - NodeList assertionList = response.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Assertion"); - if (assertionList != null && assertionList.getLength() > 1) { - throw new SSOAgentException("Error occurred while processing SAML2 response. " + - "Invalid schema for the SAML2 response. Multiple Assertion elements found."); - } - } - - /** - * Redirect SAML response received via artifact resolution. - * - * @param request Initial authentication request. - * @param samlObject Response received via artifact resolution. - * @throws SSOAgentException - */ - private void executeSAMLResponse(HttpServletRequest request, XMLObject samlObject) throws SSOAgentException { - if (samlObject instanceof LogoutResponse) { - // This is a SAML response for a single logout request from the SP. - doSLO(request); - } else if (samlObject instanceof Response) { - processSSOResponse(request, (Response) samlObject); - } else { - throw new SSOAgentException("Unable to process unknown SAML object of type: " + samlObject.getClass()); - } - } - - /** - * This method handles the logout requests from the IdP - * Any request for the defined logout URL is handled here - * - * @param request - * @throws javax.servlet.ServletException - * @throws IOException - */ - public LogoutResponse doSLO(HttpServletRequest request) throws SSOAgentException { - - XMLObject saml2Object = null; - if (request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ) != null) { - saml2Object = SSOAgentUtils.unmarshall(new String(Base64Support.decode(request.getParameter( - SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ)), Charset.forName("UTF-8"))); - } - if (saml2Object == null) { - saml2Object = SSOAgentUtils.unmarshall(new String(Base64Support.decode(request.getParameter( - SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP)), Charset.forName("UTF-8"))); - } - if (saml2Object instanceof LogoutRequest) { - LogoutRequest logoutRequest = (LogoutRequest) saml2Object; - String sessionIndex = logoutRequest.getSessionIndexes().get(0).getSessionIndex(); - Set sessions = SSOAgentSessionManager.invalidateAllSessions(sessionIndex); - for (HttpSession session : sessions) { - session.invalidate(); - } - return buildLogoutResponse(logoutRequest.getID(), SSOAgentConstants.SAML2SSO - .SUCCESS_CODE, null); - } else if (saml2Object instanceof LogoutResponse) { - if (request.getSession(false) != null) { - /** - * Not invalidating session explicitly since there may be other listeners - * still waiting to get triggered and at the end of the chain session needs to be - * invalidated by the system - */ - Set sessions = - SSOAgentSessionManager.invalidateAllSessions(request.getSession(false)); - for (HttpSession session : sessions) { - try { - session.invalidate(); - } catch (IllegalStateException ignore) { - - if (log.isDebugEnabled()) { - log.debug("Ignoring exception : ", ignore); - } - //ignore - //session is already invalidated - } - } - } - return (LogoutResponse) saml2Object; - } else { - throw new SSOAgentException("Invalid SAML2 Single Logout Request/Response"); - } - } - - private void processSSOResponse(HttpServletRequest servletRequest) throws SSOAgentException { - - String saml2ResponseString = - new String(Base64Support.decode(servletRequest.getParameter( - SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP)), Charset.forName("UTF-8")); - XMLObject response = SSOAgentUtils.unmarshall(saml2ResponseString); - - // Check for duplicate samlp:Response - NodeList list = response.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20P_NS, "Response"); - if (list.getLength() > 0) { - log.error("Invalid schema for the SAML2 response. Multiple Response elements found."); - throw new SSOAgentException("Error occurred while processing SAML2 response."); - } - - // Checking for multiple Assertions - NodeList assertionList = response.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Assertion"); - if (assertionList.getLength() > 1) { - log.error("Invalid schema for the SAML2 response. Multiple Assertion elements found."); - throw new SSOAgentException("Error occurred while processing SAML2 response."); - } - - Response saml2Response = (Response) response; - processSSOResponse(servletRequest, saml2Response); - } - - private void processSSOResponse(HttpServletRequest servletRequest, Response saml2Response) throws SSOAgentException { - - LoggedInSessionBean sessionBean = new LoggedInSessionBean(); - sessionBean.setSAML2SSO(sessionBean.new SAML2SSO()); - sessionBean.getSAML2SSO().setResponseString(saml2Response.toString()); - sessionBean.getSAML2SSO().setSAMLResponse(saml2Response); - - Assertion assertion = null; - if (ssoAgentConfig.getSAML2().isAssertionEncrypted()) { - List 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 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"); - servletRequest.setAttribute(org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants.SHOULD_GO_TO_WELCOME_PAGE, "true"); - 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 - - // validate the assertion validity period - validateAssertionValidityPeriod(assertion); - - // validate audience restriction - validateAudienceRestriction(assertion); - - // validate signature - validateSignature(saml2Response, assertion); - - // 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"); - } - - // This should be the only time where a new session can be created. - // Thus in latter places servletRequest.getSession(false) should be used. - sessionBean.getSAML2SSO().setSubjectId(subject); // set the subject - servletRequest.getSession().setAttribute(SSOAgentConstants.SESSION_BEAN_NAME, sessionBean); - - // Marshalling SAML2 assertion after signature validation due to a weird issue in OpenSAML - sessionBean.getSAML2SSO().setAssertionString(marshall(assertion)); - - ((LoggedInSessionBean) servletRequest.getSession(false).getAttribute( - SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO(). - setSubjectAttributes(getAssertionStatements(assertion)); - - // Create a new session for each authentication and invalidate the current session - if (servletRequest.getSession(Boolean.FALSE) != null) { - HttpSession session = servletRequest.getSession(Boolean.FALSE); - Enumeration attributeNames = session.getAttributeNames(); - Map sessionMap = new HashMap(); - - while (attributeNames.hasMoreElements()) { - String attributeName = attributeNames.nextElement(); - sessionMap.put(attributeName, session.getAttribute(attributeName)); - } - servletRequest.getSession(Boolean.FALSE).invalidate(); - HttpSession newSession = servletRequest.getSession(Boolean.TRUE); - for (Map.Entry entry : sessionMap.entrySet()) { - newSession.setAttribute(entry.getKey(), entry.getValue()); - } - } - - //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) servletRequest.getSession(false).getAttribute( - SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().setSessionIndex(sessionId); - SSOAgentSessionManager.addAuthenticatedSession(servletRequest.getSession(false)); - } - - servletRequest.getSession(false).setAttribute(SSOAgentConstants.SESSION_BEAN_NAME, sessionBean); - } - - 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; - } - - public LogoutResponse buildLogoutResponse(String id, String status, String statMsg) - throws SSOAgentException { - - LogoutResponse logoutResp = new LogoutResponseBuilder().buildObject(); - logoutResp.setID(SSOAgentUtils.createID()); - logoutResp.setInResponseTo(id); - - IssuerBuilder issuerBuilder = new IssuerBuilder(); - Issuer issuer = issuerBuilder.buildObject(); - issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId()); - logoutResp.setIssuer(issuer); - - logoutResp.setStatus(buildStatus(status, statMsg)); - logoutResp.setIssueInstant(new DateTime()); - logoutResp.setDestination(ssoAgentConfig.getSAML2().getIdPURL()); - - SSOAgentUtils.setSignatureValue(logoutResp, XMLSignature.ALGO_ID_SIGNATURE_RSA, - new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential())); - - return logoutResp; - } - - 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.DEFAULT_ELEMENT_LOCAL_NAME) != null) { - authRequest.setExtensions((Extensions) request.getAttribute(Extensions.DEFAULT_ELEMENT_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; - } - - protected String encodeRequestMessage(SignableSAMLObject requestMessage, String binding) - throws SSOAgentException { - - Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(requestMessage); - Element authDOM = null; - try { - authDOM = marshaller.marshall(requestMessage); - StringWriter rspWrt = new StringWriter(); - rspWrt.write(SerializeSupport.nodeToString(authDOM)); - if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(binding)) { - //Compress the message, Base 64 encode and URL encode - Deflater deflater = new Deflater(Deflater.DEFLATED, true); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream - (byteArrayOutputStream, deflater); - deflaterOutputStream.write(rspWrt.toString().getBytes(Charset.forName("UTF-8"))); - deflaterOutputStream.close(); - String encodedRequestMessage = Base64Support.encode(byteArrayOutputStream - .toByteArray(), Base64Support.UNCHUNKED); - return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim(); - } else if (SAMLConstants.SAML2_POST_BINDING_URI.equals(binding)) { - return Base64Support.encode(rspWrt.toString().getBytes(), - Base64Support.UNCHUNKED); - } else { - LOGGER.log(Level.FINE, "Unsupported SAML2 HTTP Binding. Defaulting to " + - SAMLConstants.SAML2_POST_BINDING_URI); - return Base64Support.encode(rspWrt.toString().getBytes(), - Base64Support.UNCHUNKED); - } - } catch (MarshallingException e) { - throw new SSOAgentException("Error occurred while encoding SAML2 request", e); - } catch (UnsupportedEncodingException e) { - throw new SSOAgentException("Error occurred while encoding SAML2 request", e); - } catch (IOException e) { - throw new SSOAgentException("Error occurred while encoding SAML2 request", e); - } - } - - - /* - * Process the response and returns the results - */ - private Map getAssertionStatements(Assertion assertion) { - - Map results = new HashMap(); - String multiAttributeSeparator = DEFAULT_MULTI_ATTRIBUTE_SEPARATOR; - - UserRealm realm; - try { - if (SSOAgentServiceComponent.getRealmService() != null) { - realm = SSOAgentServiceComponent.getRealmService().getTenantUserRealm - (org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID); - UserStoreManager userStoreManager = (UserStoreManager) realm.getUserStoreManager(); - - multiAttributeSeparator = userStoreManager. - getRealmConfiguration().getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); - } - } catch (UserStoreException e) { - log.warn("Error while reading MultiAttributeSeparator value from primary user store ", e); - } - - if (assertion != null && assertion.getAttributeStatements() != null) { - - List attributeStatementList = assertion.getAttributeStatements(); - - - for (AttributeStatement statement : attributeStatementList) { - List attributesList = statement.getAttributes(); - for (Attribute attribute : attributesList) { - List multipleAttributeValues = attribute.getAttributeValues(); - if (CollectionUtils.isNotEmpty(multipleAttributeValues)) { - List valueList = new ArrayList<>(); - for (XMLObject attributeVal : multipleAttributeValues) { - Element value = attributeVal.getDOM(); - valueList.add(value.getTextContent()); - } - String attributeValue = StringUtils.join(valueList.iterator(), multiAttributeSeparator); - results.put(attribute.getName(), attributeValue); - } - } - } - - } - return results; - } - - /** - * 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 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"); - } - } - } - - - /** - * Validate the signature of a SAML2 Response and Assertion - * - * @param response SAML2 Response - * @return true, if signature is valid. - */ - protected void validateSignature(Response response, Assertion assertion) throws SSOAgentException { - - if (SSOAgentDataHolder.getInstance().getSignatureValidator() != null) { - //Custom implemetation of signature validation - SAMLSignatureValidator signatureValidatorUtility = (SAMLSignatureValidator) SSOAgentDataHolder - .getInstance().getSignatureValidator(); - signatureValidatorUtility.validateSignature(response, assertion, ssoAgentConfig); - } else { - //If custom implementation not found, Execute the default implementation - if (ssoAgentConfig.getSAML2().isResponseSigned()) { - if (response.getSignature() == null) { - throw new SSOAgentException("SAML2 Response signing is enabled, but signature element not found in SAML2 Response element"); - } else { - validateSignature(response.getSignature()); - } - } - if (ssoAgentConfig.getSAML2().isAssertionSigned()) { - if (assertion.getSignature() == null) { - throw new SSOAgentException("SAML2 Assertion signing is enabled, but signature element not found in SAML2 Assertion element"); - } else { - validateSignature(assertion.getSignature()); - } - } - } - } - - /** - * Serialize the Auth. Request - * - * @param xmlObject - * @return serialized auth. req - */ - protected String marshall(XMLObject xmlObject) throws SSOAgentException { - - try { - System.setProperty("javax.xml.parsers.DocumentBuilderFactory", - "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); - MarshallerFactory marshallerFactory = - XMLObjectProviderRegistrySupport.getMarshallerFactory(); - Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); - Element element = marshaller.marshall(xmlObject); - ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream(); - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - LSOutput output = impl.createLSOutput(); - output.setByteStream(byteArrayOutputStrm); - writer.write(element, output); - return new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8")); - } catch (ClassNotFoundException e) { - throw new SSOAgentException("Error in marshalling SAML2 Assertion", e); - } catch (InstantiationException e) { - throw new SSOAgentException("Error in marshalling SAML2 Assertion", e); - } catch (MarshallingException e) { - throw new SSOAgentException("Error in marshalling SAML2 Assertion", e); - } catch (IllegalAccessException e) { - throw new SSOAgentException("Error in marshalling SAML2 Assertion", e); - } - } - - /** - * Get Decrypted Assertion - * - * @param encryptedAssertion - * @return - * @throws Exception - */ - protected Assertion getDecryptedAssertion(EncryptedAssertion encryptedAssertion) throws SSOAgentException { - - try { - KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver( - new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential())); - - EncryptedKey key = encryptedAssertion.getEncryptedData(). - getKeyInfo().getEncryptedKeys().get(0); - Decrypter decrypter = new Decrypter(null, keyResolver, null); - SecretKey dkey = (SecretKey) decrypter.decryptKey(key, encryptedAssertion.getEncryptedData(). - getEncryptionMethod().getAlgorithm()); - Credential shared = CredentialSupport.getSimpleCredential(dkey); - decrypter = new Decrypter(new StaticKeyInfoCredentialResolver(shared), null, null); - decrypter.setRootInNewDocument(true); - return decrypter.decrypt(encryptedAssertion); - } catch (Exception e) { - throw new SSOAgentException("Decrypted assertion error", e); - - } - } - - protected boolean isNoPassive(Response response) { - - return response.getStatus() != null && - response.getStatus().getStatusCode() != null && - response.getStatus().getStatusCode().getValue().equals(StatusCode.RESPONDER) && - response.getStatus().getStatusCode().getStatusCode() != null && - response.getStatus().getStatusCode().getStatusCode().getValue().equals( - StatusCode.NO_PASSIVE); - } - - public SSOAgentConfig getSsoAgentConfig() { - return ssoAgentConfig; - } - - /** - * Validates the 'Not Before' and 'Not On Or After' conditions of the SAML Assertion - * - * @param assertion SAML Assertion element - * @throws SSOAgentException - */ - private void validateAssertionValidityPeriod(Assertion assertion) throws SSOAgentException { - - if (assertion.getConditions() != null) { - int timeStampSkewInSeconds = ssoAgentConfig.getSAML2().getTimeStampSkewInSeconds(); - - DateTime validFrom = assertion.getConditions().getNotBefore(); - DateTime validTill = assertion.getConditions().getNotOnOrAfter(); - - if (validFrom != null && validFrom.minusSeconds(timeStampSkewInSeconds).isAfterNow()) { - throw new SSOAgentException("Failed to meet SAML Assertion Condition 'Not Before'"); - } - - if (validTill != null && validTill.plusSeconds(timeStampSkewInSeconds).isBeforeNow()) { - throw new SSOAgentException("Failed to meet SAML Assertion Condition 'Not On Or After'"); - } - - if (validFrom != null && validTill != null && validFrom.isAfter(validTill)) { - throw new SSOAgentException( - "SAML Assertion Condition 'Not Before' must be less than the value of 'Not On Or After'"); - } - } - } - - /** - * Validates the XML Signature object - * - * @param signature XMLObject - * @throws SSOAgentException - */ - - private void validateSignature(XMLObject signature) throws SSOAgentException{ - - SignatureImpl signImpl = (SignatureImpl) signature; - try { - SAMLSignatureProfileValidator signatureProfileValidator = new SAMLSignatureProfileValidator(); - signatureProfileValidator.validate(signImpl); - } catch (SignatureException ex) { - String logMsg = "Signature do not confirm to SAML signature profile. Possible XML Signature " + - "Wrapping Attack!"; - AUDIT_LOG.warn(logMsg); - if (log.isDebugEnabled()) { - log.debug(logMsg, ex); - } - throw new SSOAgentException(logMsg, ex); - } - - try { - SignatureValidator.validate(signImpl, new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential())); - } catch (SignatureException e) { - if (log.isDebugEnabled()) { - log.debug("Validation exception : ", e); - } - throw new SSOAgentException("Signature validation failed for SAML2 Element"); - } - } - - private Status buildStatus(String status, String statMsg) { - - Status stat = new StatusBuilder().buildObject(); - - // Set the status code. - StatusCode statCode = new StatusCodeBuilder().buildObject(); - statCode.setValue(status); - stat.setStatusCode(statCode); - - // Set the status Message. - if (statMsg != null) { - StatusMessage statMesssage = new StatusMessageBuilder().buildObject(); - statMesssage.setMessage(statMsg); - stat.setStatusMessage(statMesssage); - } - - return stat; - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/SAMLSignatureValidator.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/SAMLSignatureValidator.java deleted file mode 100644 index 284deea..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/SAMLSignatureValidator.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.wso2.carbon.identity.sso.agent.saml; - -import org.opensaml.saml.saml2.core.Assertion; -import org.opensaml.saml.saml2.core.Response; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; - -public interface SAMLSignatureValidator { - void validateSignature(Response response, Assertion assertion, SSOAgentConfig ssoAgentConfig) throws SSOAgentException; -} \ No newline at end of file diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/artifact/SAMLSSOArtifactResolutionService.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/artifact/SAMLSSOArtifactResolutionService.java deleted file mode 100644 index 1ef6e68..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/artifact/SAMLSSOArtifactResolutionService.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent.saml.artifact; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.xml.security.signature.XMLSignature; -import org.joda.time.DateTime; -import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; -import org.opensaml.saml.common.SAMLObject; -import org.opensaml.saml.common.SAMLObjectBuilder; -import org.opensaml.saml.common.SAMLVersion; -import org.opensaml.saml.common.xml.SAMLConstants; -import org.opensaml.saml.saml2.core.Artifact; -import org.opensaml.saml.saml2.core.ArtifactResolve; -import org.opensaml.saml.saml2.core.ArtifactResponse; -import org.opensaml.saml.saml2.core.Issuer; -import org.opensaml.saml.saml2.core.StatusCode; -import org.opensaml.soap.soap11.Envelope; -import org.opensaml.core.xml.XMLObjectBuilderFactory; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.exception.ArtifactResolutionException; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.security.X509CredentialImpl; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentUtils; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.util.Iterator; -import java.util.UUID; -import javax.xml.soap.MessageFactory; -import javax.xml.soap.MimeHeaders; -import javax.xml.soap.SOAPBody; -import javax.xml.soap.SOAPBodyElement; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPMessage; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -/** - * This class is used for handling SAML2 Artifact Binding. - */ -public class SAMLSSOArtifactResolutionService { - - private static final Log log = LogFactory.getLog(SAMLSSOArtifactResolutionService.class); - - private SSOAgentConfig ssoAgentConfig; - - public SAMLSSOArtifactResolutionService(SSOAgentConfig ssoAgentConfig) { - - this.ssoAgentConfig = ssoAgentConfig; - } - - /** - * Create a SAML artifactResolveObject based on given samlArt parameter and wrapped into a soapRequest - * Send the soapRequest to the Artifact Resolve Endpoint - * - * @param samlArtReceived SAML Artifact reference needed to get the actual data - * @return ArtifactResponse - */ - public ArtifactResponse getSAMLArtifactResponse(String samlArtReceived) throws ArtifactResolutionException { - - validateArtifactResolveConfig(); - ArtifactResolve artifactResolve = generateArtifactResolveReq(samlArtReceived); - return sendArtifactResolveRequest(artifactResolve); - } - - /** - * Create SAML ArtifactResolve Object and sign - * - * @param samlArtReceived object reference to actual data - * @return SAML ArtifactResolve Object - */ - public ArtifactResolve generateArtifactResolveReq(String samlArtReceived) throws ArtifactResolutionException { - - ArtifactResolve artifactResolve = createArtifactResolveObject(samlArtReceived); - if (ssoAgentConfig.getSAML2().isEnableArtifactResolveSigning()) { - if (log.isDebugEnabled()) { - log.debug("Signing artifact resolve request for the received SAML artifact: " + samlArtReceived); - } - artifactResolve = signArtifactResolveReq(artifactResolve); - } - - if (log.isDebugEnabled()) { - log.debug("Created Artifact Resolve object: " + artifactResolve); - } - - return artifactResolve; - } - - /** - * Send Artifact Resolve Request to Artifact Resolution Service - * - * @param artifactResolve Artifact Resolve Request - * @return ArtifactResponse - * @throws ArtifactResolutionException - */ - public ArtifactResponse sendArtifactResolveRequest(ArtifactResolve artifactResolve) - throws ArtifactResolutionException { - - SAMLSSOSoapMessageService soapMessageService = new SAMLSSOSoapMessageService(); - Envelope envelope = soapMessageService.buildSOAPMessage(artifactResolve); - String envelopeElement; - try { - envelopeElement = SSOAgentUtils.marshall(envelope); - } catch (SSOAgentException e) { - throw new ArtifactResolutionException("Encountered error marshalling SOAP message with artifact " + - "resolve, into its DOM representation", e); - } - - if (log.isDebugEnabled()) { - log.debug("Artifact Resolve Request as a SOAP Message: " + envelopeElement); - } - - String artifactResponseString = soapMessageService.sendSOAP(envelopeElement, - ssoAgentConfig.getSAML2().getArtifactResolveURL()); - if (log.isDebugEnabled()) { - log.debug("Received artifact response string: " + artifactResponseString); - } - ArtifactResponse artifactResponse = extractArtifactResponse(artifactResponseString); - validateArtifactResponse(artifactResolve, artifactResponse); - return artifactResponse; - } - - /** - * Extract Artifact response object from soap message string. Return null if fail. - * - * @param artifactResponseString Response string from artifact resolver. - * @return Extracted artifact response object. - * @throws ArtifactResolutionException - */ - public ArtifactResponse extractArtifactResponse(String artifactResponseString) - throws ArtifactResolutionException { - - ArtifactResponse artifactResponse = null; - InputStream stream = new ByteArrayInputStream(artifactResponseString.getBytes(StandardCharsets.UTF_8)); - try { - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage soapMessage = messageFactory.createMessage(new MimeHeaders(), stream); - SOAPBody soapBody = soapMessage.getSOAPBody(); - Iterator iterator = soapBody.getChildElements(); - - while (iterator.hasNext()) { - SOAPBodyElement artifactResponseElement = (SOAPBodyElement) iterator.next(); - - if (StringUtils.equals(SAMLConstants.SAML20P_NS, artifactResponseElement.getNamespaceURI()) && - StringUtils.equals(ArtifactResponse.DEFAULT_ELEMENT_LOCAL_NAME, - artifactResponseElement.getLocalName())) { - - DOMSource source = new DOMSource(artifactResponseElement); - StringWriter stringResult = new StringWriter(); - TransformerFactory.newInstance().newTransformer().transform( - source, new StreamResult(stringResult)); - artifactResponse = (ArtifactResponse) SSOAgentUtils.unmarshall(stringResult.toString()); - if (log.isDebugEnabled()) { - log.debug("Extracted Artifact Response: " + stringResult); - } - } else { - throw new ArtifactResolutionException("Received invalid artifact response with nameSpaceURI: " + - artifactResponseElement.getNamespaceURI() + " and localName: " + - artifactResponseElement.getLocalName()); - } - } - } catch (SOAPException | IOException | TransformerException e) { - throw new ArtifactResolutionException("Didn't receive valid artifact response.", e); - } catch (SSOAgentException e) { - throw new ArtifactResolutionException("Encountered error unmarshalling response into SAML2 object", e); - } - return artifactResponse; - } - - private void validateArtifactResponse(ArtifactResolve artifactResolve, ArtifactResponse artifactResponse) - throws ArtifactResolutionException { - - if (artifactResponse == null) { - throw new ArtifactResolutionException("Received artifact response message was null."); - } - - String artifactResolveId = artifactResolve.getID(); - String artifactResponseInResponseTo = artifactResponse.getInResponseTo(); - if (!artifactResolveId.equals(artifactResponseInResponseTo)) { - throw new ArtifactResolutionException("Artifact resolve ID: " + artifactResolveId + " is not equal to " + - "artifact response InResponseTo : " + artifactResponseInResponseTo); - } - - String artifactResponseStatus = artifactResponse.getStatus().getStatusCode().getValue(); - if (!StatusCode.SUCCESS.equals(artifactResponseStatus)) { - throw new ArtifactResolutionException("Unsuccessful artifact response with status: " + - artifactResponseStatus); - } - - SAMLObject message = artifactResponse.getMessage(); - if (message == null) { - throw new ArtifactResolutionException("No SAML response embedded into the artifact response."); - } - } - - private void validateArtifactResolveConfig() throws ArtifactResolutionException { - - if (StringUtils.isEmpty(ssoAgentConfig.getSAML2().getArtifactResolveURL())) { - throw new ArtifactResolutionException("Artifact Resolve Url is not configured."); - } - if (StringUtils.isEmpty(ssoAgentConfig.getSAML2().getSPEntityId())) { - throw new ArtifactResolutionException("Artifact Resolve Issuer is not configured."); - } - } - - private ArtifactResolve createArtifactResolveObject(String samlArtReceived) { - - XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory(); - - SAMLObjectBuilder artifactResolveBuilder = - (SAMLObjectBuilder) builderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME); - ArtifactResolve artifactResolve = artifactResolveBuilder.buildObject(); - artifactResolve.setVersion(SAMLVersion.VERSION_20); - artifactResolve.setID(UUID.randomUUID().toString()); - artifactResolve.setIssueInstant(new DateTime()); - - SAMLObjectBuilder artifactBuilder = - (SAMLObjectBuilder) builderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME); - Artifact artifact = artifactBuilder.buildObject(); - artifact.setArtifact(samlArtReceived); - - SAMLObjectBuilder issuerBuilder = (SAMLObjectBuilder) builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME); - Issuer issuer = issuerBuilder.buildObject(); - issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId()); - - artifactResolve.setIssuer(issuer); - artifactResolve.setArtifact(artifact); - - return artifactResolve; - } - - private ArtifactResolve signArtifactResolveReq(ArtifactResolve artifactResolve) - throws ArtifactResolutionException { - - try { - return SSOAgentUtils.setSignature(artifactResolve, XMLSignature.ALGO_ID_SIGNATURE_RSA, - new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential())); - } catch (SSOAgentException e) { - throw new ArtifactResolutionException("Error in signing the Artifact Resolve request", e); - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/artifact/SAMLSSOSoapMessageService.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/artifact/SAMLSSOSoapMessageService.java deleted file mode 100644 index 76eeef4..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/saml/artifact/SAMLSSOSoapMessageService.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent.saml.artifact; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicResponseHandler; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.opensaml.saml.common.SAMLObject; -import org.opensaml.soap.common.SOAPObjectBuilder; -import org.opensaml.soap.soap11.Body; -import org.opensaml.soap.soap11.Envelope; -import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; -import org.opensaml.core.xml.XMLObjectBuilderFactory; -import org.wso2.carbon.identity.sso.agent.exception.ArtifactResolutionException; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; - -import java.io.IOException; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; - -/** - * This class is used for handling SAML SOAP Binding - */ -public class SAMLSSOSoapMessageService { - - private static final String CONTENT_TYPE = "text/xml; charset=utf-8"; - private static final String MIME_TYPE = "text/xml"; - private static final Log log = LogFactory.getLog(SAMLSSOSoapMessageService.class); - - /** - * Build a SOAP Message. - * - * @param samlMessage SAMLObject. - * @return Envelope soap envelope - */ - public Envelope buildSOAPMessage(SAMLObject samlMessage) { - - XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory(); - - SOAPObjectBuilder envBuilder = (SOAPObjectBuilder) builderFactory.getBuilder( - Envelope.DEFAULT_ELEMENT_NAME); - Envelope envelope = envBuilder.buildObject(); - - SOAPObjectBuilder bodyBuilder = (SOAPObjectBuilder) builderFactory.getBuilder( - Body.DEFAULT_ELEMENT_NAME); - Body body = bodyBuilder.buildObject(); - body.getUnknownXMLObjects().add(samlMessage); - envelope.setBody(body); - return envelope; - } - - /** - * Send SOAP message - * - * @param message message that needs to be send - * @param url url that the artifact resolve request should be sent - * @return response of invoking artifact resolve endpoint - * @throws ArtifactResolutionException - */ - public String sendSOAP(String message, String url) throws ArtifactResolutionException { - - if (message == null) { - throw new ArtifactResolutionException("Cannot send null SOAP message."); - } - if (url == null) { - throw new ArtifactResolutionException("Cannot send SOAP message to null URL."); - } - - if (log.isDebugEnabled()) { - log.debug("Sending SOAP message to the URL: " + url); - } - - StringBuilder soapResponse = new StringBuilder(); - try { - HttpPost httpPost = new HttpPost(url); - setRequestProperties(url, message, httpPost); - HttpClient httpClient = getHttpClient(); - HttpResponse httpResponse = httpClient.execute(httpPost); - - int responseCode = httpResponse.getStatusLine().getStatusCode(); - if (responseCode != 200) { - throw new ArtifactResolutionException("Problem in communicating with: " + url + ". Received response: " - + responseCode); - } else { - log.info("Successful response from the URL: " + url); - soapResponse.append(getResponseBody(httpResponse)); - } - } catch (UnknownHostException e) { - throw new ArtifactResolutionException("Unknown targeted host: " + url, e); - } catch (IOException e) { - throw new ArtifactResolutionException("Could not open connection with host: " + url, e); - } - return soapResponse.toString(); - } - - private void setRequestProperties(String url, String message, HttpPost httpPost) { - - httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.CONTENT_TYPE_PARAM_KEY, CONTENT_TYPE); - httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.ACCEPT_PARAM_KEY, CONTENT_TYPE); - String sbSOAPAction = "\"" + url + "\""; - httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.SOAP_ACTION_PARAM_KEY, sbSOAPAction); - httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.PRAGMA_PARAM_KEY, "no-cache"); - httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.CACHE_CONTROL_PARAM_KEY, "no-cache, no-store"); - - httpPost.setEntity(new StringEntity(message, ContentType.create(MIME_TYPE, StandardCharsets.UTF_8))); - } - - private static String getResponseBody(HttpResponse response) throws ArtifactResolutionException { - - ResponseHandler responseHandler = new BasicResponseHandler(); - String responseBody; - try { - responseBody = responseHandler.handleResponse(response); - } catch (IOException e) { - throw new ArtifactResolutionException("Error when retrieving the HTTP response body.", e); - } - if (log.isDebugEnabled()) { - log.debug("Response Body:" + responseBody); - } - return responseBody; - } - - private HttpClient getHttpClient() throws ArtifactResolutionException { - - CloseableHttpClient httpClient = null; - SSLContextBuilder builder = new SSLContextBuilder(); - try { - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( - builder.build()); - httpClient = HttpClients.custom().setSSLSocketFactory( - sslsf).build(); - } catch (NoSuchAlgorithmException | KeyStoreException e) { - throw new ArtifactResolutionException("Error while building trust store.", e); - } catch (KeyManagementException e) { - throw new ArtifactResolutionException("Error while building socket factory.", e); - } - - return httpClient; - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentCarbonX509Credential.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentCarbonX509Credential.java deleted file mode 100644 index 7b0e27c..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentCarbonX509Credential.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.security; - -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.core.util.KeyStoreManager; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; - -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -public class SSOAgentCarbonX509Credential implements SSOAgentX509Credential { - - private PublicKey publicKey = null; - private PrivateKey privateKey = null; - private X509Certificate entityCertificate = null; - - public SSOAgentCarbonX509Credential(int tenantId, String tenantDomain) - throws SSOAgentException { - - readCarbonX509Credentials(tenantId, tenantDomain); - } - - @Override - public PublicKey getPublicKey() { - return publicKey; - } - - @Override - public PrivateKey getPrivateKey() { - return privateKey; - } - - @Override - public X509Certificate getEntityCertificate() { - return entityCertificate; - } - - protected void readCarbonX509Credentials(int tenantId, String tenantDomain) throws SSOAgentException { - - KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - // derive key store name - String ksName = tenantDomain.trim().replace(".", "-"); - // derive JKS name - String jksName = ksName + ".jks"; - KeyStore keyStore = null; - try { - keyStore = tenantKSM.getKeyStore(jksName); - } catch (Exception e) { - throw new SSOAgentException("Error occurred while retrieving " + - "key store of tenant " + tenantDomain, e); - } - try { - entityCertificate = (X509Certificate) keyStore.getCertificate(tenantDomain); - } catch (KeyStoreException e) { - throw new SSOAgentException("Error occurred while retrieving " + - "public certificate with alias " + tenantDomain + - " of tenant " + tenantDomain, e); - } - privateKey = (PrivateKey) tenantKSM.getPrivateKey(jksName, tenantDomain); - } else { - try { - entityCertificate = tenantKSM.getDefaultPrimaryCertificate(); - } catch (Exception e) { - throw new SSOAgentException("Error retrieving default primary certificate of " + - MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, e); - } - try { - privateKey = tenantKSM.getDefaultPrivateKey(); - } catch (Exception e) { - throw new SSOAgentException("Error retrieving default private key of " + - MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, e); - } - } - publicKey = entityCertificate.getPublicKey(); - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentCredential.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentCredential.java deleted file mode 100644 index dfd1bd9..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentCredential.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.security; - -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -public interface SSOAgentCredential { - - void init() throws SSOAgentException; - - PublicKey getPublicKey() throws SSOAgentException; - - PrivateKey getPrivateKey() throws SSOAgentException; - - X509Certificate getEntityCertificate() throws SSOAgentException; - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentKeyStoreCredential.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentKeyStoreCredential.java deleted file mode 100644 index ffc97d5..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentKeyStoreCredential.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.security; - -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConfigs; - -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.UnrecoverableKeyException; -import java.security.cert.X509Certificate; - -public class SSOAgentKeyStoreCredential implements SSOAgentCredential { - - private static PublicKey publicKey = null; - private static PrivateKey privateKey = null; - private static X509Certificate entityCertificate = null; - - private static void readX509Credentials() throws SSOAgentException { - - String privateKeyAlias = SSOAgentConfigs.getPrivateKeyAlias(); - String privateKeyPassword = SSOAgentConfigs.getPrivateKeyPassword(); - String idpCertAlias = SSOAgentConfigs.getIdPCertAlias(); - - KeyStore keyStore = SSOAgentConfigs.getKeyStore(); - X509Certificate cert = null; - PrivateKey privateKey = null; - - try { - - if (privateKeyAlias != null && SSOAgentConfigs.isRequestSigned()) { - privateKey = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword.toCharArray()); - - if (privateKey == null) { - throw new SSOAgentException("RequestSigning is enabled, but cannot find private key with the alias " + - privateKeyAlias + " in the key store"); - } - } - - - cert = (X509Certificate) keyStore.getCertificate(idpCertAlias); - if (cert == null) { - throw new SSOAgentException("Cannot find IDP certificate with the alias " + idpCertAlias + " in the trust store"); - } - } catch (KeyStoreException e) { - throw new SSOAgentException("Error when reading keystore", e); - } catch (UnrecoverableKeyException e) { - throw new SSOAgentException("Error when reading keystore", e); - } catch (NoSuchAlgorithmException e) { - throw new SSOAgentException("Error when reading keystore", e); - } - - publicKey = cert.getPublicKey(); - SSOAgentKeyStoreCredential.privateKey = privateKey; - entityCertificate = cert; - } - - @Override - public void init() throws SSOAgentException { - readX509Credentials(); - } - - @Override - public PublicKey getPublicKey() { - return publicKey; - } - - @Override - public PrivateKey getPrivateKey() { - return privateKey; - } - - @Override - public X509Certificate getEntityCertificate() { - return entityCertificate; - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentX509Credential.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentX509Credential.java deleted file mode 100644 index 6415616..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentX509Credential.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.security; - -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -public interface SSOAgentX509Credential { - - PublicKey getPublicKey() throws SSOAgentException; - - PrivateKey getPrivateKey() throws SSOAgentException; - - X509Certificate getEntityCertificate() throws SSOAgentException; - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentX509KeyStoreCredential.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentX509KeyStoreCredential.java deleted file mode 100644 index 72a21b8..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/SSOAgentX509KeyStoreCredential.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.security; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; - -import java.io.IOException; -import java.io.InputStream; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.UnrecoverableKeyException; -import java.security.cert.X509Certificate; - -public class SSOAgentX509KeyStoreCredential implements SSOAgentX509Credential { - - private static final Log log = LogFactory.getLog(SSOAgentX509KeyStoreCredential.class); - private PublicKey publicKey = null; - private PrivateKey privateKey = null; - private X509Certificate entityCertificate = null; - - public SSOAgentX509KeyStoreCredential(KeyStore keyStore, String publicCertAlias, - String privateKeyAlias, char[] privateKeyPassword) - throws SSOAgentException { - - readX509Credentials(keyStore, publicCertAlias, privateKeyAlias, privateKeyPassword); - } - - public SSOAgentX509KeyStoreCredential(InputStream keyStoreInputStream, char[] keyStorePassword, - String publicCertAlias, String privateKeyAlias, - char[] privateKeyPassword) - throws SSOAgentException { - - readX509Credentials(keyStoreInputStream, keyStorePassword, publicCertAlias, - privateKeyAlias, privateKeyPassword); - } - - @Override - public PublicKey getPublicKey() throws SSOAgentException { - return publicKey; - } - - @Override - public PrivateKey getPrivateKey() throws SSOAgentException { - return privateKey; - } - - @Override - public X509Certificate getEntityCertificate() throws SSOAgentException { - return entityCertificate; - } - - protected void readX509Credentials(KeyStore keyStore, String publicCertAlias, - String privateKeyAlias, char[] privateKeyPassword) - throws SSOAgentException { - - try { - entityCertificate = (X509Certificate) keyStore.getCertificate(publicCertAlias); - } catch (KeyStoreException e) { - throw new SSOAgentException( - "Error occurred while retrieving public certificate for alias " + - publicCertAlias, e); - } - publicKey = entityCertificate.getPublicKey(); - try { - privateKey = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword); - } catch (KeyStoreException e) { - throw new SSOAgentException( - "Error occurred while retrieving private key for alias " + - privateKeyAlias, e); - } catch (NoSuchAlgorithmException e) { - throw new SSOAgentException( - "Error occurred while retrieving private key for alias " + - privateKeyAlias, e); - } catch (UnrecoverableKeyException e) { - throw new SSOAgentException( - "Error occurred while retrieving private key for alias " + - privateKeyAlias, e); - } - } - - 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"); - } - } - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/X509CredentialImpl.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/X509CredentialImpl.java deleted file mode 100644 index 8e8278b..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/security/X509CredentialImpl.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.security; - -import org.opensaml.security.credential.Credential; -import org.opensaml.security.credential.CredentialContextSet; -import org.opensaml.security.credential.UsageType; -import org.opensaml.security.x509.X509Credential; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.security.SSOAgentX509Credential; - -import javax.crypto.SecretKey; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; - -/** - * X509Credential implementation for signing and verification. - */ -public class X509CredentialImpl implements X509Credential { - - private PublicKey publicKey = null; - private X509Certificate entityCertificate = null; - private PrivateKey privateKey = null; - - public X509CredentialImpl(SSOAgentX509Credential credential) throws SSOAgentException { - publicKey = credential.getPublicKey(); - this.entityCertificate = credential.getEntityCertificate(); - this.privateKey = credential.getPrivateKey(); - } - - /** - * Retrieves the publicKey - */ - @Override - public PublicKey getPublicKey() { - return publicKey; - } - - @Override - public PrivateKey getPrivateKey() { - return privateKey; - } - - @Override - public X509Certificate getEntityCertificate() { - return entityCertificate; - } - - // ********** Not implemented ************************************************************** - - @Override - public Collection getCRLs() { - return new ArrayList(); - } - - @Override - public Collection getEntityCertificateChain() { - return new ArrayList(); - } - - /*** - * Get the credential context set. - * @return This method is not supported so the return is null. - */ - @Override - public CredentialContextSet getCredentialContextSet() { - return null; - } - - @Override - public Class getCredentialType() { - return null; - } - - @Override - public String getEntityId() { - return null; - } - - @Override - public Collection getKeyNames() { - return new ArrayList(); - } - - @Override - public SecretKey getSecretKey() { - return null; - } - - @Override - public UsageType getUsageType() { - return null; - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/session/management/SSOAgentHttpSessionListener.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/session/management/SSOAgentHttpSessionListener.java deleted file mode 100644 index 30f5e46..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/session/management/SSOAgentHttpSessionListener.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.session.management; - -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; - -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class SSOAgentHttpSessionListener implements HttpSessionListener { - - private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); - - @Override - public void sessionCreated(HttpSessionEvent httpSessionEvent) { - if (httpSessionEvent.getSession().getAttribute(SSOAgentConstants.SESSION_BEAN_NAME) == null) { - // This log is not accurate, since we depend on request.getSession() to create new session - // if there is no existing session. After that only we set the Session-Bean. - // Thus in this listener the session always does not contain a Session-Bean Attribute. - LOGGER.log(Level.WARNING, "HTTP Session created without LoggedInSessionBean"); - } - } - - @Override - public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { - // No need to invalidate session here, as it is going to be invalidated soon - SSOAgentSessionManager.invalidateSession(httpSessionEvent.getSession()); - httpSessionEvent.getSession().removeAttribute(SSOAgentConstants.SESSION_BEAN_NAME); - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/session/management/SSOAgentSessionManager.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/session/management/SSOAgentSessionManager.java deleted file mode 100644 index ea66bd6..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/session/management/SSOAgentSessionManager.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.session.management; - -import org.wso2.carbon.identity.sso.agent.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean; - -import javax.servlet.http.HttpSession; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - - -public class SSOAgentSessionManager { - - /* - * Session Index at the IdP is mapped to the session at the SP so that a single logout request - * can be handled by invalidating the SP session mapped to IdP Session Index. - */ - private static Map> ssoSessionsMap = - new HashMap>(); - - private SSOAgentSessionManager() { - } - - public static void invalidateSession(HttpSession session) { - LoggedInSessionBean sessionBean = (LoggedInSessionBean) session.getAttribute( - SSOAgentConstants.SESSION_BEAN_NAME); - if (sessionBean != null && sessionBean.getSAML2SSO() != null) { - String sessionIndex = sessionBean.getSAML2SSO().getSessionIndex(); - if (sessionIndex != null) { - Set sessions = ssoSessionsMap.get(sessionIndex); - if (sessions != null) { - sessions.remove(session); - } - } - } - } - - public static Set invalidateAllSessions(HttpSession session) { - LoggedInSessionBean sessionBean = (LoggedInSessionBean) session.getAttribute( - SSOAgentConstants.SESSION_BEAN_NAME); - Set sessions = new HashSet(); - if (sessionBean != null && sessionBean.getSAML2SSO() != null) { - String sessionIndex = sessionBean.getSAML2SSO().getSessionIndex(); - if (sessionIndex != null) { - sessions = ssoSessionsMap.remove(sessionIndex); - } - } - if (sessions == null) { - sessions = new HashSet(); - } - return sessions; - } - - public static Set invalidateAllSessions(String sessionIndex) { - Set sessions = ssoSessionsMap.remove(sessionIndex); - if (sessions == null) { - sessions = new HashSet(); - } - return sessions; - } - - public static void addAuthenticatedSession(HttpSession session) { - String sessionIndex = ((LoggedInSessionBean) session.getAttribute( - SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().getSessionIndex(); - if (ssoSessionsMap.get(sessionIndex) != null) { - ssoSessionsMap.get(sessionIndex).add(session); - } else { - Set sessions = new HashSet(); - sessions.add(session); - ssoSessionsMap.put(sessionIndex, sessions); - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentConfigs.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentConfigs.java deleted file mode 100644 index b9247c7..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentConfigs.java +++ /dev/null @@ -1,692 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.util; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; - -import javax.servlet.FilterConfig; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.security.KeyStore; -import java.util.Properties; -import java.util.logging.Logger; - -public class SSOAgentConfigs { - - private static final Logger LOGGER = Logger.getLogger("InfoLogging"); - private static final Log log = LogFactory.getLog(SSOAgentConfig.class); - - - private static Boolean samlSSOLoginEnabled; - private static Boolean openidLoginEnabled; - private static Boolean saml2GrantEnabled; - private static String sessionBeanName; - private static String loginUrl; - private static String samlSSOUrl; - private static String openIdUrl; - private static String saml2GrantUrl; - - private static String issuerId; - private static String consumerUrl; - private static String idPUrl; - - private static String attributeConsumingServiceIndex; - private static Boolean isSLOEnabled; - private static String logoutUrl; - private static Boolean isResponseSigned; - private static Boolean isAssertionSigned; - private static Boolean isAssertionEncrypted; - private static Boolean isRequestSigned; - private static Boolean isForceAuthn; - private static String ssoAgentCredentialImplClass; - private static InputStream keyStoreStream; - private static String keyStorePassword; - private static KeyStore keyStore; - private static String idPCertAlias; - private static String privateKeyAlias; - private static String privateKeyPassword; - private static String tokenEndpoint; - private static String clientId; - private static String clientSecret; - - private static String openIdProviderUrl; - private static String returnTo; - private static String claimedIdParameterName; - private static String attributesRequestorImplClass; - - private static String requestQueryParameters; - - private static String addExtension; - - private SSOAgentConfigs() { - } - - public static void initConfig(FilterConfig fConfigs) throws SSOAgentException { - - Properties properties = new Properties(); - - if (fConfigs.getInitParameter("SSOAgentPropertiesFilePath") != null && - !"".equals(fConfigs.getInitParameter("SSOAgentPropertiesFilePath"))) { - try (FileInputStream fileInputStream = new FileInputStream(fConfigs.getInitParameter - ("SSOAgentPropertiesFilePath"))) { - properties.load(fileInputStream); - initConfig(properties); - } catch (FileNotFoundException e) { - if (log.isDebugEnabled()) { - log.debug("File not found ", e); - } - throw new SSOAgentException("Agent properties file not found"); - - } catch (IOException e) { - - throw new SSOAgentException("Error occurred while reading Agent properties file", e); - } - - } else { - LOGGER.warning("\'SSOAgentPropertiesFilePath\' not configured"); - } - } - - public static void initConfig(String propertiesFilePath) throws SSOAgentException { - - Properties properties = new Properties(); - try (FileInputStream fileInputStream = new FileInputStream(propertiesFilePath)){ - properties.load(fileInputStream); - initConfig(properties); - } catch (FileNotFoundException e) { - - throw new SSOAgentException("Agent properties file not found at " + propertiesFilePath, e); - } catch (IOException e) { - - throw new SSOAgentException("Error reading Agent properties file at " + propertiesFilePath, e); - } - } - - public static void initConfig(Properties properties) throws SSOAgentException { - - if (properties.getProperty("EnableSAMLSSOLogin") != null) { - samlSSOLoginEnabled = Boolean.parseBoolean(properties.getProperty("EnableSAMLSSOLogin")); - } else { - LOGGER.info("\'EnableSAMLSSOLogin\' not configured. Defaulting to \'true\'"); - samlSSOLoginEnabled = true; - } - - if (properties.getProperty("EnableOpenIDLogin") != null) { - openidLoginEnabled = Boolean.parseBoolean(properties.getProperty("EnableOpenIDLogin")); - } else { - LOGGER.info("\'EnableOpenIDLogin\' not configured. Defaulting to \'true\'"); - openidLoginEnabled = true; - } - - if (properties.getProperty("EnableSAML2Grant") != null) { - saml2GrantEnabled = Boolean.parseBoolean(properties.getProperty("EnableSAML2Grant")); - } else { - LOGGER.info("\'EnableSAML2Grant\' not configured. Defaulting to \'true\'"); - saml2GrantEnabled = true; - } - - if (properties.getProperty("SSOAgentSessionBeanName") != null) { - sessionBeanName = properties.getProperty("SSOAgentSessionBeanName"); - } else { - LOGGER.info("\'SSOAgentSessionBeanName\' not configured. Defaulting to \'SSOAgentSessionBean\'"); - sessionBeanName = "SSOAgentSessionBean"; - } - - loginUrl = properties.getProperty("LoginUrl"); - samlSSOUrl = properties.getProperty("SAMLSSOUrl"); - saml2GrantUrl = properties.getProperty("SAML2GrantUrl"); - openIdUrl = properties.getProperty("OpenIDUrl"); - - issuerId = properties.getProperty("SAML.IssuerID"); - consumerUrl = properties.getProperty("SAML.ConsumerUrl"); - idPUrl = properties.getProperty("SAML.IdPUrl"); - attributeConsumingServiceIndex = properties.getProperty("SAML.AttributeConsumingServiceIndex"); - - if (properties.getProperty("SAML.EnableSLO") != null) { - isSLOEnabled = Boolean.parseBoolean(properties.getProperty("SAML.EnableSLO")); - } else { - LOGGER.info("\'SAML.EnableSLO\' not configured. Defaulting to \'false\'"); - isSLOEnabled = false; - } - - logoutUrl = properties.getProperty("SAML.LogoutUrl"); - - if (properties.getProperty("SAML.EnableResponseSigning") != null) { - isResponseSigned = Boolean.parseBoolean(properties.getProperty("SAML.EnableResponseSigning")); - } else { - LOGGER.info("\'SAML.EnableResponseSigning\' not configured. Defaulting to \'false\'"); - isResponseSigned = false; - } - - if (properties.getProperty("SAML.EnableAssertionSigning") != null) { - isAssertionSigned = Boolean.parseBoolean(properties.getProperty("SAML.EnableAssertionSigning")); - } else { - LOGGER.info("\'SAML.EnableAssertionSigning\' not configured. Defaulting to \'true\'"); - isAssertionSigned = true; - } - - if (properties.getProperty("SAML.EnableAssertionEncryption") != null) { - isAssertionEncrypted = Boolean.parseBoolean(properties.getProperty("SAML.EnableAssertionEncryption")); - } else { - LOGGER.info("\'SAML.EnableAssertionEncryption\' not configured. Defaulting to \'false\'"); - isAssertionEncrypted = false; - } - - if (properties.getProperty("SAML.EnableRequestSigning") != null) { - isRequestSigned = Boolean.parseBoolean(properties.getProperty("SAML.EnableRequestSigning")); - } else { - LOGGER.info("\'SAML.EnableRequestSigning\' not configured. Defaulting to \'false\'"); - isRequestSigned = false; - } - - if (properties.getProperty("SAML.EnableForceAuthentication") != null) { - isForceAuthn = Boolean.parseBoolean(properties.getProperty("SAML.EnableForceAuthentication")); - } else { - LOGGER.info("\'SAML.EnableForceAuthentication\' not configured. Defaulting to \'false\'"); - isForceAuthn = false; - } - - ssoAgentCredentialImplClass = properties.getProperty("SAML.SSOAgentCredentialImplClass"); - if (properties.getProperty("KeyStore") != null) { - try { - keyStoreStream = new FileInputStream(properties.getProperty("KeyStore")); - } catch (FileNotFoundException e) { - - throw new SSOAgentException("Cannot find file " + properties.getProperty("KeyStore"), e); - } - } - keyStorePassword = properties.getProperty("KeyStorePassword"); - idPCertAlias = properties.getProperty("SAML.IdPCertAlias"); - privateKeyAlias = properties.getProperty("SAML.PrivateKeyAlias"); - privateKeyPassword = properties.getProperty("SAML.PrivateKeyPassword"); - - tokenEndpoint = properties.getProperty("SAML.OAuth2TokenEndpoint"); - clientId = properties.getProperty("SAML.OAuth2ClientID"); - clientSecret = properties.getProperty("SAML.OAuth2ClientSecret"); - - openIdProviderUrl = properties.getProperty("OpenID.OpenIdProviderUrl"); - returnTo = properties.getProperty("OpenID.ReturnToUrl"); - claimedIdParameterName = properties.getProperty("OpenID.ClaimedIDParameterName"); - attributesRequestorImplClass = properties.getProperty("OpenID.AttributesRequestorImplClass"); - - requestQueryParameters = properties.getProperty("SAML.Request.Query.Param"); - - addExtension = properties.getProperty("SAML.Request.Add.Extension"); - - } - - public static void initCheck() throws SSOAgentException { - - if ((SSOAgentConfigs.isSAMLSSOLoginEnabled() || SSOAgentConfigs.isOpenIDLoginEnabled()) && - SSOAgentConfigs.getLoginUrl() == null) { - - throw new SSOAgentException("\'LoginUrl\' not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.isSAML2GrantEnabled() && - SSOAgentConfigs.getSAML2GrantUrl() == null) { - throw new SSOAgentException("\'SAML2GrantUrl\' not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getSAMLSSOUrl() == null) { - throw new SSOAgentException("\'SAMLSSOUrl\' not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getIssuerId() == null) { - throw new SSOAgentException("\'SAML.IssuerId\' not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getConsumerUrl() == null) { - throw new SSOAgentException("\'SAML.ConsumerUrl\' not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getIdPUrl() == null) { - throw new SSOAgentException("\'SAML.IdPUrl\' not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getAttributeConsumingServiceIndex() == null) { - LOGGER.info("\'SAML.AttributeConsumingServiceIndex\' not configured. " + - "No attributes of the Subject will be requested"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.isSLOEnabled() && - SSOAgentConfigs.getLogoutUrl() == null) { - throw new SSOAgentException("Single Logout enabled, but SAML.LogoutUrl not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && - (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned() || SSOAgentConfigs.isAssertionEncripted() || SSOAgentConfigs.isRequestSigned()) && - SSOAgentConfigs.getSSOAgentCredentialImplClass() == null) { - LOGGER.info("SAML.SSOAgentCredentialImplClass not configured." + - " Defaulting to \'org.wso2.carbon.identity.sso.agent.security.SSOAgentKeyStoreCredential\'"); - SSOAgentConfigs.setSSOAgentCredentialImplClass("org.wso2.carbon.identity.sso.agent.security.SSOAgentKeyStoreCredential"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && - (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned() || SSOAgentConfigs.isAssertionEncripted() || SSOAgentConfigs.isRequestSigned()) && - SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && SSOAgentConfigs.getKeyStoreStream() == null) { - throw new SSOAgentException("KeyStore not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && - (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned() || SSOAgentConfigs.isAssertionEncripted() || SSOAgentConfigs.isRequestSigned()) && - SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && SSOAgentConfigs.getKeyStoreStream() != null && - SSOAgentConfigs.getKeyStorePassword() == null) { - LOGGER.info("KeyStorePassword not configured." + - " Defaulting to \'wso2carbon\'"); - SSOAgentConfigs.setKeyStorePassword("wso2carbon"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && - (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned()) && - SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && SSOAgentConfigs.getIdPCertAlias() == null) { - LOGGER.info("\'SAML.IdPCertAlias\' not configured. Defaulting to \'wso2carbon\'"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && (SSOAgentConfigs.isRequestSigned() || SSOAgentConfigs.isAssertionEncripted()) && - SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && SSOAgentConfigs.getPrivateKeyAlias() == null) { - LOGGER.info("SAML.PrivateKeyAlias not configured. Defaulting to \'wso2carbon\'"); - SSOAgentConfigs.setPrivateKeyAlias("wso2carbon"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && (SSOAgentConfigs.isRequestSigned() || SSOAgentConfigs.isAssertionEncripted()) && - SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && SSOAgentConfigs.getPrivateKeyPassword() == null) { - LOGGER.info("SAML.PrivateKeyPassword not configured. Defaulting to \'wso2carbon\'"); - SSOAgentConfigs.setPrivateKeyPassword("wso2carbon"); - } - - if (!SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.isSAML2GrantEnabled()) { - LOGGER.info("SAMLSSOLogin disabled. Therefore disabling SAML2Grant as well"); - SSOAgentConfigs.setSAML2GrantEnabled(false); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.isSAML2GrantEnabled() && - SSOAgentConfigs.getTokenEndpoint() == null) { - LOGGER.info("SAML.OAuth2TokenEndpoint not configured. Defaulting to \'https://localhost:9443/oauth2/token\'"); - SSOAgentConfigs.setTokenEndpoint("https://localhost:9443/oauth2/token"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.isSAML2GrantEnabled() && - SSOAgentConfigs.getTokenEndpoint() != null && SSOAgentConfigs.getOAuth2ClientId() == null) { - LOGGER.info("SAML.OAuth2ClientID not configured"); - throw new SSOAgentException("SAML.OAuth2ClientId not configured"); - } - - if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.isSAML2GrantEnabled() && - SSOAgentConfigs.getTokenEndpoint() != null && SSOAgentConfigs.getOAuth2ClientSecret() == null) { - throw new SSOAgentException("SAML.OAuth2ClientSecret not configured"); - } - - if (SSOAgentConfigs.isOpenIDLoginEnabled() && SSOAgentConfigs.getOpenIdUrl() == null) { - throw new SSOAgentException("\'OpenIDUrl\' not configured"); - } - - if (SSOAgentConfigs.isOpenIDLoginEnabled() && SSOAgentConfigs.getOpenIdProviderUrl() == null) { - throw new SSOAgentException("\'OpenID.OpenIdProviderUrl\' not configured"); - } - - if (SSOAgentConfigs.isOpenIDLoginEnabled() && SSOAgentConfigs.getReturnTo() == null) { - throw new SSOAgentException("OpenID.ReturnToUrl not configured"); - } - - if (SSOAgentConfigs.isOpenIDLoginEnabled() && SSOAgentConfigs.getClaimedIdParameterName() == null) { - LOGGER.info("OpenID.ClaimIDParameterName not configured. Defaulting to \'claimed_id\'"); - SSOAgentConfigs.setClaimedIdParameterName("claimed_id"); - } - - if (SSOAgentConfigs.isOpenIDLoginEnabled() && SSOAgentConfigs.getAttributesRequestorImplClass() == null) { - LOGGER.info("OpenID.AttributesRequestorImplClass not configured. No attributes of the subject will be fetched"); - } - - } - - public static boolean isSAMLSSOLoginEnabled() { - return samlSSOLoginEnabled; - } - - public static void setSAMLSSOLoginEnabled(Boolean samlSSOLoginEnabled) { - SSOAgentConfigs.samlSSOLoginEnabled = samlSSOLoginEnabled; - } - - public static boolean isOpenIDLoginEnabled() { - return openidLoginEnabled; - } - - public static boolean isSAML2GrantEnabled() { - return saml2GrantEnabled; - } - - public static void setSAML2GrantEnabled(Boolean saml2GrantEnabled) { - SSOAgentConfigs.saml2GrantEnabled = saml2GrantEnabled; - } - - public static String getSessionBeanName() { - return sessionBeanName; - } - - public static void setSessionBeanName(String sessionBeanName) { - SSOAgentConfigs.sessionBeanName = sessionBeanName; - } - - public static String getLoginUrl() { - return loginUrl; - } - - public static void setLoginUrl(String loginUrl) { - SSOAgentConfigs.loginUrl = loginUrl; - } - - public static String getSAMLSSOUrl() { - return samlSSOUrl; - } - - public static void setSAMLSSOUrl(String samlSSOUrl) { - SSOAgentConfigs.samlSSOUrl = samlSSOUrl; - } - - public static String getOpenIdUrl() { - return openIdUrl; - } - - public static void setOpenIdUrl(String openIdUrl) { - SSOAgentConfigs.openIdUrl = openIdUrl; - } - - public static String getSAML2GrantUrl() { - return saml2GrantUrl; - } - - public static void setSAML2GrantUrl(String saml2GrantUrl) { - SSOAgentConfigs.saml2GrantUrl = saml2GrantUrl; - } - - public static String getIssuerId() { - return issuerId; - } - - public static void setIssuerId(String issuerId) { - SSOAgentConfigs.issuerId = issuerId; - } - - public static String getConsumerUrl() { - return consumerUrl; - } - - public static void setConsumerUrl(String consumerUrl) { - SSOAgentConfigs.consumerUrl = consumerUrl; - } - - public static String getIdPUrl() { - return idPUrl; - } - - public static void setIdPUrl(String idPUrl) { - SSOAgentConfigs.idPUrl = idPUrl; - } - - public static String getAttributeConsumingServiceIndex() { - return attributeConsumingServiceIndex; - } - - public static void setAttributeConsumingServiceIndex(String attributeConsumingServiceIndex) { - SSOAgentConfigs.attributeConsumingServiceIndex = attributeConsumingServiceIndex; - } - - public static boolean isSLOEnabled() { - return isSLOEnabled; - } - - public static void setSLOEnabled(Boolean SLOEnabled) { - isSLOEnabled = SLOEnabled; - } - - public static String getLogoutUrl() { - return logoutUrl; - } - - public static void setLogoutUrl(String logoutUrl) { - SSOAgentConfigs.logoutUrl = logoutUrl; - } - - public static boolean isResponseSigned() { - return isResponseSigned; - } - - public static void setResponseSigned(Boolean responseSigned) { - isResponseSigned = responseSigned; - } - - public static boolean isAssertionSigned() { - return isAssertionSigned; - } - - public static void setAssertionSigned(Boolean assertionSigned) { - isAssertionSigned = assertionSigned; - } - - public static boolean isAssertionEncripted() { - return isAssertionEncrypted; - } - - public static boolean isRequestSigned() { - return isRequestSigned; - } - - public static void setRequestSigned(Boolean requestSigned) { - isRequestSigned = requestSigned; - } - - public static boolean isForceAuthn() { - return isForceAuthn; - } - - public static void setForceAuthn(Boolean forceAuthn) { - isForceAuthn = forceAuthn; - } - - public static String getSSOAgentCredentialImplClass() { - return ssoAgentCredentialImplClass; - } - - public static void setSSOAgentCredentialImplClass(String ssoAgentCredentialImplClass) { - SSOAgentConfigs.ssoAgentCredentialImplClass = ssoAgentCredentialImplClass; - } - - private static InputStream getKeyStoreStream() { - return keyStoreStream; - } - - public static void setKeyStoreStream(InputStream keyStoreStream) { - if (SSOAgentConfigs.keyStoreStream == null) { - SSOAgentConfigs.keyStoreStream = keyStoreStream; - } - } - - private static String getKeyStorePassword() { - return keyStorePassword; - } - - public static void setKeyStorePassword(String keyStorePassword) { - SSOAgentConfigs.keyStorePassword = keyStorePassword; - } - - public static KeyStore getKeyStore() throws SSOAgentException { - if (keyStore == null) { - setKeyStore(readKeyStore(getKeyStoreStream(), getKeyStorePassword())); - } - return keyStore; - } - - public static void setKeyStore(KeyStore keyStore) { - SSOAgentConfigs.keyStore = keyStore; - } - - public static String getIdPCertAlias() { - return idPCertAlias; - } - - public static void setIdPCertAlias(String idPCertAlias) { - SSOAgentConfigs.idPCertAlias = idPCertAlias; - } - - public static String getPrivateKeyAlias() { - return privateKeyAlias; - } - - public static void setPrivateKeyAlias(String privateKeyAlias) { - SSOAgentConfigs.privateKeyAlias = privateKeyAlias; - } - - public static String getPrivateKeyPassword() { - return privateKeyPassword; - } - - public static void setPrivateKeyPassword(String privateKeyPassword) { - SSOAgentConfigs.privateKeyPassword = privateKeyPassword; - } - - public static String getTokenEndpoint() { - return tokenEndpoint; - } - - public static void setTokenEndpoint(String tokenEndpoint) { - SSOAgentConfigs.tokenEndpoint = tokenEndpoint; - } - - public static String getOAuth2ClientId() { - return clientId; - } - - public static void setOAuth2ClientId(String clientSecret) { - SSOAgentConfigs.clientSecret = clientSecret; - } - - public static String getOAuth2ClientSecret() { - return clientSecret; - } - - public static void setOAuth2ClientSecret(String clientId) { - SSOAgentConfigs.clientId = clientId; - } - - public static String getOpenIdProviderUrl() { - return openIdProviderUrl; - } - - public static void setOpenIdProviderUrl(String openIdProviderUrl) { - SSOAgentConfigs.openIdProviderUrl = openIdProviderUrl; - } - - public static String getReturnTo() { - return returnTo; - } - - public static void setReturnTo(String returnTo) { - SSOAgentConfigs.returnTo = returnTo; - } - - public static String getClaimedIdParameterName() { - return claimedIdParameterName; - } - - public static void setClaimedIdParameterName(String claimedIdParameterName) { - SSOAgentConfigs.claimedIdParameterName = claimedIdParameterName; - } - - public static String getAttributesRequestorImplClass() { - return attributesRequestorImplClass; - } - - public static void setAttributesRequestorImplClass(String attributesRequestorImplClass) { - SSOAgentConfigs.attributesRequestorImplClass = attributesRequestorImplClass; - } - - public static void setOpenidLoginEnabled(Boolean openidLoginEnabled) { - SSOAgentConfigs.openidLoginEnabled = openidLoginEnabled; - } - - public static void setAssertionEncrypted(Boolean assertionEncrypted) { - isAssertionEncrypted = assertionEncrypted; - } - - public static void setKeyStoreStream(String keyStore) throws SSOAgentException { - try { - SSOAgentConfigs.keyStoreStream = new FileInputStream(keyStore); - } catch (FileNotFoundException e) { - if (log.isDebugEnabled()) { - log.debug("File not found : ", e); - } - - throw new SSOAgentException("Cannot find file " + keyStore); - } - } - - public static String getRequestQueryParameters() { - return requestQueryParameters; - } - - public static String getAddExtension() { - return addExtension; - } - - public static void setAddExtension(String addExtension) { - SSOAgentConfigs.addExtension = addExtension; - } - - /** - * get the key store instance - * - * @param is KeyStore InputStream - * @param storePassword password of key store - * @return KeyStore instant - * @throws SSOAgentException if fails to load key store - */ - private static KeyStore readKeyStore(InputStream is, String storePassword) throws SSOAgentException { - - if (storePassword == null) { - throw new 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 SSOAgentException("Error while loading key store file", e); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException ignored) { - - throw new SSOAgentException("Error while closing input stream of key store", ignored); - } - } - } - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentConstants.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentConstants.java deleted file mode 100644 index a829acc..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentConstants.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent.util; - -public class SSOAgentConstants { - - public static final String KEY_STORE_PASSWORD = "KeyStorePassword"; - public static final String IDP_PUBLIC_CERT = "IdPPublicCertAlias"; - public static final String PRIVATE_KEY_ALIAS = "PrivateKeyAlias"; - public static final String PRIVATE_KEY_PASSWORD = "PrivateKeyPassword"; - - public static final String LOGGER_NAME = "org.wso2.carbon.identity.sso.agent"; - - public static final String SESSION_BEAN_NAME = "org.wso2.carbon.identity.sso.agent.LoggedInSessionBean"; - public static final String CONFIG_BEAN_NAME = "org.wso2.carbon.identity.sso.agent.SSOAgentConfig"; - - public static final String SHOULD_GO_TO_WELCOME_PAGE = "shouldGoToWelcomePage"; - public static final String PROPERTY_FILE_PARAMETER_NAME = "property-file"; - public static final String CERTIFICATE_FILE_PARAMETER_NAME = "certificate-file"; - - public static class SAML2SSO { - - private SAML2SSO() {} - - public static final String HTTP_POST_PARAM_SAML2_AUTH_REQ = "SAMLRequest"; - public static final String HTTP_POST_PARAM_SAML2_RESP = "SAMLResponse"; - public static final String SAML2_ARTIFACT_RESP = "SAMLart"; - public static final String SUCCESS_CODE = "urn:oasis:names:tc:SAML:2.0:status:Success"; - } - - public static class OpenID { - - public static final String OPENID_MODE = "openid.mode"; - private OpenID() {} - - } - - public static class OAuth2 { - public static final String SAML2_BEARER_GRANT_TYPE = - "urn:ietf:params:oauth:grant-type:saml2-bearer"; - - private OAuth2() {} - } - - private SSOAgentConstants() {} - - public static class SSOAgentConfig { - - public static final String ENABLE_SAML2_SSO_LOGIN = "EnableSAML2SSOLogin"; - public static final String ENABLE_OPENID_SSO_LOGIN = "EnableOpenIDLogin"; - public static final String ENABLE_OAUTH2_SAML2_OAUTH2_GRANT = "EnableOAuth2SAML2Grant"; - public static final String SAML2_SSO_URL = "SAML2SSOURL"; - public static final String OPENID_URL = "OpenIdURL"; - public static final String OAUTH2_SAML2_GRANT_URL = "OAuth2SAML2GrantURL"; - public static final String SKIP_URIS = "SkipURIs"; - public static final String QUERY_PARAMS = "QueryParams"; - public static final String PASSWORD_FILEPATH = "/conf/password_temp.txt"; - - private SSOAgentConfig() {} - - public static class SAML2 { - - public static final String HTTP_BINDING = "SAML2.HTTPBinding"; - public static final String SP_ENTITY_ID = "SAML2.SPEntityId"; - public static final String ACS_URL = "SAML2.AssertionConsumerURL"; - public static final String IDP_ENTITY_ID = "SAML2.IdPEntityId"; - public static final String IDP_URL = "SAML2.IdPURL"; - public static final String ATTRIBUTE_CONSUMING_SERVICE_INDEX = - "SAML2.AttributeConsumingServiceIndex"; - public static final String ENABLE_SLO = "SAML2.EnableSLO"; - public static final String SLO_URL = "SAML2.SLOURL"; - public static final String ENABLE_ASSERTION_SIGNING = - "SAML2.EnableAssertionSigning"; - public static final String ENABLE_ASSERTION_ENCRYPTION = - "SAML2.EnableAssertionEncryption"; - public static final String ENABLE_RESPONSE_SIGNING = - "SAML2.EnableResponseSigning"; - public static final String ENABLE_REQUEST_SIGNING = "SAML2.EnableRequestSigning"; - public static final String IS_PASSIVE_AUTHN = "SAML2.IsPassiveAuthn"; - public static final String IS_FORCE_AUTHN = "SAML2.IsForceAuthn"; - public static final String RELAY_STATE = "SAML2.RelayState"; - public static final String POST_BINDING_REQUEST_HTML_PAYLOAD = - "SAML2.PostBindingRequestHTMLPayload"; - public static final String POST_BINDING_REQUEST_HTML_FILE_PATH = - "SAML2.PostBindingRequestHTMLFilePath"; - public static final String SIGNATURE_VALIDATOR = "SAML2.SignatureValidatorImplClass"; - public static final String TIME_STAMP_SKEW = "SAML2.TimestampSkew"; - - public static final String SOAP_ACTION_PARAM_KEY = "SOAPAction"; - public static final String ACCEPT_PARAM_KEY = "Accept"; - public static final String CONTENT_TYPE_PARAM_KEY = "Content-Type"; - public static final String PRAGMA_PARAM_KEY = "Pragma"; - public static final String CACHE_CONTROL_PARAM_KEY = "Cache-Control"; - public static final String IS_ARTIFACT_RESOLVE_REQ_SIGNED = "ISArtifactResolveReqSigned"; - public static final String ARTIFACT_RESOLVE_URL = "SAML2.ArtifactResolveUrl"; - public static final String ENABLE_ARTIFACT_RESOLVE_SIGNING = "SAML2.EnableArtifactResolveSigning"; - - private SAML2() {} - } - - public static class OpenID { - - public static final String PROVIDER_URL = "OpenId.ProviderURL"; - public static final String RETURN_TO_URL = "OpenId.ReturnToURL"; - public static final String CLAIMED_ID = "OpenId.ClaimedId"; - public static final String ENABLE_ATTRIBUTE_EXCHANGE = "OpenId.EnableAttributeExchange"; - public static final String ENABLE_DUMB_MODE = "OpenId.EnableDumbMode"; - - private OpenID() {} - } - - public static class OIDC { - - public static final String CONSUMER_KEY = "consumerKey"; - public static final String CONSUMER_SECRET = "consumerSecret"; - public static final String CALL_BACK_URL = "callBackUrl"; - public static final String OAUTH2_GRANT_TYPE = "grantType"; - public static final String OAUTH2_AUTHZ_ENDPOINT = "authorizeEndpoint"; - public static final String OIDC_LOGOUT_ENDPOINT = "logoutEndpoint"; - public static final String OIDC_SESSION_IFRAME_ENDPOINT = "sessionIFrameEndpoint"; - public static final String SCOPE = "scope"; - public static final String POST_LOGOUT_REDIRECT_RUI = "postLogoutRedirectUri"; - - private OIDC() {} - } - - public static class OAuth2 { - - public static final String CLIENT_ID = "OAuth2.ClientId"; - public static final String CLIENT_SECRET = "OAuth2.ClientSecret"; - public static final String TOKEN_URL = "OAuth2.TokenURL"; - - private OAuth2() {} - } - - } - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentDataHolder.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentDataHolder.java deleted file mode 100644 index 88f33b1..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentDataHolder.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.util; - -import org.openid4java.consumer.ConsumerManager; - -public class SSOAgentDataHolder { - - private Object signatureValidator = null; - - private ConsumerManager consumerManager; - private static SSOAgentDataHolder instance = new SSOAgentDataHolder(); - - private SSOAgentDataHolder() { - } - - public Object getSignatureValidator() { - return signatureValidator; - } - - public void setSignatureValidator(Object signatureValidator) { - this.signatureValidator = signatureValidator; - } - - - public ConsumerManager getConsumerManager() { - return consumerManager; - } - - public static SSOAgentDataHolder getInstance(){ - return instance; - } - - - public void setConsumerManager(ConsumerManager consumerManager) { - this.consumerManager = consumerManager; - } - - -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentFilterUtils.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentFilterUtils.java deleted file mode 100644 index 797f62d..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentFilterUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.agent.util; - -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; - -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -/** - * Comprised of Util methods for SSOAgentFilters. - */ -public class SSOAgentFilterUtils { - - public static SSOAgentConfig getSSOAgentConfig(FilterConfig filterConfig) throws SSOAgentException{ - - return getSSOAgentConfig(filterConfig.getServletContext()); - } - - public static SSOAgentConfig getSSOAgentConfig(ServletContext application) throws SSOAgentException { - - // Make sure SSOAgentConstants.CONFIG_BEAN_NAME attribute is added on servlet context initialization. - // It should be in the type of SSOAgentConfig. - Object configBeingAttribute = application.getAttribute(SSOAgentConstants.CONFIG_BEAN_NAME); - if (!(configBeingAttribute instanceof SSOAgentConfig)) { - throw new SSOAgentException("Cannot find " + SSOAgentConstants.CONFIG_BEAN_NAME + - " attribute of SSOAgentConfig type in the servletContext. Cannot proceed further."); - } - - return (SSOAgentConfig) configBeingAttribute; - } - - public static boolean shouldGoToWelcomePage(HttpServletRequest request) { - - if (request == null) { - return true; - } - - //check should go to welcome page, if so go to welcome page - Object shouldGoToWelcomePage = request.getAttribute(SSOAgentConstants.SHOULD_GO_TO_WELCOME_PAGE); - return shouldGoToWelcomePage instanceof String && Boolean.parseBoolean((String) shouldGoToWelcomePage); - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentRequestResolver.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentRequestResolver.java deleted file mode 100644 index 36ed386..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentRequestResolver.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.util; - -import org.opensaml.saml.common.xml.SAMLConstants; -import org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean; -import org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class SSOAgentRequestResolver { - - SSOAgentConfig ssoAgentConfig = null; - HttpServletRequest request = null; - - public SSOAgentRequestResolver(HttpServletRequest request, HttpServletResponse response, - SSOAgentConfig ssoAgentConfig) { - - this.request = request; - this.ssoAgentConfig = ssoAgentConfig; - } - - public boolean isSLORequest() { - - return ssoAgentConfig.isSAML2SSOLoginEnabled() && - request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ) != null; - } - - // This could be either SAML Response for a SSO SAML Request by the client application - // or a SAML Response for a SLO SAML Request from a SP - public boolean isSAML2SSOResponse() { - - return ssoAgentConfig.isSAML2SSOLoginEnabled() && - request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP) != null; - } - - public boolean isSAML2ArtifactResponse() { - - return ssoAgentConfig.isSAML2SSOLoginEnabled() && - request.getParameter(SSOAgentConstants.SAML2SSO.SAML2_ARTIFACT_RESP) != null; - } - - public boolean isOpenIdLoginResponse() { - return ssoAgentConfig.isOpenIdLoginEnabled() && - ssoAgentConfig.getOpenId().getMode() != null && - !ssoAgentConfig.getOpenId().getMode().trim().isEmpty(); - } - - public boolean isSLOURL() { - return ssoAgentConfig.isSAML2SSOLoginEnabled() && - ssoAgentConfig.getSAML2().isSLOEnabled() && - request.getRequestURI().endsWith(ssoAgentConfig.getSAML2().getSLOURL()); - } - - public boolean isHttpPostBinding() { - return ssoAgentConfig.getSAML2().getHttpBinding() != null && - SAMLConstants.SAML2_POST_BINDING_URI.equals( - ssoAgentConfig.getSAML2().getHttpBinding()); - } - - public boolean isSAML2SSOURL() { - return ssoAgentConfig.isSAML2SSOLoginEnabled() && - request.getRequestURI().endsWith(ssoAgentConfig.getSAML2SSOURL()); - } - - public boolean isOpenIdURL() { - return ssoAgentConfig.isOpenIdLoginEnabled() && - request.getRequestURI().endsWith(ssoAgentConfig.getOpenIdURL()) && - ssoAgentConfig.getOpenId().getClaimedId() != null && - !ssoAgentConfig.getOpenId().getClaimedId().trim().isEmpty(); - } - - public boolean isPassiveAuthnRequest() { - return (ssoAgentConfig.isSAML2SSOLoginEnabled() || - ssoAgentConfig.isOpenIdLoginEnabled()) && - (request.getSession(false) == null || - request.getSession(false).getAttribute(SSOAgentConstants.SESSION_BEAN_NAME) == null); - } - - public boolean isSAML2OAuth2GrantRequest() { - return ssoAgentConfig.isSAML2SSOLoginEnabled() && - ssoAgentConfig.isOAuth2SAML2GrantEnabled() && - request.getRequestURI().endsWith(ssoAgentConfig.getOAuth2SAML2GrantURL()) && - request.getSession(false) != null && - request.getSession(false).getAttribute(SSOAgentConstants.SESSION_BEAN_NAME) != null && - ((LoggedInSessionBean) request.getSession(false).getAttribute( - SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO() != null && - ((LoggedInSessionBean) request.getSession(false).getAttribute( - SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO() - .getAssertion() != null; - } - - public boolean isURLToSkip() { - return ssoAgentConfig.getSkipURIs().contains(request.getRequestURI()); - } -} diff --git a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentUtils.java b/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentUtils.java deleted file mode 100644 index 87b6180..0000000 --- a/components/org.wso2.carbon.identity.sso.agent/src/main/java/org/wso2/carbon/identity/sso/agent/util/SSOAgentUtils.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.wso2.carbon.identity.sso.agent.util; - -import org.apache.commons.lang.StringUtils; -import org.apache.xerces.impl.Constants; -import org.apache.xerces.util.SecurityManager; -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xml.security.signature.XMLSignature; -import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; -import org.opensaml.saml.saml2.core.ArtifactResolve; -import org.opensaml.saml.saml2.core.AuthnRequest; -import org.opensaml.saml.saml2.core.LogoutRequest; -import org.opensaml.core.config.InitializationException; -import org.opensaml.core.xml.XMLObject; -import org.opensaml.core.xml.XMLObjectBuilder; -import org.opensaml.core.xml.io.Marshaller; -import org.opensaml.core.xml.io.MarshallerFactory; -import org.opensaml.core.xml.io.Unmarshaller; -import org.opensaml.core.xml.io.UnmarshallerFactory; -import org.opensaml.core.xml.io.UnmarshallingException; -import org.opensaml.security.x509.X509Credential; -import org.opensaml.xmlsec.signature.KeyInfo; -import org.opensaml.xmlsec.signature.SignableXMLObject; -import org.opensaml.xmlsec.signature.Signature; -import org.opensaml.xmlsec.signature.support.Signer; -import org.opensaml.xmlsec.signature.X509Data; -import net.shibboleth.utilities.java.support.codec.Base64Support; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.w3c.dom.bootstrap.DOMImplementationRegistry; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSOutput; -import org.w3c.dom.ls.LSSerializer; -import org.wso2.carbon.identity.saml.common.util.SAMLInitializer; -import org.wso2.carbon.identity.sso.agent.exception.SSOAgentException; -import org.xml.sax.SAXException; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.Writer; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.cert.CertificateEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -public class SSOAgentUtils { - - private static Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); - private static boolean isBootStrapped = false; - - private static Random random = new Random(); - private static final int ENTITY_EXPANSION_LIMIT = 0; - - private SSOAgentUtils() { - } - - /** - * Generates a unique Id for Authentication Requests - * - * @return generated unique ID - */ - - public static String createID() { - - byte[] bytes = new byte[20]; // 160 bit - - random.nextBytes(bytes); - - char[] charMapping = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'}; - - char[] chars = new char[40]; - - for (int i = 0; i < bytes.length; i++) { - int left = (bytes[i] >> 4) & 0x0f; - int right = bytes[i] & 0x0f; - chars[i * 2] = charMapping[left]; - chars[i * 2 + 1] = charMapping[right]; - } - - return String.valueOf(chars); - } - - public static void doBootstrap() throws SSOAgentException { - - if (!isBootStrapped) { - try { - SAMLInitializer.doBootstrap(); - isBootStrapped = true; - } catch (InitializationException e) { - throw new SSOAgentException("Error in bootstrapping the OpenSAML3 library", e); - } - } - - } - - /** - * Sign the SAML AuthnRequest message - * - * @param authnRequest - * @param signatureAlgorithm - * @param cred - * @return - * @throws SSOAgentException - */ - public static AuthnRequest setSignature(AuthnRequest authnRequest, String signatureAlgorithm, - X509Credential cred) throws SSOAgentException { - doBootstrap(); - return setSignatureValue(authnRequest, signatureAlgorithm, cred); - } - - /** - * 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 { - - return setSignatureValue(logoutRequest, signatureAlgorithm, cred); - } - - /** - * Sign SAML2 Artifact Resolve. - * - * @param artifactResolve ArtifactResolve object to be signed. - * @param signatureAlgorithm Signature algorithm. - * @param cred X509 Credential. - * @return Signed Artifact Resolve object. - * @throws SSOAgentException - */ - public static ArtifactResolve setSignature(ArtifactResolve artifactResolve, String signatureAlgorithm, - X509Credential cred) throws SSOAgentException { - - return setSignatureValue(artifactResolve, signatureAlgorithm, cred); - } - - /** - * Add signature to any singable XML object. - * @param xmlObject Singable xml object. - * @param signatureAlgorithm Signature algorithm to be used. - * @param cred X509 Credentials. - * @param Singable XML object with signature. - * @return Singable XML object with signature. - * @throws SSOAgentException If error occurred. - */ - public static T setSignatureValue(T xmlObject, String signatureAlgorithm, - X509Credential cred) - throws SSOAgentException { - - try { - Signature signature = setSignatureRaw(signatureAlgorithm, cred); - xmlObject.setSignature(signature); - - List signatureList = new ArrayList<>(); - signatureList.add(signature); - - // Marshall and Sign - MarshallerFactory marshallerFactory = - XMLObjectProviderRegistrySupport.getMarshallerFactory(); - Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); - - marshaller.marshall(xmlObject); - - org.apache.xml.security.Init.init(); - Signer.signObjects(signatureList); - return xmlObject; - } catch (Exception e) { - throw new SSOAgentException("Error while signing the SAML Request message", e); - } - } - - 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.xmlsec.signature.X509Certificate cert = - (org.opensaml.xmlsec.signature.X509Certificate) buildXMLObject(org.opensaml.xmlsec.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); - } - } - - 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 = Base64Support.encode(signatureByteArray, - Base64Support.UNCHUNKED); - httpQueryString.append("&Signature=" - + URLEncoder.encode(signatureBase64encodedString, "UTF-8").trim()); - } catch (Exception e) { - throw new SSOAgentException("Error applying SAML2 Redirect Binding signature", e); - } - } - - /** - * Builds SAML Elements - * - * @param objectQName - * @return - * @throws SSOAgentException - */ - private static XMLObject buildXMLObject(QName objectQName) throws SSOAgentException { - doBootstrap(); - XMLObjectBuilder builder = - XMLObjectProviderRegistrySupport.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()); - } - - public static void sendPostResponse(HttpServletRequest request, HttpServletResponse response, - String htmlPayload) - throws SSOAgentException { - - Writer writer = null; - try { - writer = response.getWriter(); - writer.write(htmlPayload); - response.flushBuffer(); - } catch (IOException e) { - throw new SSOAgentException("Error occurred while writing to HttpServletResponse", e); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (IOException e) { - LOGGER.log(Level.WARNING, "Error occurred while closing Writer", e); - } - } - } - } - - /** - * Serializing a SAML2 object into a String. - * - * @param xmlObject object that needs to serialized. - * @return serialized object - * @throws SSOAgentException - */ - public static String marshall(XMLObject xmlObject) throws SSOAgentException { - - try { - MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport - .getMarshallerFactory(); - Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); - Element element = marshaller.marshall(xmlObject); - - ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream(); - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - LSOutput output = impl.createLSOutput(); - output.setByteStream(byteArrayOutputStrm); - writer.write(element, output); - return byteArrayOutputStrm.toString(); - } catch (Exception e) { - throw new SSOAgentException("Error Serializing the SAML Response", e); - } - } - - public static XMLObject unmarshall(String saml2SSOString) throws SSOAgentException { - - doBootstrap(); - - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilderFactory.setXIncludeAware(false); - documentBuilderFactory.setExpandEntityReferences(false); - try { - documentBuilderFactory - .setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false); - documentBuilderFactory - .setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); - documentBuilderFactory - .setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false); - documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - - } catch (ParserConfigurationException e) { - LOGGER.log(Level.SEVERE, - "Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " + - Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE + - " or secure-processing."); - } - - org.apache.xerces.util.SecurityManager securityManager = new SecurityManager(); - securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); - documentBuilderFactory - .setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager); - - try { - documentBuilderFactory.setIgnoringComments(true); - Document document = getDocument(documentBuilderFactory, saml2SSOString); - if (isSignedWithComments(document)) { - documentBuilderFactory.setIgnoringComments(false); - document = getDocument(documentBuilderFactory, saml2SSOString); - } - Element element = document.getDocumentElement(); - UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory(); - Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); - return unmarshaller.unmarshall(element); - } catch (ParserConfigurationException e) { - throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); - } catch (UnmarshallingException e) { - throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); - } catch (SAXException e) { - throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); - } catch (IOException e) { - throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); - } - - } - - /** - * Return whether SAML Assertion has the canonicalization method - * set to 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments'. - * - * @param document - * @return true if canonicalization method equals to 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments' - */ - private static boolean isSignedWithComments(Document document) { - - XPath xPath = XPathFactory.newInstance().newXPath(); - try { - String assertionId = (String) xPath.compile("//*[local-name()='Assertion']/@ID") - .evaluate(document, XPathConstants.STRING); - - if (StringUtils.isBlank(assertionId)) { - return false; - } - - NodeList nodeList = ((NodeList) xPath.compile( - "//*[local-name()='Assertion']" + - "/*[local-name()='Signature']" + - "/*[local-name()='SignedInfo']" + - "/*[local-name()='Reference'][@URI='#" + assertionId + "']" + - "/*[local-name()='Transforms']" + - "/*[local-name()='Transform']" + - "[@Algorithm='http://www.w3.org/2001/10/xml-exc-c14n#WithComments']") - .evaluate(document, XPathConstants.NODESET)); - return nodeList != null && nodeList.getLength() > 0; - } catch (XPathExpressionException e) { - String message = "Failed to find the canonicalization algorithm of the assertion. Defaulting to: " + - "http://www.w3.org/2001/10/xml-exc-c14n#"; - LOGGER.log(Level.WARNING, message); - return false; - } - } - - private static Document getDocument(DocumentBuilderFactory documentBuilderFactory, String samlString) - throws IOException, SAXException, ParserConfigurationException { - - DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); - ByteArrayInputStream inputStream = new ByteArrayInputStream(samlString.getBytes()); - return docBuilder.parse(inputStream); - } -} diff --git a/components/org.wso2.carbon.identity.sso.encryptor/pom.xml b/components/org.wso2.carbon.identity.sso.encryptor/pom.xml deleted file mode 100644 index 71e8872..0000000 --- a/components/org.wso2.carbon.identity.sso.encryptor/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - org.wso2.carbon.identity.agent.sso.java - identity-agent-sso - ../../pom.xml - 5.5.9-SNAPSHOT - - - 4.0.0 - org.wso2.encryptor - jar - - - - - maven-assembly-plugin - - - - org.wso2.carbon.identity.sso.encryptor.Encryption - - - - jar-with-dependencies - - - - - - - - - - org.bouncycastle - bcprov-jdk15on - - - commons-codec - commons-codec - ${commons-codec.version} - - - org.jetbrains - annotations-java5 - RELEASE - - - - diff --git a/components/org.wso2.carbon.identity.sso.encryptor/src/main/java/org/wso2/carbon/identity/sso/encryptor/EncryptingException.java b/components/org.wso2.carbon.identity.sso.encryptor/src/main/java/org/wso2/carbon/identity/sso/encryptor/EncryptingException.java deleted file mode 100644 index 1f5901a..0000000 --- a/components/org.wso2.carbon.identity.sso.encryptor/src/main/java/org/wso2/carbon/identity/sso/encryptor/EncryptingException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.encryptor; - -/** - * Invalid encryption exception. - */ -public class EncryptingException extends Exception { - - public EncryptingException(String message) { - super(message); - } - - public EncryptingException(String message, Exception ex) { - super(message, ex); - } - -} diff --git a/components/org.wso2.carbon.identity.sso.encryptor/src/main/java/org/wso2/carbon/identity/sso/encryptor/Encryption.java b/components/org.wso2.carbon.identity.sso.encryptor/src/main/java/org/wso2/carbon/identity/sso/encryptor/Encryption.java deleted file mode 100644 index b882080..0000000 --- a/components/org.wso2.carbon.identity.sso.encryptor/src/main/java/org/wso2/carbon/identity/sso/encryptor/Encryption.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.encryptor; - -import org.apache.commons.codec.binary.Base64; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; -import org.bouncycastle.crypto.params.KeyParameter; - -import java.io.Console; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -/** - * Class is used for encrypt a password using AES. - */ -public class Encryption { - - private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; - private static final String SALT = "84B03D034B409D4E"; - private static final int KEY_DERIVATION_ITERATION_COUNT = 4096; - private static final int KEY_SIZE = 128; - - /** - * Encrypt and encrypt the plain text. - * - * @param secret Password to be encrypted. - * @param cipherKey Password use for encryption. - * @return Encrypted value. - * @throws Exception If an error occurred while encrypting. - */ - - private static String encrypt(String secret, char[] cipherKey) throws EncryptingException { - - try { - - // Change char array to byte array. - ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(cipherKey)); - byte[] secretKey = new byte[buf.limit()]; - buf.get(secretKey); - - PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); - gen.init(secretKey, SALT.getBytes(), KEY_DERIVATION_ITERATION_COUNT); - byte[] key = ((KeyParameter) gen.generateDerivedParameters(KEY_SIZE)).getKey(); - - SecretKey secretKeySpec = new SecretKeySpec(key, "AES"); - Cipher cipher = Cipher.getInstance(ALGORITHM); - - // Create an initialization vector with Cipher's block size. - byte[] iv = new byte[cipher.getBlockSize()]; - IvParameterSpec ivParams = new IvParameterSpec(iv); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParams); - - // Encrypt the password. - byte[] encryptedVal = cipher.doFinal(secret.getBytes(StandardCharsets.UTF_8)); - - // Encode the password. - byte[] encodedVal = new Base64().encode(encryptedVal); - return new String(encodedVal, StandardCharsets.UTF_8); - } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | - NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException ex) { - throw new EncryptingException("Error while encrypting", ex); - } - } - - /** - * Main entry point. - * - * @param args The password you wanted to encrypt. - * @throws Exception If an error occurred. - */ - public static void main(String[] args) { - - String encryptedVal; - Console console = System.console(); - if (console == null) { - System.err.println("Couldn't get Console instance"); - System.exit(-1); - } - - // Get the password used for encryption. - char passwordArray[] = console.readPassword("Please Enter a password you want to use for the encryption: "); - try { - encryptedVal = encrypt(args[0], passwordArray); - Files.write(Paths.get("./encrypted_password.txt"), encryptedVal.getBytes(StandardCharsets.UTF_8)); - } catch (EncryptingException | IOException ex) { - System.err.println("Error occurred while encrypting or while writing in to the file "); - ex.printStackTrace(); - return; - } - Arrays.fill(passwordArray, (char) 0); - System.out.println("File with encrypted value created successfully in your current location"); - } -} diff --git a/components/org.wso2.carbon.identity.sso.tomcat.server/pom.xml b/components/org.wso2.carbon.identity.sso.tomcat.server/pom.xml deleted file mode 100644 index 3f011ea..0000000 --- a/components/org.wso2.carbon.identity.sso.tomcat.server/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - identity-agent-sso - org.wso2.carbon.identity.agent.sso.java - 5.5.9-SNAPSHOT - ../../pom.xml - - 4.0.0 - - org.wso2.carbon.identity.sso.tomcat.server - bundle - WSO2 Carbon - SAML2 SSO Tomcat Server - http://www.wso2.com - - - - org.wso2.carbon.identity.agent.sso.java - org.wso2.carbon.identity.sso.agent.saml - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - org.wso2.carbon.identity.sso.tomcat.server.internal - - !org.wso2.carbon.identity.sso.tomcat.server.internal, - org.wso2.carbon.identity.sso.tomcat.server.*; - version="${identity.sso.agent.package.export.version}", - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - diff --git a/components/org.wso2.carbon.identity.sso.tomcat.server/src/main/java/org/wso2/carbon/identity/sso/tomcat/server/SAML2SSOAgentFilter.java b/components/org.wso2.carbon.identity.sso.tomcat.server/src/main/java/org/wso2/carbon/identity/sso/tomcat/server/SAML2SSOAgentFilter.java deleted file mode 100644 index 4becdba..0000000 --- a/components/org.wso2.carbon.identity.sso.tomcat.server/src/main/java/org/wso2/carbon/identity/sso/tomcat/server/SAML2SSOAgentFilter.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.tomcat.server; - -import org.opensaml.saml.saml2.core.LogoutResponse; -import org.wso2.carbon.identity.sso.agent.saml.SAML2SSOManager; -import org.wso2.carbon.identity.sso.agent.saml.bean.LoggedInSessionBean; -import org.wso2.carbon.identity.sso.agent.saml.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.saml.exception.InvalidSessionException; -import org.wso2.carbon.identity.sso.agent.saml.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.saml.util.SSOAgentConstants; -import org.wso2.carbon.identity.sso.agent.saml.util.SSOAgentFilterUtils; -import org.wso2.carbon.identity.sso.agent.saml.util.SSOAgentRequestResolver; -import org.wso2.carbon.identity.sso.agent.saml.util.SSOAgentUtils; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -/** - * Servlet Filter implementation class SAML2SSOAgentFilter. - */ -public class SAML2SSOAgentFilter implements Filter { - - private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); - protected FilterConfig filterConfig = null; - - /** - * @see Filter#init(FilterConfig) - */ - @Override - public void init(FilterConfig fConfig) throws ServletException { - - this.filterConfig = fConfig; - } - - /** - * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) - */ - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, - FilterChain chain) throws IOException, ServletException { - - HttpServletRequest request = (HttpServletRequest) servletRequest; - HttpServletResponse response = (HttpServletResponse) servletResponse; - - try { - SSOAgentConfig ssoAgentConfig = SSOAgentFilterUtils.getSSOAgentConfig(filterConfig); - - SSOAgentRequestResolver resolver = - new SSOAgentRequestResolver(request, response, ssoAgentConfig); - - if (resolver.isURLToSkip()) { - chain.doFilter(servletRequest, servletResponse); - return; - } - - SAML2SSOManager samlSSOManager; - - if (resolver.isSLORequest()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - LogoutResponse logoutResponse = samlSSOManager.doSLO(request); - String encodedRequestMessage = samlSSOManager.buildPostResponse(logoutResponse); - SSOAgentUtils.sendPostResponse(request, response, encodedRequestMessage); - return; - } else if (resolver.isSAML2SSOResponse()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - try { - samlSSOManager.processResponse(request, response); - } catch (SSOAgentException e) { - handleException(request, e); - } - - } else if (resolver.isSAML2ArtifactResponse()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - try { - samlSSOManager.processArtifactResponse(request); - } catch (SSOAgentException e) { - handleException(request, e); - } - } else if (resolver.isSLOURL()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - if (resolver.isHttpPostBinding()) { - - boolean isPassiveAuth = ssoAgentConfig.getSAML2().isPassiveAuthn(); - ssoAgentConfig.getSAML2().setPassiveAuthn(false); - String htmlPayload = samlSSOManager.buildPostRequest(request, response, true); - ssoAgentConfig.getSAML2().setPassiveAuthn(isPassiveAuth); - SSOAgentUtils.sendPostResponse(request, response, htmlPayload); - - } else { - //if "SSOAgentConstants.HTTP_BINDING_PARAM" is not defined, default to redirect - boolean isPassiveAuth = ssoAgentConfig.getSAML2().isPassiveAuthn(); - ssoAgentConfig.getSAML2().setPassiveAuthn(false); - String redirectUrl = samlSSOManager.buildRedirectRequest(request, true); - ssoAgentConfig.getSAML2().setPassiveAuthn(isPassiveAuth); - response.sendRedirect(redirectUrl); - } - return; - - } else if (resolver.isSAML2SSOURL()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - if (resolver.isHttpPostBinding()) { - String htmlPayload = samlSSOManager.buildPostRequest(request, response, false); - SSOAgentUtils.sendPostResponse(request, response, htmlPayload); - return; - } - response.sendRedirect(samlSSOManager.buildRedirectRequest(request, false)); - return; - - } else if (resolver.isPassiveAuthnRequest()) { - - samlSSOManager = new SAML2SSOManager(ssoAgentConfig); - boolean isPassiveAuth = ssoAgentConfig.getSAML2().isPassiveAuthn(); - ssoAgentConfig.getSAML2().setPassiveAuthn(true); - String redirectUrl = samlSSOManager.buildRedirectRequest(request, false); - ssoAgentConfig.getSAML2().setPassiveAuthn(isPassiveAuth); - response.sendRedirect(redirectUrl); - return; - } - String indexPage = ssoAgentConfig.getIndexPage(); - if (request.getSession(false) != null && - request.getSession(false).getAttribute(SSOAgentConstants.SESSION_BEAN_NAME) == null) { - request.getSession().invalidate(); - response.sendRedirect(indexPage); - return; - } - - HttpSession session = request.getSession(); - LoggedInSessionBean - sessionBean = (LoggedInSessionBean) session.getAttribute(SSOAgentConstants.SESSION_BEAN_NAME); - - if (sessionBean == null || sessionBean.getSAML2SSO() == null) { - response.sendRedirect(indexPage); - return; - } - // pass the request along the filter chain - chain.doFilter(request, response); - - } catch (InvalidSessionException e) { - // Redirect to the index page when session is expired or user already logged out. - LOGGER.log(Level.FINE, "Invalid Session!", e); - response.sendRedirect(filterConfig.getServletContext().getContextPath()); - } - } - - /** - * @see Filter#destroy() - */ - @Override - public void destroy() { - - return; - } - - protected void handleException(HttpServletRequest request, SSOAgentException e) - throws SSOAgentException { - - if (request.getSession(false) != null) { - request.getSession(false).removeAttribute(SSOAgentConstants.SESSION_BEAN_NAME); - } - throw e; - } - -} diff --git a/components/org.wso2.carbon.identity.sso.tomcat.server/src/main/java/org/wso2/carbon/identity/sso/tomcat/server/SSOAgentContextEventListener.java b/components/org.wso2.carbon.identity.sso.tomcat.server/src/main/java/org/wso2/carbon/identity/sso/tomcat/server/SSOAgentContextEventListener.java deleted file mode 100644 index c6a7ad6..0000000 --- a/components/org.wso2.carbon.identity.sso.tomcat.server/src/main/java/org/wso2/carbon/identity/sso/tomcat/server/SSOAgentContextEventListener.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.sso.tomcat.server; - -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.sso.agent.saml.bean.SSOAgentConfig; -import org.wso2.carbon.identity.sso.agent.saml.exception.SSOAgentException; -import org.wso2.carbon.identity.sso.agent.saml.security.SSOAgentX509Credential; -import org.wso2.carbon.identity.sso.agent.saml.security.SSOAgentX509KeyStoreCredential; -import org.wso2.carbon.identity.sso.agent.saml.util.SSOAgentConstants; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -/** - * Context EventListner Class for SAML2 SSO. - */ -public class SSOAgentContextEventListener implements ServletContextListener { - - private static Logger logger = Logger.getLogger(SSOAgentContextEventListener.class.getName()); - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - - Properties properties = new Properties(); - try { - - ServletContext servletContext = servletContextEvent.getServletContext(); - - // Load the client property-file, if not specified throw SSOAgentException - String propertyFileName = servletContext.getInitParameter(SSOAgentConstants.PROPERTY_FILE_PARAMETER_NAME); - if (StringUtils.isNotBlank(propertyFileName)) { - properties.load(servletContextEvent.getServletContext(). - getResourceAsStream("/WEB-INF/classes/" + propertyFileName)); - } else { - throw new SSOAgentException(SSOAgentConstants.PROPERTY_FILE_PARAMETER_NAME - + " context-param is not specified in the web.xml"); - } - - // Load the client security certificate, if not specified throw SSOAgentException. - String certificateFileName = servletContext.getInitParameter(SSOAgentConstants - .CERTIFICATE_FILE_PARAMETER_NAME); - InputStream keyStoreInputStream; - if (StringUtils.isNotBlank(certificateFileName)) { - keyStoreInputStream = servletContext.getResourceAsStream("/WEB-INF/classes/" - + certificateFileName); - } else { - throw new SSOAgentException(SSOAgentConstants.CERTIFICATE_FILE_PARAMETER_NAME - + " context-param is not specified in the web.xml"); - } - - SSOAgentX509Credential credential = new SSOAgentX509KeyStoreCredential(keyStoreInputStream, - properties.getProperty(SSOAgentConstants.KEY_STORE_PASSWORD).toCharArray(), - properties.getProperty(SSOAgentConstants.IDP_PUBLIC_CERT), - properties.getProperty(SSOAgentConstants.PRIVATE_KEY_ALIAS), - properties.getProperty(SSOAgentConstants.PRIVATE_KEY_PASSWORD).toCharArray()); - - SSOAgentConfig config = new SSOAgentConfig(); - config.initConfig(properties); - config.getSAML2().setSSOAgentX509Credential(credential); - servletContext.setAttribute(SSOAgentConstants.CONFIG_BEAN_NAME, config); - - } catch (IOException | SSOAgentException e) { - logger.log(Level.SEVERE, e.getMessage(), e); - } - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - - } - -} diff --git a/pom.xml b/pom.xml index 78bbba4..4ca7918 100644 --- a/pom.xml +++ b/pom.xml @@ -123,16 +123,6 @@ bcprov-jdk15on 1.62 - - org.openid4java - openid4java - ${openid4java.version} - - - org.apache.oltu.oauth2 - org.apache.oltu.oauth2.client - ${org.apache.oltu.oauth2.client.version} - org.wso2.orbit.org.apache.oltu.oauth2 oltu @@ -178,11 +168,6 @@ org.wso2.carbon.identity.saml.common.util ${saml.common.util.version} - - org.wso2.carbon.identity.agent.sso.java - org.wso2.carbon.identity.sso.agent.saml - ${project.version} - org.wso2.carbon.identity.agent.sso.java org.wso2.carbon.identity.sso.tomcat.server @@ -352,13 +337,8 @@ - components/org.wso2.carbon.identity.sso.agent components/org.wso2.carbon.identity.sso.agent.saml features/org.wso2.carbon.identity.sso.agent.server.feature - components/org.wso2.carbon.identity.sso.encryptor - components/org.wso2.carbon.identity.sso.tomcat.server - resources/SampleApp - resources/SampleApp-boilerplate diff --git a/resources/SampleApp-boilerplate/pom.xml b/resources/SampleApp-boilerplate/pom.xml deleted file mode 100644 index dbc4485..0000000 --- a/resources/SampleApp-boilerplate/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - identity-agent-sso - org.wso2.carbon.identity.agent.sso.java - 5.5.9-SNAPSHOT - ../../pom.xml - - 4.0.0 - - SampleApp-boilerplate - war - - - SampleApp-boilerplate - - - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - diff --git a/resources/SampleApp-boilerplate/src/main/webapp/WEB-INF/web.xml b/resources/SampleApp-boilerplate/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 69b55b5..0000000 --- a/resources/SampleApp-boilerplate/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - COOKIE - diff --git a/resources/SampleApp-boilerplate/src/main/webapp/home.jsp b/resources/SampleApp-boilerplate/src/main/webapp/home.jsp deleted file mode 100644 index 1251577..0000000 --- a/resources/SampleApp-boilerplate/src/main/webapp/home.jsp +++ /dev/null @@ -1,70 +0,0 @@ -<%-- - ~ Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - ~ - ~ WSO2 Inc. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%-- - Created by IntelliJ IDEA. - User: chamaths - Date: 7/27/20 - Time: 21:26 - To change this template use File | Settings | File Templates. ---%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - - Home - - - - -
-
-
-

Home Page!

-
- -
- Logout -
-
-
- - diff --git a/resources/SampleApp-boilerplate/src/main/webapp/index.html b/resources/SampleApp-boilerplate/src/main/webapp/index.html deleted file mode 100644 index ab4080c..0000000 --- a/resources/SampleApp-boilerplate/src/main/webapp/index.html +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - Sample App - - - -
-
-

- Log In Page! -

-
- -
- -
-
-
-
- - diff --git a/resources/SampleApp/pom.xml b/resources/SampleApp/pom.xml deleted file mode 100644 index b90d29c..0000000 --- a/resources/SampleApp/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - identity-agent-sso - org.wso2.carbon.identity.agent.sso.java - 5.5.9-SNAPSHOT - ../../pom.xml - - 4.0.0 - - SampleApp - war - - - SampleApp - src/main - - - - org.apache.maven.plugins - maven-war-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - - UTF-8 - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-release-plugin - - clean install - true - - - - org.apache.maven.plugins - maven-deploy-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - - - false - maven-clean-plugin - 2.1 - - - - - - - org.wso2.carbon.identity.agent.sso.java - org.wso2.carbon.identity.sso.tomcat.server - ${identity.sso.agent.package.export.version} - - - diff --git a/resources/SampleApp/src/main/resources/sampleApp.properties b/resources/SampleApp/src/main/resources/sampleApp.properties deleted file mode 100644 index 3fe93b9..0000000 --- a/resources/SampleApp/src/main/resources/sampleApp.properties +++ /dev/null @@ -1,76 +0,0 @@ -# -# Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -EnableSAML2SSOLogin=true - -#Url to do send SAML2 SSO AuthnRequest -SAML2SSOURL=samlsso - -#URIs to skip SSOAgentFilter; comma separated values -SkipURIs= - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.SPEntityId=SampleApp - -IndexPage=/SampleApp/index.html - -#The URL of the SAML 2.0 Assertion Consumer -SAML2.AssertionConsumerURL=http://localhost:8080/SampleApp/home.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.IdPEntityId=localhost - -#The URL of the SAML 2.0 Identity Provider -SAML2.IdPURL=https://localhost:9443/samlsso - -#Identifier given for the Service Provider for SAML 2.0 attributes -#exchange -#SAML2.AttributeConsumingServiceIndex=1701087467 - -#Specify if SingleLogout is enabled/disabled -SAML2.EnableSLO=true - -#This is the URL that is used for SLO -SAML2.SLOURL=logout - -#Specify if SAMLResponse element is signed -SAML2.EnableResponseSigning=true - -#Specify if SAMLAssertion element is signed -SAML2.EnableAssertionSigning=true - -#Specify if SAMLAssertion element is encrypted -SAML2.EnableAssertionEncryption=false - -#Specify if AuthnRequests and LogoutRequests should be signed -SAML2.EnableRequestSigning=true - -#Specify if SAML request is a passive -SAML2.IsPassiveAuthn=false - -#Password of the KeyStore for SAML and OpenID -KeyStorePassword=wso2carbon - -#Alias of the IdP's public certificate -IdPPublicCertAlias=wso2carbon - -#Alias of the SP's private key -PrivateKeyAlias=wso2carbon - -#Private key password to retrieve the private key used to sign -#AuthnRequest and LogoutRequest messages -PrivateKeyPassword=wso2carbon diff --git a/resources/SampleApp/src/main/resources/wso2carbon.jks b/resources/SampleApp/src/main/resources/wso2carbon.jks deleted file mode 100644 index c877578..0000000 Binary files a/resources/SampleApp/src/main/resources/wso2carbon.jks and /dev/null differ diff --git a/resources/SampleApp/src/main/webapp/WEB-INF/web.xml b/resources/SampleApp/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 638464e..0000000 --- a/resources/SampleApp/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - SampleApp - - - SAML2SSOAgentFilter - org.wso2.carbon.identity.sso.tomcat.server.SAML2SSOAgentFilter - - - SAML2SSOAgentFilter - *.jsp - - - SAML2SSOAgentFilter - *.html - - - SAML2SSOAgentFilter - /samlsso - - - SAML2SSOAgentFilter - /logout - - - - org.wso2.carbon.identity.sso.tomcat.server.SSOAgentContextEventListener - - - property-file - sampleApp.properties - - - certificate-file - wso2carbon.jks - - diff --git a/resources/SampleApp/src/main/webapp/home.jsp b/resources/SampleApp/src/main/webapp/home.jsp deleted file mode 100644 index d42ef15..0000000 --- a/resources/SampleApp/src/main/webapp/home.jsp +++ /dev/null @@ -1,99 +0,0 @@ -<%-- - ~ Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - ~ - ~ WSO2 Inc. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - - -<%@ page import="org.wso2.carbon.identity.sso.agent.saml.util.SSOAgentConstants" %> -<%@ page import="org.wso2.carbon.identity.sso.agent.saml.bean.LoggedInSessionBean" %> -<%@ page import="java.util.Map" %> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - - Home - - -<% - LoggedInSessionBean sessionBean = (LoggedInSessionBean) session.getAttribute(SSOAgentConstants.SESSION_BEAN_NAME); - String subjectId = sessionBean.getSAML2SSO().getSubjectId(); - Map saml2SSOAttributes = sessionBean.getSAML2SSO().getSubjectAttributes(); -%> - -
-
-
-

Home Page!

-
-
- <% - if (subjectId != null) { - %> -

You are logged in as <%=subjectId%> -

- <% - } - %> -
-
- - <% - if (saml2SSOAttributes != null) { - for (Map.Entry entry : saml2SSOAttributes.entrySet()) { - %> - - - - - <% - } - } - %> -
<%=entry.getKey()%> - <%=entry.getValue()%> -
-
-
- Logout -
-
-
- - diff --git a/resources/SampleApp/src/main/webapp/index.html b/resources/SampleApp/src/main/webapp/index.html deleted file mode 100644 index 3743269..0000000 --- a/resources/SampleApp/src/main/webapp/index.html +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - Sample App - - - -
-
-

- Log In Page! -

-
-
- -
-
-
-
- -