Search in sources :

Example 1 with AuthInfo

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

the class K8sInjectImpersonation method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    Iterator<String> it = request.getHeaderNames();
    List<String> toRemove = new ArrayList<String>();
    while (it.hasNext()) {
        String headerName = it.next();
        if (headerName.toLowerCase().startsWith("impersonate-") || headerName.equalsIgnoreCase("Authorization")) {
            toRemove.add(headerName);
        }
    }
    for (String headerToRemove : toRemove) {
        request.removeHeader(headerToRemove);
    }
    request.removeHeader("Authorization");
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    request.addHeader(new Attribute("Impersonate-User", userData.getAttribs().get(this.userNameAttribute).getValues().get(0)));
    Attribute groups = new Attribute("Impersonate-Group");
    groups.getValues().add("system:authenticated");
    Attribute fromUser = userData.getAttribs().get(this.groupAttribute);
    if (fromUser != null) {
        groups.getValues().addAll(fromUser.getValues());
    }
    if (groups.getValues().size() > 0) {
        request.addHeader(groups);
    }
    OpenShiftTarget target = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.targetName).getProvider();
    request.addHeader(new Attribute("Authorization", new StringBuilder().append("Bearer ").append(target.getAuthToken()).toString()));
    HashMap<String, String> uriParams = (HashMap<String, String>) request.getAttribute("TREMOLO_URI_PARAMS");
    uriParams.put("k8s_url", target.getUrl());
    chain.nextFilter(request, response, chain);
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) AuthController(com.tremolosecurity.proxy.auth.AuthController)

Example 2 with AuthInfo

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

the class RegisterPasswordResetAuth method doGet.

@Override
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);
    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());
    AuthController ac = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL));
    AuthInfo au = ac.getAuthInfo();
    Attribute uid = au.getAttribs().get(this.uidAttribute);
    if (uid == null) {
        logger.warn("Attribute : '" + this.uidAttribute + "' does not exist");
        as.setSuccess(false);
    } else {
        ResetUserPasswordOnLogout logoutHandler = new ResetUserPasswordOnLogout(this.workflowName, this.uidAttribute, uid.getValues().get(0));
        LogoutUtil.insertFirstLogoutHandler(request, logoutHandler);
        as.setSuccess(true);
    }
    holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) AuthController(com.tremolosecurity.proxy.auth.AuthController) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) AuthChainType(com.tremolosecurity.config.xml.AuthChainType)

Example 3 with AuthInfo

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

the class ScaleToken method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    Gson gson = new Gson();
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
    if (request.getRequestURI().endsWith("/token/config")) {
        response.setContentType("application/json");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().println(gson.toJson(scaleConfig).trim());
    } else if (request.getMethod().equalsIgnoreCase("GET") && request.getRequestURI().endsWith("/token/user")) {
        AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
        ScaleTokenUser stu = new ScaleTokenUser();
        Attribute displayNameAttribute = userData.getAttribs().get(this.scaleConfig.getDisplayNameAttribute());
        if (displayNameAttribute != null) {
            stu.setDisplayName(displayNameAttribute.getValues().get(0));
        } else {
            stu.setDisplayName("Unknown");
        }
        stu.setToken(this.tokenLoader.loadToken(userData, request.getSession()));
        ScaleJSUtils.addCacheHeaders(response);
        response.setContentType("application/json");
        response.getWriter().println(gson.toJson(stu).trim());
    }
}
Also used : ScaleTokenUser(com.tremolosecurity.scalejs.token.data.ScaleTokenUser) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) Gson(com.google.gson.Gson)

Example 4 with AuthInfo

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

the class SendMessageThread method doApproval.

/* (non-Javadoc)
	 * @see com.tremolosecurity.provisioning.core.ProvisioningEngine#doApproval(int, java.lang.String, boolean, java.lang.String)
	 */
@Override
public void doApproval(int id, String userID, boolean approved, String reason) throws ProvisioningException {
    org.hibernate.Session session = this.sessionFactory.openSession();
    try {
        StringBuffer b = new StringBuffer();
        LDAPSearchResults res = this.cfgMgr.getMyVD().search(this.cfgMgr.getCfg().getLdapRoot(), 2, equal(this.userIDAttributeName, userID).toString(), new ArrayList<String>());
        if (!res.hasMore()) {
            throw new ProvisioningException("Could not locate approver '" + userID + "'");
        }
        LDAPEntry approver = res.next();
        AuthInfo auinfo = new AuthInfo();
        auinfo.setUserDN(approver.getDN());
        LDAPAttributeSet attrs = approver.getAttributeSet();
        for (Object obj : attrs) {
            LDAPAttribute attr = (LDAPAttribute) obj;
            Attribute attrib = new Attribute(attr.getName());
            String[] vals = attr.getStringValueArray();
            for (String val : vals) {
                attrib.getValues().add(val);
            }
            auinfo.getAttribs().put(attrib.getName(), attrib);
        }
        while (res.hasMore()) res.next();
        Query query = session.createQuery("FROM Approvers WHERE userKey = :user_key");
        query.setParameter("user_key", userID);
        List<Approvers> approvers = query.list();
        Approvers approverObj = null;
        if (logger.isDebugEnabled()) {
            logger.debug("Approver UserID : " + userID);
        }
        int approverID;
        if (approvers.size() == 0) {
            approverObj = new Approvers();
            approverObj.setUserKey(userID);
            session.save(approverObj);
            approverID = approverObj.getId();
        } else {
            approverObj = approvers.get(0);
            approverID = approverObj.getId();
        }
        session.beginTransaction();
        boolean changed = false;
        for (String attrName : this.getApproverAttributes()) {
            boolean found = false;
            for (ApproverAttributes appAttr : approverObj.getApproverAttributeses()) {
                if (attrName.equalsIgnoreCase(appAttr.getName())) {
                    found = true;
                    LDAPAttribute approverAttr = approver.getAttribute(attrName);
                    if (approverAttr != null) {
                        if (!approverAttr.getStringValue().equals(appAttr.getValue())) {
                            appAttr.setValue(approverAttr.getStringValue());
                            session.save(appAttr);
                        }
                    }
                }
            }
            if (!found) {
                ApproverAttributes attr = new ApproverAttributes();
                attr.setName(attrName);
                LDAPAttribute approverAttr = approver.getAttribute(attrName);
                if (approverAttr != null) {
                    attr.setValue(approverAttr.getStringValue());
                }
                attr.setApprovers(approverObj);
                approverObj.getApproverAttributeses().add(attr);
                session.save(attr);
                changed = true;
            }
        }
        Approvals approvals = session.load(Approvals.class, id);
        if (approvals == null) {
            throw new ProvisioningException("Approval not found");
        }
        Gson gson = new Gson();
        String json = approvals.getWorkflowObj();
        Token token = gson.fromJson(json, Token.class);
        byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());
        IvParameterSpec spec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, this.cfgMgr.getSecretKey(this.cfgMgr.getCfg().getProvisioning().getApprovalDB().getEncryptionKey()), spec);
        byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
        String jsonDecr = new String(cipher.doFinal(encBytes));
        Workflow wf = (Workflow) JsonReader.jsonToJava(jsonDecr);
        Approval approval = (Approval) wf.findCurrentApprovalTask();
        if (approval == null) {
            throw new ProvisioningException("Could not locate approval step");
        }
        AzSys az = new AzSys();
        for (AzRule rule : approval.getAzRules()) {
            if (rule.getCustomAuthorization() != null) {
                rule.getCustomAuthorization().loadConfigManager(cfgMgr);
                rule.getCustomAuthorization().setWorkflow(wf);
            }
        }
        if (!az.checkRules(auinfo, this.cfgMgr, approval.getAzRules(), wf.getRequest())) {
            throw new ProvisioningException("Az of approval failed");
        }
        DateTime now = new DateTime();
        approvals.setWorkflowObj(null);
        approvals.setApprovedTs(new Timestamp(now.getMillis()));
        approvals.setApprovers(approverObj);
        approvals.setApproved(approved ? 1 : 0);
        approvals.setReason(reason);
        session.save(approvals);
        wf.getRequest().put(Approval.APPROVAL_RESULT, new Boolean(approved));
        approval.markComplete(approved);
        if (approved) {
            wf.reInit(cfgMgr);
            wf.restart();
        } else {
            if (wf.getUserNum() != wf.getRequesterNum()) {
                wf.getRequester().getAttribs().put("reason", new Attribute("reason", reason));
                if (!wf.getRequester().getAttribs().containsKey(approval.getMailAttr())) {
                    logger.warn("Can not send failure notification to " + wf.getRequester().getUserID() + ", no mail found");
                } else {
                    this.sendNotification(wf.getRequester().getAttribs().get(approval.getMailAttr()).getValues().get(0), approval.getFailureEmailMsg(), approval.getFailureEmailSubject(), wf.getRequester());
                }
            }
            wf.getUser().getAttribs().put("reason", new Attribute("reason", reason));
            if (!wf.getUser().getAttribs().containsKey(approval.getMailAttr())) {
                logger.warn("Can not send failure notification to " + wf.getUser().getUserID() + ", no mail found");
            } else {
                this.sendNotification(wf.getUser().getAttribs().get(approval.getMailAttr()).getValues().get(0), approval.getFailureEmailMsg(), approval.getFailureEmailSubject(), wf.getUser());
            }
            wf.reInit(cfgMgr);
            wf.restart();
        }
        session.getTransaction().commit();
    } catch (LDAPException e) {
        throw new ProvisioningException("Could not load approver", e);
    } catch (SQLException e) {
        throw new ProvisioningException("Could not load saved workflow", e);
    } catch (IOException e) {
        throw new ProvisioningException("Could not load saved workflow", e);
    } catch (ClassNotFoundException e) {
        throw new ProvisioningException("Could not load saved workflow", e);
    } catch (NoSuchAlgorithmException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (NoSuchPaddingException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (InvalidKeyException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (IllegalBlockSizeException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (BadPaddingException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (ProvisioningException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Exception running workflow", e);
        throw new ProvisioningException("Exception running workflow", e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
Also used : ApproverAttributes(com.tremolosecurity.provisioning.objects.ApproverAttributes) Query(org.hibernate.Query) Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) SQLException(java.sql.SQLException) Approvals(com.tremolosecurity.provisioning.objects.Approvals) Gson(com.google.gson.Gson) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Token(com.tremolosecurity.json.Token) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) Timestamp(java.sql.Timestamp) DateTime(org.joda.time.DateTime) LDAPEntry(com.novell.ldap.LDAPEntry) Approvers(com.tremolosecurity.provisioning.objects.Approvers) AllowedApprovers(com.tremolosecurity.provisioning.objects.AllowedApprovers) Approval(com.tremolosecurity.provisioning.tasks.Approval) LDAPAttribute(com.novell.ldap.LDAPAttribute) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) LDAPAttributeSet(com.novell.ldap.LDAPAttributeSet) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) LDAPException(com.novell.ldap.LDAPException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SocketException(java.net.SocketException) SQLException(java.sql.SQLException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) MessagingException(javax.mail.MessagingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) JMSException(javax.jms.JMSException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) BadPaddingException(javax.crypto.BadPaddingException) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException) AzSys(com.tremolosecurity.proxy.auth.AzSys) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) AzRule(com.tremolosecurity.proxy.az.AzRule)

Example 5 with AuthInfo

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

the class SamlTransaction method doFederation.

private void doFederation(HttpServletRequest request, HttpServletResponse response, String issuer, String nameID, String authnCtx, String url, String relayState, Saml2Trust trust) throws Exception, ServletException, IOException {
    if (authnCtx == null) {
        authnCtx = trust.params.get("defaultAuthCtx").getValues().get(0);
    }
    if (nameID == null) {
        nameID = trust.params.get("defaultNameId").getValues().get(0);
    }
    String authChain = trust.authChainMap.get(authnCtx);
    if (authChain == null) {
        StringBuffer b = new StringBuffer();
        b.append("IdP does not have an authenticaiton chain configured with '").append(authnCtx).append("'");
        throw new Exception(b.toString());
    }
    String nameIDAttr = trust.nameIDMap.get(nameID);
    if (logger.isDebugEnabled()) {
        logger.debug("Auth Chain : '" + authChain + "'");
        logger.debug("NameID Attr : '" + nameIDAttr + "'");
    }
    HttpSession session = request.getSession();
    AuthInfo authData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    AuthChainType act = holder.getConfig().getAuthChains().get(authChain);
    if (url == null) {
        url = trust.params.get("httpPostRespURL").getValues().get(0);
    }
    SamlTransaction transaction = new SamlTransaction();
    transaction.issuer = issuer;
    transaction.nameIDAttr = nameIDAttr;
    transaction.nameIDFormat = nameID;
    transaction.postToURL = url;
    transaction.authnCtxName = authnCtx;
    transaction.relayState = relayState;
    session.setAttribute(Saml2Idp.TRANSACTION_DATA, transaction);
    if (authData == null || !authData.isAuthComplete() && !(authData.getAuthLevel() < act.getLevel())) {
        nextAuth(request, response, session, false, act);
    } else {
        if (authData.getAuthLevel() < act.getLevel()) {
            // step up authentication, clear existing auth data
            /*AuthController controller = ((AuthController) session.getAttribute(AuthSys.AUTH_CTL));
				controller.setHolder(null);
				for (AuthStep as : controller.getAuthSteps()) {
					as.setExecuted(false);
					as.setSuccess(false);
				}*/
            session.removeAttribute(ProxyConstants.AUTH_CTL);
            holder.getConfig().createAnonUser(session);
            nextAuth(request, response, session, false, act);
        } else {
            // chain.doFilter(req, resp);
            // next.nextSys((HttpServletRequest) req, (HttpServletResponse) resp);
            StringBuffer b = genFinalURL(request);
            response.sendRedirect(b.toString());
        }
    }
}
Also used : UrlHolder(com.tremolosecurity.config.util.UrlHolder) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) HttpSession(javax.servlet.http.HttpSession) AuthController(com.tremolosecurity.proxy.auth.AuthController) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) 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)

Aggregations

AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)71 AuthController (com.tremolosecurity.proxy.auth.AuthController)59 Attribute (com.tremolosecurity.saml.Attribute)46 LDAPAttribute (com.novell.ldap.LDAPAttribute)27 IOException (java.io.IOException)25 ServletException (javax.servlet.ServletException)24 HttpSession (javax.servlet.http.HttpSession)23 Gson (com.google.gson.Gson)22 LDAPException (com.novell.ldap.LDAPException)22 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)22 LDAPEntry (com.novell.ldap.LDAPEntry)19 HashMap (java.util.HashMap)19 UrlHolder (com.tremolosecurity.config.util.UrlHolder)18 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)18 MalformedURLException (java.net.MalformedURLException)15 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)14 ArrayList (java.util.ArrayList)14 AzSys (com.tremolosecurity.proxy.auth.AzSys)12 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11