Search in sources :

Example 1 with MyVDConnection

use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.

the class AzSys method isUserInGroup.

private boolean isUserInGroup(AuthInfo authData, ConfigManager cfgMgr, AzRule rule, String localConstraint) {
    boolean OK = false;
    MyVDConnection con = cfgMgr.getMyVD();
    ArrayList<String> attribs = new ArrayList<String>();
    attribs.add("1.1");
    try {
        LDAPSearchResults res = con.search(localConstraint, 0, equal(cfgMgr.getCfg().getGroupMemberAttribute(), authData.getUserDN()).toString(), attribs);
        if (res.hasMore()) {
            OK = true;
            res.next();
        }
    } catch (LDAPException e) {
        logger.error("Could not parse", e);
    }
    return OK;
}
Also used : LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException) ArrayList(java.util.ArrayList) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection)

Example 2 with MyVDConnection

use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.

the class GithubAuthMech method doGet.

public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    MyVDConnection myvd = cfg.getMyVD();
    String bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String clientid = authParams.get("clientid").getValues().get(0);
    String secret = authParams.get("secretid").getValues().get(0);
    String idpURL = authParams.get("idpURL") != null ? authParams.get("idpURL").getValues().get(0) : "https://github.com/login/oauth/authorize";
    String scope = authParams.get("scope").getValues().get(0);
    boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0));
    String noMatchOU = authParams.get("noMatchOU").getValues().get(0);
    String uidAttr = authParams.get("uidAttr").getValues().get(0);
    String lookupFilter = authParams.get("lookupFilter").getValues().get(0);
    String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);
    // authParams.get("forceAuthentication") != null ? authParams.get("forceAuthentication").getValues().get(0).equalsIgnoreCase("true") : false;
    boolean forceAuth = true;
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    StringBuffer b = new StringBuffer();
    URL reqURL = new URL(request.getRequestURL().toString());
    b.append(reqURL.getProtocol()).append("://").append(reqURL.getHost());
    if (reqURL.getPort() != -1) {
        b.append(":").append(reqURL.getPort());
    }
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    String authMechName = amt.getName();
    b.append(holder.getConfig().getContextPath()).append(cfg.getAuthMechs().get(authMechName).getUri());
    String loadTokenURL = authParams.get("loadTokenURL") != null ? authParams.get("loadTokenURL").getValues().get(0) : "https://github.com/login/oauth/access_token";
    if (request.getParameter("state") == null) {
        // initialize openidconnect
        String state = new BigInteger(130, new SecureRandom()).toString(32);
        request.getSession().setAttribute("UNISON_OPENIDCONNECT_STATE", state);
        StringBuffer redirToSend = new StringBuffer();
        redirToSend.append(idpURL).append("?client_id=").append(URLEncoder.encode(clientid, "UTF-8")).append("&scope=").append(URLEncoder.encode(scope, "UTF-8")).append("&state=").append(URLEncoder.encode("security_token=", "UTF-8")).append(URLEncoder.encode(state, "UTF-8"));
        response.sendRedirect(redirToSend.toString());
    } else {
        String stateFromURL = request.getParameter("state");
        stateFromURL = URLDecoder.decode(stateFromURL, "UTF-8");
        stateFromURL = stateFromURL.substring(stateFromURL.indexOf('=') + 1);
        String stateFromSession = (String) request.getSession().getAttribute("UNISON_OPENIDCONNECT_STATE");
        if (!stateFromSession.equalsIgnoreCase(stateFromURL)) {
            throw new ServletException("Invalid State");
        }
        HttpUriRequest post = null;
        try {
            post = RequestBuilder.post().setUri(new java.net.URI(loadTokenURL)).addParameter("code", request.getParameter("code")).addParameter("client_id", clientid).addParameter("client_secret", secret).build();
        } catch (URISyntaxException e) {
            throw new ServletException("Could not create post request");
        }
        BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();
        try {
            CloseableHttpResponse httpResp = http.execute(post);
            BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
            StringBuffer token = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                token.append(line);
            }
            List<NameValuePair> params = URLEncodedUtils.parse(token.toString(), Charset.defaultCharset());
            String accessToken = null;
            for (NameValuePair nvp : params) {
                if (nvp.getName().equals("access_token")) {
                    accessToken = nvp.getValue();
                }
            }
            if (accessToken == null) {
                throw new ServletException("Could not get authorization toekn : " + token);
            }
            httpResp.close();
            Gson gson = new Gson();
            HttpGet get = new HttpGet("https://api.github.com/user");
            get.addHeader("Authorization", new StringBuilder().append("Bearer ").append(accessToken).toString());
            // Store the bearer token for use by Unison
            request.getSession().setAttribute(bearerTokenName, accessToken);
            httpResp = http.execute(get);
            in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
            token.setLength(0);
            line = null;
            while ((line = in.readLine()) != null) {
                token.append(line);
            }
            httpResp.close();
            Map jwtNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());
            ;
            if (jwtNVP == null) {
                as.setSuccess(false);
            } else {
                get = new HttpGet("https://api.github.com/user/emails");
                get.addHeader("Authorization", new StringBuilder().append("Bearer ").append(accessToken).toString());
                httpResp = http.execute(get);
                in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
                token.setLength(0);
                line = null;
                while ((line = in.readLine()) != null) {
                    token.append(line);
                }
                httpResp.close();
                JSONParser parser = new JSONParser();
                org.json.simple.JSONArray emails = (org.json.simple.JSONArray) parser.parse(token.toString());
                for (Object o : emails) {
                    org.json.simple.JSONObject emailObj = (org.json.simple.JSONObject) o;
                    boolean isPrimary = (Boolean) emailObj.get("primary");
                    if (isPrimary) {
                        jwtNVP.put("mail", emailObj.get("email"));
                    }
                }
                if (!linkToDirectory) {
                    loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);
                    as.setSuccess(true);
                } else {
                    lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, jwtNVP, defaultObjectClass);
                }
                get = new HttpGet("https://api.github.com/user/orgs");
                get.addHeader("Authorization", new StringBuilder().append("Bearer ").append(accessToken).toString());
                httpResp = http.execute(get);
                in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
                token.setLength(0);
                line = null;
                while ((line = in.readLine()) != null) {
                    token.append(line);
                }
                httpResp.close();
                parser = new JSONParser();
                org.json.simple.JSONArray orgs = (org.json.simple.JSONArray) parser.parse(token.toString());
                Attribute userOrgs = new Attribute("githubOrgs");
                Attribute userTeams = new Attribute("githubTeams");
                for (Object o : orgs) {
                    org.json.simple.JSONObject org = (org.json.simple.JSONObject) o;
                    String orgName = (String) org.get("login");
                    userOrgs.getValues().add(orgName);
                    HttpUriRequest graphql = RequestBuilder.post().addHeader(new BasicHeader("Authorization", "Bearer " + accessToken)).setUri("https://api.github.com/graphql").setEntity(new StringEntity("{\"query\":\"{organization(login: \\\"" + orgName + "\\\") { teams(first: 100, userLogins: [\\\"" + jwtNVP.get("login") + "\\\"]) { totalCount edges {node {name description}}}}}\"}")).build();
                    httpResp = http.execute(graphql);
                    in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
                    token.setLength(0);
                    line = null;
                    while ((line = in.readLine()) != null) {
                        token.append(line);
                    }
                    httpResp.close();
                    org.json.simple.JSONObject root = (org.json.simple.JSONObject) parser.parse(token.toString());
                    org.json.simple.JSONObject data = (org.json.simple.JSONObject) root.get("data");
                    org.json.simple.JSONObject organization = (org.json.simple.JSONObject) data.get("organization");
                    org.json.simple.JSONObject teams = (org.json.simple.JSONObject) organization.get("teams");
                    org.json.simple.JSONArray edges = (org.json.simple.JSONArray) teams.get("edges");
                    for (Object oi : edges) {
                        org.json.simple.JSONObject edge = (org.json.simple.JSONObject) oi;
                        org.json.simple.JSONObject node = (org.json.simple.JSONObject) edge.get("node");
                        userTeams.getValues().add(orgName + "/" + node.get("name"));
                    }
                }
                ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo().getAttribs().put("githubOrgs", userOrgs);
                ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo().getAttribs().put("githubTeams", userTeams);
                String redirectToURL = request.getParameter("target");
                if (redirectToURL != null && !redirectToURL.isEmpty()) {
                    reqHolder.setURL(redirectToURL);
                }
            }
            holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        } catch (ParseException e) {
            throw new ServletException("Could not parse orgs", e);
        } finally {
            if (bhcm != null) {
                bhcm.close();
            }
            if (http != null) {
                http.close();
            }
        }
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) Gson(com.google.gson.Gson) URISyntaxException(java.net.URISyntaxException) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) URL(java.net.URL) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) HttpSession(javax.servlet.http.HttpSession) JSONArray(org.jose4j.json.internal.json_simple.JSONArray) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) SecureRandom(java.security.SecureRandom) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) BufferedReader(java.io.BufferedReader) BigInteger(java.math.BigInteger) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) HashMap(java.util.HashMap) BasicHeader(org.apache.http.message.BasicHeader)

Example 3 with MyVDConnection

use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.

the class OpenIDConnectAuthMech method doGet.

public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    MyVDConnection myvd = cfg.getMyVD();
    String idpURL;
    String loadTokenURL;
    if (authParams.get("issuer") != null) {
        StringBuffer b = new StringBuffer();
        String issuer = authParams.get("issuer").getValues().get(0);
        b.append(issuer);
        if (issuer.charAt(issuer.length() - 1) != '/') {
            b.append('/');
        }
        b.append(".well-known/openid-configuration");
        String discoveryUrl = b.toString();
        OidcIdpUrls idp = this.idpUrls.get(discoveryUrl);
        if (idp == null) {
            idp = new OidcIdpUrls();
            this.idpUrls.put(discoveryUrl, idp);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
            RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
            CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();
            try {
                HttpGet get = new HttpGet(b.toString());
                CloseableHttpResponse resp = http.execute(get);
                if (resp.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(resp.getEntity());
                    resp.close();
                    JSONParser parser = new JSONParser();
                    org.json.simple.JSONObject root = (org.json.simple.JSONObject) parser.parse(json);
                    idp.setIdpUrl((String) root.get("authorization_endpoint"));
                    idp.setTokenUrl((String) root.get("token_endpoint"));
                    idp.setUserInfoUrl((String) root.get("userinfo_endpoint"));
                } else {
                    idp.setIdpUrl(authParams.get("idpURL").getValues().get(0));
                    idp.setTokenUrl(loadTokenURL = authParams.get("loadTokenURL").getValues().get(0));
                }
            } catch (ParseException e) {
                throw new ServletException("Could not parse discovery document", e);
            } finally {
                try {
                    http.close();
                } catch (Throwable e) {
                }
                bhcm.close();
            }
        }
        request.setAttribute(OIDC_IDP, idp);
        idpURL = idp.getIdpUrl();
        loadTokenURL = idp.getTokenUrl();
    } else {
        idpURL = authParams.get("idpURL").getValues().get(0);
        loadTokenURL = authParams.get("loadTokenURL").getValues().get(0);
    }
    String bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String clientid = authParams.get("clientid").getValues().get(0);
    String secret = authParams.get("secretid").getValues().get(0);
    String responseType = authParams.get("responseType").getValues().get(0);
    String scope = authParams.get("scope").getValues().get(0);
    boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0));
    String noMatchOU = authParams.get("noMatchOU").getValues().get(0);
    String uidAttr = authParams.get("uidAttr").getValues().get(0);
    String lookupFilter = authParams.get("lookupFilter").getValues().get(0);
    String userLookupClassName = authParams.get("userLookupClassName").getValues().get(0);
    String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);
    boolean forceAuth = authParams.get("forceAuthentication") != null ? authParams.get("forceAuthentication").getValues().get(0).equalsIgnoreCase("true") : true;
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    StringBuffer b = new StringBuffer();
    URL reqURL = new URL(ProxyTools.getInstance().getHttpsUrl(request.getRequestURL().toString(), request));
    b.append(reqURL.getProtocol()).append("://").append(reqURL.getHost());
    if (reqURL.getPort() != -1) {
        b.append(":").append(reqURL.getPort());
    }
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    String authMechName = amt.getName();
    b.append(holder.getConfig().getContextPath()).append(cfg.getAuthMechs().get(authMechName).getUri());
    String hd = authParams.get("hd").getValues().get(0);
    if (request.getParameter("state") == null) {
        // initialize openidconnect
        String state = new BigInteger(130, new SecureRandom()).toString(32);
        request.getSession().setAttribute("UNISON_OPENIDCONNECT_STATE", state);
        StringBuffer redirToSend = new StringBuffer();
        redirToSend.append(idpURL).append("?client_id=").append(URLEncoder.encode(clientid, "UTF-8")).append("&response_type=").append(URLEncoder.encode(responseType, "UTF-8")).append("&scope=").append(URLEncoder.encode(scope, "UTF-8")).append("&redirect_uri=").append(URLEncoder.encode(b.toString(), "UTF-8")).append("&state=").append(URLEncoder.encode("security_token=", "UTF-8")).append(URLEncoder.encode(state, "UTF-8"));
        if (forceAuth) {
            redirToSend.append("&max_age=0");
        }
        if (hd != null && !hd.isEmpty()) {
            redirToSend.append("&hd=").append(hd);
        }
        response.sendRedirect(redirToSend.toString());
    } else {
        String stateFromURL = request.getParameter("state");
        stateFromURL = URLDecoder.decode(stateFromURL, "UTF-8");
        stateFromURL = stateFromURL.substring(stateFromURL.indexOf('=') + 1);
        String stateFromSession = (String) request.getSession().getAttribute("UNISON_OPENIDCONNECT_STATE");
        if (!stateFromSession.equalsIgnoreCase(stateFromURL)) {
            throw new ServletException("Invalid State");
        }
        HttpUriRequest post = null;
        try {
            post = RequestBuilder.post().setUri(new java.net.URI(loadTokenURL)).addParameter("code", request.getParameter("code")).addParameter("client_id", clientid).addParameter("client_secret", secret).addParameter("redirect_uri", b.toString()).addParameter("grant_type", "authorization_code").build();
        } catch (URISyntaxException e) {
            throw new ServletException("Could not create post request");
        }
        BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();
        CloseableHttpResponse httpResp = http.execute(post);
        if (httpResp.getStatusLine().getStatusCode() != 200) {
            logger.error("Could not retrieve token : " + httpResp.getStatusLine().getStatusCode() + " / " + httpResp.getStatusLine().getReasonPhrase());
            as.setSuccess(false);
            holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
        StringBuffer token = new StringBuffer();
        String line = null;
        while ((line = in.readLine()) != null) {
            token.append(line);
        }
        httpResp.close();
        bhcm.close();
        Gson gson = new Gson();
        Map tokenNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());
        String accessToken;
        // Store the bearer token for use by Unison
        request.getSession().setAttribute(bearerTokenName, tokenNVP.get("access_token"));
        Map jwtNVP = null;
        LoadUserData loadUser = null;
        try {
            loadUser = (LoadUserData) Class.forName(userLookupClassName).newInstance();
            jwtNVP = loadUser.loadUserAttributesFromIdP(request, response, cfg, authParams, tokenNVP);
        } catch (Exception e) {
            throw new ServletException("Could not load user data", e);
        }
        if (hd != null && !hd.isEmpty()) {
            String hdFromIdToken = (String) jwtNVP.get("hd");
            if (hdFromIdToken != null && !hdFromIdToken.isEmpty()) {
                if (!hdFromIdToken.equalsIgnoreCase(hd)) {
                    as.setSuccess(false);
                    String redirectToURL = request.getParameter("target");
                    if (redirectToURL != null && !redirectToURL.isEmpty()) {
                        reqHolder.setURL(redirectToURL);
                    }
                }
            } else {
                as.setSuccess(false);
                String redirectToURL = request.getParameter("target");
                if (redirectToURL != null && !redirectToURL.isEmpty()) {
                    reqHolder.setURL(redirectToURL);
                }
            }
        }
        if (jwtNVP == null) {
            as.setSuccess(false);
        } else {
            if (!linkToDirectory) {
                loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);
                as.setSuccess(true);
            } else {
                lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, jwtNVP, defaultObjectClass);
            }
            String redirectToURL = request.getParameter("target");
            if (redirectToURL != null && !redirectToURL.isEmpty()) {
                reqHolder.setURL(redirectToURL);
            }
        }
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) Gson(com.google.gson.Gson) URISyntaxException(java.net.URISyntaxException) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) URL(java.net.URL) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) UrlHolder(com.tremolosecurity.config.util.UrlHolder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) LoadUserData(com.tremolosecurity.unison.proxy.auth.openidconnect.sdk.LoadUserData) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStreamReader(java.io.InputStreamReader) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) SecureRandom(java.security.SecureRandom) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) LDAPException(com.novell.ldap.LDAPException) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) BufferedReader(java.io.BufferedReader) BigInteger(java.math.BigInteger) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with MyVDConnection

use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.

the class CrlChecker method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    // SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) request).getSession();
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    Attribute issuersParam = authParams.get("issuer");
    HashSet<X500Principal> issuers = new HashSet<X500Principal>();
    for (String dn : issuersParam.getValues()) {
        issuers.add(new X500Principal(dn));
    }
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    if (certs == null) {
        if (amt.getRequired().equals("required")) {
            as.setSuccess(false);
        }
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }
    X509Certificate cert = certs[0];
    DN dn = new DN(cert.getSubjectX500Principal().getName());
    Vector<RDN> rdns = dn.getRDNs();
    HashMap<String, String> subject = new HashMap<String, String>();
    for (RDN rdn : rdns) {
        subject.put(rdn.getType(), rdn.getValue());
    }
    // Load SANS
    try {
        if (cert.getSubjectAlternativeNames() != null) {
            java.util.Collection altNames = cert.getSubjectAlternativeNames();
            Iterator iter = altNames.iterator();
            while (iter.hasNext()) {
                java.util.List item = (java.util.List) iter.next();
                Integer type = (Integer) item.get(0);
                subject.put(SAN_NAMES[type.intValue()], item.get(1).toString());
            }
        }
    } catch (CertificateParsingException e1) {
        throw new ServletException("Could not parse certificate", e1);
    }
    for (CertificateExtractSubjectAttribute cesa : this.extracts) {
        cesa.addSubjects(subject, certs);
    }
    MyVDConnection myvd = cfgMgr.getMyVD();
    // HttpSession session = (HttpSession) req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest) req).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
    boolean OK = false;
    boolean certOK = true;
    int i = 0;
    for (X509Certificate certx : certs) {
        if (issuers.contains(certx.getIssuerX500Principal())) {
            OK = true;
        }
        if (certOK) {
            for (CRLManager crlM : this.crls) {
                X509Certificate issuer = null;
                if (i + 1 < certs.length) {
                    issuer = certs[i + 1];
                } else {
                    try {
                        Enumeration<String> enumer = cfgMgr.getKeyStore().aliases();
                        while (enumer.hasMoreElements()) {
                            String alias = enumer.nextElement();
                            X509Certificate lissuer = (X509Certificate) cfgMgr.getKeyStore().getCertificate(alias);
                            if (lissuer != null && lissuer.getSubjectX500Principal().equals(certs[i].getIssuerX500Principal())) {
                                try {
                                    certs[i].verify(lissuer.getPublicKey());
                                    issuer = lissuer;
                                } catch (Exception e) {
                                    logger.warn("Issuer with wrong public key", e);
                                }
                            }
                        }
                    } catch (KeyStoreException e) {
                        throw new ServletException("Could not process CRLs", e);
                    }
                }
                if (issuer != null) {
                    if (!crlM.isValid(certx, issuer)) {
                        certOK = false;
                        break;
                    }
                } else {
                    logger.warn("No issuer!  not performing CRL check");
                }
            }
        }
    }
    if (!OK || !certOK) {
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }
    String uidAttr = "uid";
    if (authParams.get("uidAttr") != null) {
        uidAttr = authParams.get("uidAttr").getValues().get(0);
    }
    boolean uidIsFilter = false;
    if (authParams.get("uidIsFilter") != null) {
        uidIsFilter = authParams.get("uidIsFilter").getValues().get(0).equalsIgnoreCase("true");
    }
    String filter = "";
    if (uidIsFilter) {
        StringBuffer b = new StringBuffer();
        int lastIndex = 0;
        int index = uidAttr.indexOf('$');
        while (index >= 0) {
            b.append(uidAttr.substring(lastIndex, index));
            lastIndex = uidAttr.indexOf('}', index) + 1;
            String reqName = uidAttr.substring(index + 2, lastIndex - 1);
            b.append(subject.get(reqName));
            index = uidAttr.indexOf('$', index + 1);
        }
        b.append(uidAttr.substring(lastIndex));
        filter = b.toString();
    } else {
        StringBuffer b = new StringBuffer();
        if (subject.get(uidAttr) == null) {
            filter = "(!(objectClass=*))";
        } else {
            filter = equal(uidAttr, subject.get(uidAttr)).toString();
        }
    }
    String rdnAttr = authParams.get("rdnAttribute").getValues().get(0);
    ArrayList<String> rdnAttrs = new ArrayList<String>();
    StringTokenizer toker = new StringTokenizer(rdnAttr, ",", false);
    while (toker.hasMoreTokens()) {
        rdnAttrs.add(toker.nextToken());
    }
    String defaultOC = authParams.get("defaultOC").getValues().get(0);
    String dnLabel = authParams.get("dnLabel").getValues().get(0);
    as.setSuccess(true);
    try {
        LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, filter, new ArrayList<String>());
        if (res.hasMore()) {
            createUserFromDir(session, act, res);
        } else {
            createUnlinkedUser(session, act, rdnAttrs, dnLabel, defaultOC, subject);
        }
    } catch (LDAPException e) {
        if (e.getResultCode() == 32) {
            createUnlinkedUser(session, act, rdnAttrs, dnLabel, defaultOC, subject);
        } else {
            throw new ServletException("Could not search for user", e);
        }
    }
    holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
/*try {
			for (String oid : cert.getCriticalExtensionOIDs()) {
				byte[] derEncoded = cert.getExtensionValue(oid);
				
				//System.out.println("critical : " + oid);
			}
			
			for (String oid : cert.getNonCriticalExtensionOIDs()) {
				byte[] derEncoded = cert.getExtensionValue(oid);
				//System.out.println("noncritical : " + oid);
				ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(derEncoded));
				
				DEREncodable obj = ain.readObject();
				do {
					DEROctetString deros = (DEROctetString) obj;
					//System.out.println(deros.toString());
					X509Extension extension = new X509Extension(false,deros);
					//System.out.println(extension.toString());
					
					obj = ain.readObject();
				} while (obj != null);
				
			}
			
			
		} catch (Exception e) {
			throw new ServletException("Error parsing certificate",e);
		}*/
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DN(com.novell.ldap.util.DN) RDN(com.novell.ldap.util.RDN) CRLManager(com.tremolosecurity.proxy.auth.ssl.CRLManager) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) RDN(com.novell.ldap.util.RDN) HashSet(java.util.HashSet) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection) HttpSession(javax.servlet.http.HttpSession) Collection(java.util.Collection) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) LDAPException(com.novell.ldap.LDAPException) ServletException(javax.servlet.ServletException) CertificateParsingException(java.security.cert.CertificateParsingException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) List(java.util.List) StringTokenizer(java.util.StringTokenizer) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException) X500Principal(javax.security.auth.x500.X500Principal)

Example 5 with MyVDConnection

use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.

the class FormLoginAuthMech method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp, AuthStep as) throws ServletException, IOException {
    String userDN = null;
    MyVDConnection myvd = cfgMgr.getMyVD();
    // HttpSession session = (HttpSession) req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest) req).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
    // SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) req).getSession();
    UrlHolder holder = (UrlHolder) req.getAttribute(ProxyConstants.AUTOIDM_CFG);
    if (holder == null) {
        throw new ServletException("Holder is null");
    }
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    String uidAttr = "uid";
    if (authParams.get("uidAttr") != null) {
        uidAttr = authParams.get("uidAttr").getValues().get(0);
    }
    boolean uidIsFilter = false;
    if (authParams.get("uidIsFilter") != null) {
        uidIsFilter = authParams.get("uidIsFilter").getValues().get(0).equalsIgnoreCase("true");
    }
    String filter = "";
    if (uidIsFilter) {
        StringBuffer b = new StringBuffer();
        int lastIndex = 0;
        int index = uidAttr.indexOf('$');
        while (index >= 0) {
            b.append(uidAttr.substring(lastIndex, index));
            lastIndex = uidAttr.indexOf('}', index) + 1;
            String reqName = uidAttr.substring(index + 2, lastIndex - 1);
            b.append(req.getParameter(reqName));
            index = uidAttr.indexOf('$', index + 1);
        }
        b.append(uidAttr.substring(lastIndex));
        filter = b.toString();
    } else {
        StringBuffer b = new StringBuffer();
        String userParam = req.getParameter("user");
        b.append('(').append(uidAttr).append('=').append(userParam).append(')');
        if (userParam == null) {
            filter = "(!(objectClass=*))";
        } else {
            filter = equal(uidAttr, userParam).toString();
        }
    }
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    String password = req.getParameter("pwd");
    if (password == null || password.trim().length() == 0) {
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
        return;
    }
    try {
        LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, filter, new ArrayList<String>());
        if (res.hasMore()) {
            LDAPEntry entry = res.next();
            userDN = entry.getDN();
            myvd.bind(entry.getDN(), req.getParameter("pwd"));
            Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator();
            AuthInfo authInfo = new AuthInfo(entry.getDN(), (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel());
            ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);
            while (it.hasNext()) {
                LDAPAttribute attrib = it.next();
                Attribute attr = new Attribute(attrib.getName());
                String[] vals = attrib.getStringValueArray();
                for (int i = 0; i < vals.length; i++) {
                    attr.getValues().add(vals[i]);
                }
                authInfo.getAttribs().put(attr.getName(), attr);
            }
            as.setSuccess(true);
        } else {
            req.setAttribute(ProxyConstants.AUTH_FAILED_USER_DN, userDN);
            as.setSuccess(false);
        }
    } catch (LDAPException e) {
        if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
            logger.error("Could not authenticate user", e);
        }
        req.setAttribute(ProxyConstants.AUTH_FAILED_USER_DN, userDN);
        as.setSuccess(false);
    }
    String redirectToURL = req.getParameter("target");
    if (redirectToURL != null && !redirectToURL.isEmpty()) {
        reqHolder.setURL(redirectToURL);
    }
    ProxyRequest pr = (ProxyRequest) req;
    pr.removeParameter("pwd");
    pr.removeParameter("user");
    holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
}
Also used : LDAPAttribute(com.novell.ldap.LDAPAttribute) HashMap(java.util.HashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) LDAPEntry(com.novell.ldap.LDAPEntry) ProxyRequest(com.tremolosecurity.proxy.ProxyRequest) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection) LDAPAttribute(com.novell.ldap.LDAPAttribute) TremoloHttpSession(com.tremolosecurity.proxy.TremoloHttpSession) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException)

Aggregations

MyVDConnection (com.tremolosecurity.proxy.myvd.MyVDConnection)13 LDAPAttribute (com.novell.ldap.LDAPAttribute)10 UrlHolder (com.tremolosecurity.config.util.UrlHolder)10 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)10 HashMap (java.util.HashMap)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 HttpSession (javax.servlet.http.HttpSession)10 LDAPException (com.novell.ldap.LDAPException)9 AuthMechType (com.tremolosecurity.config.xml.AuthMechType)9 Attribute (com.tremolosecurity.saml.Attribute)9 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)8 LDAPEntry (com.novell.ldap.LDAPEntry)6 ServletException (javax.servlet.ServletException)6 ArrayList (java.util.ArrayList)5 AuthController (com.tremolosecurity.proxy.auth.AuthController)4 RequestHolder (com.tremolosecurity.proxy.auth.RequestHolder)4 IOException (java.io.IOException)4 Gson (com.google.gson.Gson)3 TremoloHttpSession (com.tremolosecurity.proxy.TremoloHttpSession)3 ConfigManager (com.tremolosecurity.config.util.ConfigManager)2