Search in sources :

Example 71 with AuthController

use of com.tremolosecurity.proxy.auth.AuthController in project OpenUnison by TremoloSecurity.

the class GithubAuthMech method lookupUser.

public static void lookupUser(AuthStep as, HttpSession session, MyVDConnection myvd, String noMatchOU, String uidAttr, String lookupFilter, AuthChainType act, Map jwtNVP, String defaultObjectClass) {
    boolean uidIsFilter = !lookupFilter.isEmpty();
    String filter = "";
    if (uidIsFilter) {
        StringBuffer b = new StringBuffer();
        int lastIndex = 0;
        int index = lookupFilter.indexOf('$');
        while (index >= 0) {
            b.append(lookupFilter.substring(lastIndex, index));
            lastIndex = lookupFilter.indexOf('}', index) + 1;
            String reqName = lookupFilter.substring(index + 2, lastIndex - 1);
            b.append(jwtNVP.get(reqName).toString());
            index = lookupFilter.indexOf('$', index + 1);
        }
        b.append(lookupFilter.substring(lastIndex));
        filter = b.toString();
        if (logger.isDebugEnabled()) {
            logger.debug("Filter : '" + filter + "'");
        }
    } else {
        StringBuffer b = new StringBuffer();
        String userParam = (String) jwtNVP.get(uidAttr);
        b.append('(').append(uidAttr).append('=').append(userParam).append(')');
        if (userParam == null) {
            filter = "(!(objectClass=*))";
        } else {
            filter = equal(uidAttr, userParam).toString();
        }
    }
    try {
        String root = act.getRoot();
        if (root == null || root.trim().isEmpty()) {
            root = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot();
        }
        LDAPSearchResults res = myvd.search(root, 2, filter, new ArrayList<String>());
        if (res.hasMore()) {
            LDAPEntry entry = res.next();
            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);
            }
            for (Object o : jwtNVP.keySet()) {
                String s = (String) o;
                Object v = jwtNVP.get(s);
                Attribute attr = authInfo.getAttribs().get(s);
                if (attr == null) {
                    attr = new Attribute(s);
                    authInfo.getAttribs().put(attr.getName(), attr);
                }
                if (v instanceof String) {
                    String val = (String) v;
                    if (!attr.getValues().contains(val)) {
                        attr.getValues().add(val);
                    }
                } else if (v instanceof Object[]) {
                    for (Object vo : ((Object[]) v)) {
                        String vv = (String) vo;
                        if (vv != null && !attr.getValues().contains(vv)) {
                            attr.getValues().add(vv);
                        }
                    }
                }
            }
            as.setSuccess(true);
        } else {
            loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);
            as.setSuccess(true);
        }
    } catch (LDAPException e) {
        if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
            logger.error("Could not authenticate user", e);
        }
        as.setSuccess(false);
    }
}
Also used : LDAPAttribute(com.novell.ldap.LDAPAttribute) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) AuthController(com.tremolosecurity.proxy.auth.AuthController) LDAPEntry(com.novell.ldap.LDAPEntry) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException) JSONObject(org.jose4j.json.internal.json_simple.JSONObject)

Example 72 with AuthController

use of com.tremolosecurity.proxy.auth.AuthController in project OpenUnison by TremoloSecurity.

the class TokenData method processUserInfoRequest.

private void processUserInfoRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    AuthController ac = (AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL);
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    holder.getApp().getCookieConfig().getTimeout();
    String header = request.getHeader("Authorization");
    if (header == null) {
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(), "NONE");
        response.sendError(401);
        return;
    }
    String accessToken = header.substring("Bearer ".length());
    OidcSessionState dbSession = this.getSessionByAccessToken(accessToken);
    if (dbSession == null) {
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(), "NONE");
        response.sendError(401);
        return;
    }
    OpenIDConnectTrust trust = trusts.get(dbSession.getClientID());
    JsonWebSignature jws = new JsonWebSignature();
    jws.setCompactSerialization(this.decryptToken(this.trusts.get(dbSession.getClientID()).getCodeLastmileKeyName(), new Gson(), dbSession.getEncryptedIdToken()));
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName).getPublicKey());
    if (!jws.verifySignature()) {
        logger.warn("id_token tampered with");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(), "NONE");
        response.sendError(401);
        return;
    }
    JwtClaims claims = JwtClaims.parse(jws.getPayload());
    response.setContentType("application/jwt");
    String jwt = null;
    if (trust.isSignedUserInfo()) {
        jws = new JsonWebSignature();
        jws.setPayload(claims.toJson());
        jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
        jwt = jws.getCompactSerialization();
    } else {
        jwt = claims.toJson();
    }
    response.getOutputStream().write(jwt.getBytes("UTF-8"));
    AuthInfo remUser = new AuthInfo();
    remUser.setUserDN(dbSession.getUserDN());
    AccessLog.log(AccessEvent.AuSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE");
    AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE");
}
Also used : UrlHolder(com.tremolosecurity.config.util.UrlHolder) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) Gson(com.google.gson.Gson) AuthController(com.tremolosecurity.proxy.auth.AuthController) OidcSessionState(com.tremolosecurity.idp.providers.oidc.model.OidcSessionState)

Example 73 with AuthController

use of com.tremolosecurity.proxy.auth.AuthController in project OpenUnison by TremoloSecurity.

the class TokenData method clientCredentialsGrant.

private void clientCredentialsGrant(HttpServletRequest request, HttpServletResponse response, String clientID, String clientSecret, AuthController ac, UrlHolder holder) throws Exception, IOException, ServletException {
    OpenIDConnectTrust trust = this.trusts.get(clientID);
    if (trust == null) {
        String errorMessage = new StringBuilder().append("Trust '").append(clientID).append("' not found").toString();
        logger.warn(errorMessage);
        throw new Exception(errorMessage);
    }
    if (!trust.isEnableClientCredentialGrant()) {
        logger.error(new StringBuilder().append("Trust '").append(clientID).append("' does not support the client_credentials grant").toString());
        response.sendError(403);
        return;
    }
    String authChain = trust.getAuthChain();
    if (authChain == null) {
        if (trust.isPublicEndpoint()) {
            StringBuffer b = new StringBuffer();
            b.append("IdP does not have an authenticaiton chain configured, but is set to public");
            throw new ServletException(b.toString());
        } else {
            if (clientSecret == null || !clientSecret.equals(trust.getClientSecret())) {
                logger.warn(new StringBuilder().append("Invalid client secret for '").append(clientID).append("'"));
                response.sendError(401);
            } else {
                HttpSession session = request.getSession();
                AuthInfo authData = new AuthInfo();
                authData.setUserDN(new StringBuilder().append("uid=").append(clientID).append(",ou=oauth2,").append(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot()).toString());
                authData.setAuthLevel(0);
                authData.setAuthChain("anonymous");
                authData.getAttribs().put("uid", new Attribute("uid", clientID));
                authData.getAttribs().put("sub", new Attribute("sub", clientID));
                authData.getAttribs().put("client", new Attribute("client", "true"));
                authData.getAttribs().put("auth_chain", new Attribute("auth_chain", "anonymous"));
                authData.getAttribs().put("objectClass", new Attribute("objectClass", GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getUserObjectClass()));
                ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authData);
                AuthChainType act = holder.getConfig().getAuthChains().get(authChain);
                OpenIDConnectTransaction transaction = new OpenIDConnectTransaction();
                transaction.setClientID(clientID);
                session.setAttribute(OpenIDConnectIdP.TRANSACTION_DATA, transaction);
                ClientCredentialsGrantPostAuth postAuth = new ClientCredentialsGrantPostAuth(transaction, trust, this);
                request.setAttribute(PostAuthSuccess.POST_AUTH_ACTION, postAuth);
                postAuth.runAfterSuccessfulAuthentication(request, response, holder, act, null, ac, null);
            }
            return;
        }
    }
    HttpSession session = request.getSession();
    AuthInfo authData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    AuthChainType act = holder.getConfig().getAuthChains().get(authChain);
    OpenIDConnectTransaction transaction = new OpenIDConnectTransaction();
    transaction.setClientID(clientID);
    session.setAttribute(OpenIDConnectIdP.TRANSACTION_DATA, transaction);
    ClientCredentialsGrantPostAuth postAuth = new ClientCredentialsGrantPostAuth(transaction, trust, this);
    request.setAttribute(PostAuthSuccess.POST_AUTH_ACTION, postAuth);
    if (authData == null || !authData.isAuthComplete() && !(authData.getAuthLevel() < act.getLevel())) {
        nextTokenAuth(request, response, session, false, act);
    } else {
        if (authData.getAuthLevel() < act.getLevel()) {
            // step up authentication, clear existing auth data
            session.removeAttribute(ProxyConstants.AUTH_CTL);
            holder.getConfig().createAnonUser(session);
            nextTokenAuth(request, response, session, false, act);
        } else {
            // authenticated, next step
            postAuth.runAfterSuccessfulAuthentication(request, response, holder, act, null, ac, null);
        }
    }
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) HttpSession(javax.servlet.http.HttpSession) AuthController(com.tremolosecurity.proxy.auth.AuthController) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) LDAPException(com.novell.ldap.LDAPException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) JoseException(org.jose4j.lang.JoseException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ParseException(org.json.simple.parser.ParseException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) MalformedURLException(java.net.MalformedURLException) BadPaddingException(javax.crypto.BadPaddingException) ServletException(javax.servlet.ServletException) AuthChainType(com.tremolosecurity.config.xml.AuthChainType)

Example 74 with AuthController

use of com.tremolosecurity.proxy.auth.AuthController in project OpenUnison by TremoloSecurity.

the class TokenData method stsImpersontion.

private void stsImpersontion(HttpServletRequest request, HttpServletResponse response, String clientID, AuthController ac, UrlHolder holder, StsRequest stsRequest, OpenIDConnectTrust trust) throws ServletException, IOException {
    String authChain = trust.getAuthChain();
    if (authChain == null) {
        StringBuffer b = new StringBuffer();
        b.append("IdP does not have an authenticaiton chain configured");
        throw new ServletException(b.toString());
    }
    HttpSession session = request.getSession();
    AuthInfo authData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    AuthChainType act = holder.getConfig().getAuthChains().get(authChain);
    OpenIDConnectTransaction transaction = new OpenIDConnectTransaction();
    transaction.setClientID(clientID);
    session.setAttribute(OpenIDConnectIdP.TRANSACTION_DATA, transaction);
    TokenPostAuth postAuth = new TokenPostAuth(transaction, trust, stsRequest, this);
    request.setAttribute(PostAuthSuccess.POST_AUTH_ACTION, postAuth);
    if (authData == null || !authData.isAuthComplete() && !(authData.getAuthLevel() < act.getLevel())) {
        nextTokenAuth(request, response, session, false, act);
    } else {
        if (authData.getAuthLevel() < act.getLevel()) {
            // step up authentication, clear existing auth data
            session.removeAttribute(ProxyConstants.AUTH_CTL);
            holder.getConfig().createAnonUser(session);
            nextTokenAuth(request, response, session, false, act);
        } else {
            // authenticated, next step
            postAuth.runAfterSuccessfulAuthentication(request, response, holder, act, null, ac, null);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) HttpSession(javax.servlet.http.HttpSession) AuthController(com.tremolosecurity.proxy.auth.AuthController) AuthChainType(com.tremolosecurity.config.xml.AuthChainType)

Example 75 with AuthController

use of com.tremolosecurity.proxy.auth.AuthController in project OpenUnison by TremoloSecurity.

the class U2fAuth method startAuthentication.

private void startAuthentication(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws ServletException, MalformedURLException, IOException {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    // 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();
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    String challengeStoreAttribute = authParams.get("attribute").getValues().get(0);
    String encyrptionKeyName = authParams.get("encryptionKeyName").getValues().get(0);
    String uidAttributeName = authParams.get("uidAttributeName").getValues().get(0);
    String formURI = authParams.get("formURI").getValues().get(0);
    List<SecurityKeyData> keys;
    try {
        keys = U2fUtil.loadUserKeys(userData, challengeStoreAttribute, encyrptionKeyName);
    } catch (Exception e1) {
        throw new ServletException("Could not loak keys", e1);
    }
    Set<String> origins = new HashSet<String>();
    String appID = U2fUtil.getApplicationId(request);
    origins.add(appID);
    U2FServer u2f = new U2FServerUnison(this.challengeGen, new UnisonDataStore(UUID.randomUUID().toString(), keys), new BouncyCastleCrypto(), origins);
    String uid = userData.getAttribs().get(uidAttributeName).getValues().get(0);
    if (keys == null || keys.size() == 0) {
        if (amt.getRequired().equals("required")) {
            as.setSuccess(false);
        }
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }
    U2fSignRequest sigReq = null;
    try {
        sigReq = u2f.getSignRequest(uid, appID);
    } catch (U2FException e) {
        logger.error("Could not start authentication", e);
        if (amt.getRequired().equals("required")) {
            as.setSuccess(false);
        }
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }
    Gson gson = new Gson();
    request.getSession().setAttribute(AUTH_SIGN_REQ, sigReq);
    request.getSession().setAttribute(AUTH_SIGN_REQ_JSON, gson.toJson(sigReq));
    request.getSession().setAttribute(SERVER, u2f);
    response.sendRedirect(formURI);
}
Also used : U2FServer(com.google.u2f.server.U2FServer) BouncyCastleCrypto(com.google.u2f.server.impl.BouncyCastleCrypto) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) Gson(com.google.gson.Gson) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) U2fSignRequest(com.google.u2f.server.messages.U2fSignRequest) SecurityKeyData(com.google.u2f.server.data.SecurityKeyData) U2FException(com.google.u2f.U2FException) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) HashSet(java.util.HashSet) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) AuthController(com.tremolosecurity.proxy.auth.AuthController) ServletException(javax.servlet.ServletException) U2FException(com.google.u2f.U2FException) MalformedURLException(java.net.MalformedURLException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException)

Aggregations

AuthController (com.tremolosecurity.proxy.auth.AuthController)76 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)59 Attribute (com.tremolosecurity.saml.Attribute)45 ServletException (javax.servlet.ServletException)28 HttpSession (javax.servlet.http.HttpSession)28 UrlHolder (com.tremolosecurity.config.util.UrlHolder)26 HashMap (java.util.HashMap)25 IOException (java.io.IOException)24 LDAPAttribute (com.novell.ldap.LDAPAttribute)21 LDAPException (com.novell.ldap.LDAPException)19 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)19 Gson (com.google.gson.Gson)18 RequestHolder (com.tremolosecurity.proxy.auth.RequestHolder)17 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)14 ConfigManager (com.tremolosecurity.config.util.ConfigManager)14 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)12 MalformedURLException (java.net.MalformedURLException)12 ArrayList (java.util.ArrayList)12 LDAPEntry (com.novell.ldap.LDAPEntry)11