Search in sources :

Example 1 with Saml2Assertion

use of com.tremolosecurity.saml.Saml2Assertion in project OpenUnison by TremoloSecurity.

the class SamlTransaction method postResponse.

private void postResponse(final SamlTransaction transaction, HttpServletRequest request, HttpServletResponse response, AuthInfo authInfo, UrlHolder holder) throws MalformedURLException, ServletException, UnsupportedEncodingException, IOException {
    User mapped = null;
    try {
        if (authInfo.getAttribs().get(transaction.nameIDAttr) == null) {
            StringBuffer b = new StringBuffer();
            b.append("No attribute mapping for '").append(transaction.nameIDAttr).append("'");
            throw new ServletException(b.toString());
        }
        User orig = new User(authInfo.getAttribs().get(transaction.nameIDAttr).getValues().get(0));
        orig.getAttribs().putAll(authInfo.getAttribs());
        mapped = this.mapper.mapUser(orig);
    } catch (Exception e) {
        throw new ServletException("Could not map user", e);
    }
    String subject = authInfo.getAttribs().get(transaction.nameIDAttr).getValues().get(0);
    Saml2Trust trust = trusts.get(transaction.issuer);
    if (transaction.authnCtxName == null) {
        transaction.authnCtxName = trust.params.get("defaultAuthCtx").getValues().get(0);
    }
    PrivateKey pk = holder.getConfig().getPrivateKey(this.idpSigKeyName);
    java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.idpSigKeyName);
    java.security.cert.X509Certificate spEncCert = holder.getConfig().getCertificate(trust.spEncCert);
    StringBuffer issuer = new StringBuffer();
    URL url = new URL(request.getRequestURL().toString());
    if (request.isSecure()) {
        issuer.append("https://");
    } else {
        issuer.append("http://");
    }
    issuer.append(url.getHost());
    if (url.getPort() != -1) {
        issuer.append(':').append(url.getPort());
    }
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    // issuer.append(holder.getUrl().getUri());
    issuer.append(cfg.getAuthIdPPath()).append(this.idpName);
    Saml2Assertion resp = new Saml2Assertion(subject, pk, cert, spEncCert, issuer.toString(), transaction.postToURL, transaction.issuer, trust.signAssertion, trust.signResponse, trust.encAssertion, transaction.nameIDFormat, transaction.authnCtxName);
    for (String attrName : mapped.getAttribs().keySet()) {
        resp.getAttribs().add(mapped.getAttribs().get(attrName));
    }
    // resp.getAttribs().add(new Attribute("groups","admin"));
    String respXML = "";
    try {
        respXML = resp.generateSaml2Response();
    } catch (Exception e) {
        throw new ServletException("Could not generate SAMLResponse", e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug(respXML);
    }
    String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));
    request.setAttribute("postdata", base64);
    request.setAttribute("postaction", transaction.postToURL);
    if (transaction.relayState != null) {
        request.setAttribute("relaystate", transaction.relayState);
    } else {
        request.setAttribute("relaystate", "");
    }
    ST st = new ST(this.saml2PostTemplate, '$', '$');
    st.add("relaystate", (String) request.getAttribute("relaystate"));
    st.add("postdata", base64);
    st.add("postaction", transaction.postToURL);
    response.setContentType("text/html");
    response.getWriter().write(st.render());
}
Also used : ST(org.stringtemplate.v4.ST) User(com.tremolosecurity.provisioning.core.User) PrivateKey(java.security.PrivateKey) ServletException(javax.servlet.ServletException) SignatureException(java.security.SignatureException) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAXException(org.xml.sax.SAXException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InitializationException(org.opensaml.core.config.InitializationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) URL(java.net.URL) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ServletException(javax.servlet.ServletException) Saml2Assertion(com.tremolosecurity.saml.Saml2Assertion)

Example 2 with Saml2Assertion

use of com.tremolosecurity.saml.Saml2Assertion in project OpenUnison by TremoloSecurity.

the class PreAuthFilter method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    List<Cookie> cookies = null;
    if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
        if (uid == null || !uid.equals(userData.getUserDN())) {
            session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
            HashMap<String, String> uriParams = new HashMap<String, String>();
            uriParams.put("fullURI", this.uri);
            UrlHolder remHolder = cfg.findURL(this.url);
            org.apache.http.client.methods.HttpRequestBase method = null;
            if (this.postSAML) {
                PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
                java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);
                Saml2Assertion assertion = new Saml2Assertion(userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null, this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion, this.signResponse, false, this.nameIDType, this.authnCtxClassRef);
                String respXML = "";
                try {
                    respXML = assertion.generateSaml2Response();
                } catch (Exception e) {
                    throw new ServletException("Could not generate SAMLResponse", e);
                }
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));
                formparams.add(new BasicNameValuePair("SAMLResponse", base64));
                if (this.relayState != null && !this.relayState.isEmpty()) {
                    formparams.add(new BasicNameValuePair("RelayState", this.relayState));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpPost post = new HttpPost(this.assertionConsumerURL);
                post.setEntity(entity);
                method = post;
            } else {
                HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
                method = get;
            }
            LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0), this.loginAttribute, method, lastMileKeyAlias, true);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(cfg.getHttpClientSocketRegistry());
            try {
                CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();
                HttpResponse resp = httpclient.execute(method);
                if (resp.getStatusLine().getStatusCode() == 500) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
                    StringBuffer error = new StringBuffer();
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        error.append(line).append('\n');
                    }
                    logger.warn("Pre-Auth Failed : " + error);
                }
                org.apache.http.Header[] headers = resp.getAllHeaders();
                StringBuffer stmp = new StringBuffer();
                cookies = new ArrayList<Cookie>();
                for (org.apache.http.Header header : headers) {
                    if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) {
                        // System.out.println(header.getValue());
                        String cookieVal = header.getValue();
                        /*if (cookieVal.endsWith("HttpOnly")) {
								cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
							}
							
							//System.out.println(cookieVal);*/
                        List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal);
                        for (HttpCookie cookie : cookiesx) {
                            String cookieFinalName = cookie.getName();
                            if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                                stmp.setLength(0);
                                stmp.append("JSESSIONID").append('-').append(holder.getApp().getName().replaceAll(" ", "|"));
                                cookieFinalName = stmp.toString();
                            }
                            // logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");
                            Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                            respcookie.setComment(cookie.getComment());
                            if (cookie.getDomain() != null) {
                            // respcookie.setDomain(cookie.getDomain());
                            }
                            respcookie.setMaxAge((int) cookie.getMaxAge());
                            respcookie.setPath(cookie.getPath());
                            respcookie.setSecure(cookie.getSecure());
                            respcookie.setVersion(cookie.getVersion());
                            cookies.add(respcookie);
                            if (request.getCookieNames().contains(respcookie.getName())) {
                                request.removeCookie(cookieFinalName);
                            }
                            request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
                        }
                    }
                }
            } finally {
                bhcm.shutdown();
            }
        }
    }
    chain.nextFilter(request, response, chain);
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            response.addCookie(cookie);
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) InputStreamReader(java.io.InputStreamReader) HttpSession(javax.servlet.http.HttpSession) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ProtocolException(org.apache.http.ProtocolException) ServletException(javax.servlet.ServletException) MalformedCookieException(org.apache.http.cookie.MalformedCookieException) Saml2Assertion(com.tremolosecurity.saml.Saml2Assertion) BufferedReader(java.io.BufferedReader) HttpCookie(java.net.HttpCookie)

Example 3 with Saml2Assertion

use of com.tremolosecurity.saml.Saml2Assertion in project OpenUnison by TremoloSecurity.

the class SamlTransaction method postErrorResponse.

private void postErrorResponse(final SamlTransaction transaction, HttpServletRequest request, HttpServletResponse response, AuthInfo authInfo, UrlHolder holder) throws MalformedURLException, ServletException, UnsupportedEncodingException, IOException {
    Saml2Trust trust = trusts.get(transaction.issuer);
    PrivateKey pk = holder.getConfig().getPrivateKey(this.idpSigKeyName);
    java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.idpSigKeyName);
    java.security.cert.X509Certificate spEncCert = holder.getConfig().getCertificate(trust.spEncCert);
    StringBuffer issuer = new StringBuffer();
    URL url = new URL(request.getRequestURL().toString());
    if (request.isSecure()) {
        issuer.append("https://");
    } else {
        issuer.append("http://");
    }
    issuer.append(url.getHost());
    if (url.getPort() != -1) {
        issuer.append(':').append(url.getPort());
    }
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    // issuer.append(holder.getUrl().getUri());
    issuer.append(cfg.getAuthIdPPath()).append(this.idpName);
    Saml2Assertion resp = new Saml2Assertion(null, pk, cert, spEncCert, issuer.toString(), transaction.postToURL, transaction.issuer, trust.signAssertion, trust.signResponse, trust.encAssertion, transaction.nameIDFormat, transaction.authnCtxName);
    // resp.getAttribs().add(new Attribute("groups","admin"));
    String respXML = "";
    try {
        respXML = resp.generateSaml2Response();
    } catch (Exception e) {
        throw new ServletException("Could not generate SAMLResponse", e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug(respXML);
    }
    String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));
    request.setAttribute("postdata", base64);
    request.setAttribute("postaction", transaction.postToURL);
    if (transaction.relayState != null) {
        request.setAttribute("relaystate", transaction.relayState);
    } else {
        request.setAttribute("relaystate", "");
    }
    ST st = new ST(this.saml2PostTemplate, '$', '$');
    st.add("relaystate", (String) request.getAttribute("relaystate"));
    st.add("postdata", base64);
    st.add("postaction", transaction.postToURL);
    response.setContentType("text/html");
    response.getWriter().write(st.render());
}
Also used : ST(org.stringtemplate.v4.ST) PrivateKey(java.security.PrivateKey) URL(java.net.URL) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ServletException(javax.servlet.ServletException) SignatureException(java.security.SignatureException) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAXException(org.xml.sax.SAXException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InitializationException(org.opensaml.core.config.InitializationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ServletException(javax.servlet.ServletException) Saml2Assertion(com.tremolosecurity.saml.Saml2Assertion)

Aggregations

ConfigManager (com.tremolosecurity.config.util.ConfigManager)3 Saml2Assertion (com.tremolosecurity.saml.Saml2Assertion)3 PrivateKey (java.security.PrivateKey)3 ServletException (javax.servlet.ServletException)3 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SignatureException (java.security.SignatureException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 InitializationException (org.opensaml.core.config.InitializationException)2 UnmarshallingException (org.opensaml.core.xml.io.UnmarshallingException)2 ST (org.stringtemplate.v4.ST)2 SAXException (org.xml.sax.SAXException)2 UrlHolder (com.tremolosecurity.config.util.UrlHolder)1 User (com.tremolosecurity.provisioning.core.User)1 AuthController (com.tremolosecurity.proxy.auth.AuthController)1 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)1