Search in sources :

Example 11 with Token

use of com.tremolosecurity.json.Token in project OpenUnison by TremoloSecurity.

the class UpdateApprovalAZListener method updateAllowedApprovals.

private void updateAllowedApprovals(ConfigManager cfg, int approvalID, String workflowObj) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException, ProvisioningException, SQLException, InvalidAlgorithmParameterException {
    SecretKey decryptionKey = cfg.getSecretKey(cfg.getCfg().getProvisioning().getApprovalDB().getEncryptionKey());
    Gson gson = new Gson();
    Token token = gson.fromJson(workflowObj, 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, decryptionKey, spec);
    byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
    String json = new String(cipher.doFinal(encBytes));
    Workflow wf = (Workflow) JsonReader.jsonToJava(json);
    Approval approval = (Approval) wf.findCurrentApprovalTask();
    if (approval == null) {
        throw new ProvisioningException("Could not locate approval step");
    }
    Set<Integer> currentApprovers = new HashSet<Integer>();
    Session session = cfg.getProvisioningEngine().getHibernateSessionFactory().openSession();
    try {
        Approvals approvalObj = session.load(Approvals.class, approval.getId());
        for (AllowedApprovers approver : approvalObj.getAllowedApproverses()) {
            currentApprovers.add(approver.getApprovers().getId());
        }
        session.beginTransaction();
        for (AllowedApprovers approver : approvalObj.getAllowedApproverses()) {
            session.delete(approver);
        }
        approvalObj.getAllowedApproverses().clear();
        approval.updateAllowedApprovals(session, cfg, wf.getRequest());
        // need to write the approval back to the db
        json = JsonWriter.objectToJson(wf);
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, decryptionKey);
        byte[] encJson = cipher.doFinal(json.getBytes("UTF-8"));
        String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));
        token = new Token();
        token.setEncryptedRequest(base64d);
        token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));
        // String base64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));
        approvalObj.setWorkflowObj(gson.toJson(token));
        session.save(approvalObj);
        session.getTransaction().commit();
        approvalObj = session.load(Approvals.class, approvalObj.getId());
        for (AllowedApprovers approver : approvalObj.getAllowedApproverses()) {
            if (!currentApprovers.contains(approver.getApprovers().getId())) {
                this.sendNotification(approval.getEmailTemplate(), cfg, session, approver.getApprovers().getUserKey());
            }
        }
    } catch (Throwable t) {
        try {
            if (session != null) {
                session.getTransaction().rollback();
            }
        } catch (Throwable tx) {
        }
        ;
        throw t;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
Also used : Gson(com.google.gson.Gson) Workflow(com.tremolosecurity.provisioning.core.Workflow) Approvals(com.tremolosecurity.provisioning.objects.Approvals) Token(com.tremolosecurity.json.Token) SecretKey(javax.crypto.SecretKey) AllowedApprovers(com.tremolosecurity.provisioning.objects.AllowedApprovers) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) Approval(com.tremolosecurity.provisioning.tasks.Approval) HashSet(java.util.HashSet) Session(org.hibernate.Session)

Example 12 with Token

use of com.tremolosecurity.json.Token in project OpenUnison by TremoloSecurity.

the class SessionTimeoutChecker method createSession.

private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp, ServletContext ctx, SecretKey encKey) throws Exception {
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);
    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();
    // HttpSession session = req.getSession(true);
    TremoloHttpSession tsession = new TremoloHttpSession(id);
    tsession.setAppName(app.getName());
    tsession.refresh(this.ctx, this);
    tsession.setOpen(false);
    this.anonMech.createSession(tsession, this.anonChainType);
    AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL);
    AuthInfo auInfo = actl.getAuthInfo();
    auInfo.setAuthComplete(true);
    // session.setAttribute(app.getCookieConfig().getSessionCookieName(),
    // tsession);
    tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id);
    tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encKey);
    byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8"));
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encSessionKey));
    Token token = new Token();
    token.setEncryptedRequest(base64d);
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));
    Gson gson = new Gson();
    String cookie = gson.toJson(token);
    byte[] btoken = cookie.getBytes("UTF-8");
    String encCookie = new String(org.bouncycastle.util.encoders.Base64.encode(btoken));
    Cookie sessionCookie;
    sessionCookie = new Cookie(app.getCookieConfig().getSessionCookieName(), encCookie);
    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);
    String domain = ProxyTools.getInstance().getCookieDomain(app.getCookieConfig(), req);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    sessionCookie.setSecure(app.getCookieConfig().isSecure());
    sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly());
    // resp.addCookie(sessionCookie);
    ProxyResponse.addCookieToResponse(app, sessionCookie, resp);
    // delete the opensession if it exists
    if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null && !cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) {
        Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);
        openSessionCookie.setPath("/");
        openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
        openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
        openSessionCookie.setMaxAge(0);
        resp.addCookie(openSessionCookie);
    }
    sessions.put(id, tsession);
    return tsession;
}
Also used : Cookie(javax.servlet.http.Cookie) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Gson(com.google.gson.Gson) Token(com.tremolosecurity.json.Token) Cipher(javax.crypto.Cipher) AuthController(com.tremolosecurity.proxy.auth.AuthController)

Example 13 with Token

use of com.tremolosecurity.json.Token in project OpenUnison by TremoloSecurity.

the class Approver method doTask.

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {
    if (this.isOnHold()) {
        return runChildTasks(user, request);
    } else {
        Session session = this.getConfigManager().getProvisioningEngine().getHibernateSessionFactory().openSession();
        try {
            session.beginTransaction();
            DateTime now = new DateTime();
            Approvals approval = new Approvals();
            approval.setLabel(this.renderTemplate(this.label, request));
            approval.setWorkflow(this.getWorkflow().getFromDB(session));
            approval.setCreateTs(new Timestamp(now.getMillis()));
            session.save(approval);
            this.id = approval.getId();
            // request.put("APPROVAL_ID", Integer.toString(this.id));
            request.put("APPROVAL_ID", this.id);
            if (request.get(Approval.APPROVAL_RESULT) != null) {
                request.remove(Approval.APPROVAL_RESULT);
            }
            this.setOnHold(true);
            Gson gson = new Gson();
            String json = "";
            synchronized (this.getWorkflow()) {
                json = JsonWriter.objectToJson(this.getWorkflow());
            }
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, this.getConfigManager().getSecretKey(this.getConfigManager().getCfg().getProvisioning().getApprovalDB().getEncryptionKey()));
            byte[] encJson = cipher.doFinal(json.getBytes("UTF-8"));
            String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));
            Token token = new Token();
            token.setEncryptedRequest(base64d);
            token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));
            // String base64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));
            approval.setWorkflowObj(gson.toJson(token));
            session.save(approval);
            boolean sendNotification = true;
            if (request.containsKey(Approval.SEND_NOTIFICATION) && request.get(Approval.SEND_NOTIFICATION).equals("false")) {
                sendNotification = false;
            }
            String localTemplate = this.renderTemplate(this.emailTemplate, request);
            for (Approver approver : this.approvers) {
                String[] localParams = null;
                localParams = renderCustomParameters(request, approver, localParams);
                String constraintRendered = this.renderTemplate(approver.constraint, request);
                switch(approver.type) {
                    case StaticGroup:
                        AzUtils.loadStaticGroupApprovers(approval, localTemplate, this.getConfigManager(), session, id, constraintRendered, sendNotification);
                        break;
                    case Filter:
                        AzUtils.loadFilterApprovers(approval, localTemplate, this.getConfigManager(), session, id, constraintRendered, sendNotification);
                        break;
                    case DN:
                        AzUtils.loadDNApprovers(approval, localTemplate, this.getConfigManager(), session, id, constraintRendered, sendNotification);
                        break;
                    case Custom:
                        AzUtils.loadCustomApprovers(approval, localTemplate, this.getConfigManager(), session, id, constraintRendered, sendNotification, approver.customAz, localParams);
                        break;
                }
            }
            session.getTransaction().commit();
            if (request.get(Approval.IMMEDIATE_ACTION) != null && request.get(Approval.REASON) != null) {
                String reason = (String) request.get(Approval.REASON);
                boolean action = false;
                Object tmp = request.get(Approval.IMMEDIATE_ACTION);
                if (tmp instanceof String) {
                    action = tmp.equals("true");
                } else {
                    action = (boolean) tmp;
                }
                try {
                    GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().doApproval(this.id, this.getWorkflow().getRequester().getUserID(), action, reason);
                } catch (ProvisioningException pe) {
                    logger.warn("Could not execute pre-approval", pe);
                }
            }
            return false;
        } catch (IOException e) {
            throw new ProvisioningException("Could not store approval", e);
        } catch (NoSuchAlgorithmException e) {
            throw new ProvisioningException("Could not encrypt workflow object", e);
        } catch (NoSuchPaddingException e) {
            throw new ProvisioningException("Could not encrypt workflow object", e);
        } catch (InvalidKeyException e) {
            throw new ProvisioningException("Could not encrypt workflow object", e);
        } catch (IllegalBlockSizeException e) {
            throw new ProvisioningException("Could not encrypt workflow object", e);
        } catch (BadPaddingException e) {
            throw new ProvisioningException("Could not encrypt workflow object", e);
        } finally {
            if (session != null) {
                if (session.getTransaction() != null && session.getTransaction().getStatus() == TransactionStatus.ACTIVE) {
                    session.getTransaction().rollback();
                }
                session.close();
            }
        }
    }
}
Also used : Approvals(com.tremolosecurity.provisioning.objects.Approvals) Gson(com.google.gson.Gson) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Token(com.tremolosecurity.json.Token) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) Timestamp(java.sql.Timestamp) DateTime(org.joda.time.DateTime) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) Cipher(javax.crypto.Cipher) Session(org.hibernate.Session)

Example 14 with Token

use of com.tremolosecurity.json.Token in project OpenUnison by TremoloSecurity.

the class CreateOTPKey method generateEncryptedToken.

public static String generateEncryptedToken(String userID, GoogleAuthenticatorKey key, String hostName, ConfigManager cfg, String encryptionKey) throws ProvisioningException {
    TOTPKey totpkey = new TOTPKey();
    totpkey.setHost(hostName);
    totpkey.setScratchCodes(key.getScratchCodes());
    totpkey.setSecretKey(key.getKey());
    totpkey.setUserName(userID);
    totpkey.setValidationCode(key.getVerificationCode());
    Gson gson = new Gson();
    String json = gson.toJson(totpkey);
    SecretKey sc = cfg.getSecretKey(encryptionKey);
    String attrVal = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(json.getBytes("UTF-8"));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, sc);
        byte[] encJson = cipher.doFinal(baos.toByteArray());
        String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));
        Token token = new Token();
        token.setEncryptedRequest(base64d);
        token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));
        json = gson.toJson(token);
        attrVal = new String(org.bouncycastle.util.encoders.Base64.encode(json.getBytes("UTF-8")));
    } catch (Exception e) {
        throw new ProvisioningException("Could not encrypt key", e);
    }
    return attrVal;
}
Also used : SecretKey(javax.crypto.SecretKey) TOTPKey(com.tremolosecurity.proxy.auth.otp.TOTPKey) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) Gson(com.google.gson.Gson) Token(com.tremolosecurity.json.Token) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Cipher(javax.crypto.Cipher) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException)

Example 15 with Token

use of com.tremolosecurity.json.Token in project OpenUnison by TremoloSecurity.

the class TokenData method refreshToken.

private void refreshToken(HttpServletResponse response, String clientID, String clientSecret, String refreshToken, UrlHolder holder, HttpServletRequest request, AuthInfo authData) throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException, JoseException, InvalidJwtException, UnsupportedEncodingException {
    Gson gson = new Gson();
    String json = this.inflate(refreshToken);
    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, GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(this.trusts.get(clientID).getCodeLastmileKeyName()), spec);
    byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
    String decryptedRefreshToken = new String(cipher.doFinal(encBytes));
    OidcSessionState session = this.getSessionByRefreshToken(decryptedRefreshToken);
    if (session == null) {
        logger.warn("Session does not exist from refresh_token");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
        response.sendError(401);
        return;
    }
    if (!session.getRefreshToken().equals(refreshToken)) {
        logger.warn("Session does not exist from refresh_token");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
        response.sendError(401);
        return;
    }
    OpenIDConnectTrust trust = this.trusts.get(session.getClientID());
    if (!trust.isPublicEndpoint()) {
        if (!trust.getClientSecret().equals(clientSecret)) {
            logger.warn("Invalid client_secret");
            AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
            response.sendError(401);
            return;
        }
    }
    if (session.getExpires().isBeforeNow()) {
        logger.warn("Session expired");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
        response.sendError(401);
        this.sessionStore.deleteSession(session.getSessionID());
        return;
    }
    JsonWebSignature jws = new JsonWebSignature();
    jws.setCompactSerialization(this.decryptToken(this.trusts.get(session.getClientID()).getCodeLastmileKeyName(), gson, session.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, authData, "NONE");
        response.sendError(401);
        return;
    }
    JwtClaims claims = JwtClaims.parse(jws.getPayload());
    // a unique identifier for the token
    claims.setGeneratedJwtId();
    // when the token was issued/created (now)
    claims.setIssuedAtToNow();
    // time before which the token is not yet valid (2 minutes ago)
    claims.setNotBeforeMinutesInThePast(trusts.get(clientID).getAccessTokenSkewMillis() / 1000 / 60);
    // time when the token will expire (10 minutes from now)
    claims.setExpirationTimeMinutesInTheFuture(trusts.get(clientID).getAccessTokenTimeToLive() / 1000 / 60);
    jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    String newIdToken = jws.getCompactSerialization();
    session.setEncryptedIdToken(this.encryptToken(this.trusts.get(session.getClientID()).getCodeLastmileKeyName(), gson, newIdToken));
    jws = new JsonWebSignature();
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName).getPublicKey());
    jws.setCompactSerialization(this.decryptToken(this.trusts.get(session.getClientID()).getCodeLastmileKeyName(), gson, session.getEncryptedAccessToken()));
    if (!jws.verifySignature()) {
        logger.warn("access_token tampered with");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
        response.sendError(401);
        return;
    }
    claims = JwtClaims.parse(jws.getPayload());
    // a unique identifier for the token
    claims.setGeneratedJwtId();
    // when the token was issued/created (now)
    claims.setIssuedAtToNow();
    // time before which the token is not yet valid (2 minutes ago)
    claims.setNotBeforeMinutesInThePast(trusts.get(clientID).getAccessTokenSkewMillis() / 1000 / 60);
    // time when the token will expire (10 minutes from now)
    claims.setExpirationTimeMinutesInTheFuture(trusts.get(clientID).getAccessTokenTimeToLive() / 1000 / 60);
    jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKeyIdHeaderValue(this.buildKID(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName)));
    String newAccessToken = jws.getCompactSerialization();
    session.setEncryptedAccessToken(this.encryptToken(trust.getCodeLastmileKeyName(), gson, newAccessToken));
    String b64 = encryptToken(trusts.get(clientID).getCodeLastmileKeyName(), gson, session.getSessionID());
    session.setRefreshToken(b64);
    session.setExpires(new DateTime().plusSeconds(holder.getApp().getCookieConfig().getTimeout()));
    this.sessionStore.resetSession(session);
    OpenIDConnectAccessToken access = new OpenIDConnectAccessToken();
    access.setAccess_token(newAccessToken);
    access.setExpires_in((int) (trusts.get(clientID).getAccessTokenTimeToLive() / 1000));
    access.setId_token(newIdToken);
    access.setToken_type("Bearer");
    access.setRefresh_token(session.getRefreshToken());
    json = gson.toJson(access);
    response.setContentType("text/json");
    response.getOutputStream().write(json.getBytes());
    response.getOutputStream().flush();
    AuthInfo remUser = new AuthInfo();
    remUser.setUserDN(session.getUserDN());
    AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE");
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) JwtClaims(org.jose4j.jwt.JwtClaims) Gson(com.google.gson.Gson) Token(com.tremolosecurity.json.Token) DateTime(org.joda.time.DateTime) JsonWebSignature(org.jose4j.jws.JsonWebSignature) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) OidcSessionState(com.tremolosecurity.idp.providers.oidc.model.OidcSessionState)

Aggregations

Token (com.tremolosecurity.json.Token)16 Cipher (javax.crypto.Cipher)16 Gson (com.google.gson.Gson)13 IvParameterSpec (javax.crypto.spec.IvParameterSpec)10 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)4 Approvals (com.tremolosecurity.provisioning.objects.Approvals)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 SecretKey (javax.crypto.SecretKey)4 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)3 TOTPKey (com.tremolosecurity.proxy.auth.otp.TOTPKey)3 Attribute (com.tremolosecurity.saml.Attribute)3 IOException (java.io.IOException)3 Session (org.hibernate.Session)3 LDAPAttribute (com.novell.ldap.LDAPAttribute)2 LDAPEntry (com.novell.ldap.LDAPEntry)2 LDAPException (com.novell.ldap.LDAPException)2 Workflow (com.tremolosecurity.provisioning.core.Workflow)2 AllowedApprovers (com.tremolosecurity.provisioning.objects.AllowedApprovers)2 Approval (com.tremolosecurity.provisioning.tasks.Approval)2 AuthController (com.tremolosecurity.proxy.auth.AuthController)2