Search in sources :

Example 6 with Token

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

the class SessionTimeoutChecker method findSessionFromCookie.

public static TremoloHttpSession findSessionFromCookie(Cookie sessionCookie, SecretKey encKey, SessionManagerImpl sessionMgr) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    String tokenHeader = new String(org.bouncycastle.util.encoders.Base64.decode(sessionCookie.getValue().getBytes("UTF-8")));
    Gson gson = new Gson();
    Token token = gson.fromJson(tokenHeader, 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, encKey, spec);
    byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
    String requestToken = new String(cipher.doFinal(encBytes));
    TremoloHttpSession tsession = sessionMgr.getSessions().get(requestToken);
    return tsession;
}
Also used : Gson(com.google.gson.Gson) Token(com.tremolosecurity.json.Token) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 7 with Token

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

the class TOTPToken method loadToken.

@Override
public Object loadToken(AuthInfo user, HttpSession session) throws Exception {
    HashMap<String, String> tokenRet = new HashMap<String, String>();
    Attribute attr = user.getAttribs().get(this.attributeName);
    if (attr != null) {
        String json = attr.getValues().get(0);
        SecretKey decryptionKey = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encryptionKey);
        Gson gson = new Gson();
        Token token = gson.fromJson(new String(Base64.decode(json.getBytes("UTF-8"))), 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);
        String decryptedJSON = new String(cipher.doFinal(Base64.decode(token.getEncryptedRequest().getBytes("UTF-8"))));
        if (logger.isDebugEnabled())
            logger.debug(decryptedJSON);
        TOTPKey totp = gson.fromJson(decryptedJSON, TOTPKey.class);
        tokenRet.put("TOTP URL", "otpauth://totp/" + totp.getUserName() + "@" + totp.getHost() + "?secret=" + totp.getSecretKey());
    } else {
        tokenRet.put("TOTP URL", "No password found");
    }
    return tokenRet;
}
Also used : SecretKey(javax.crypto.SecretKey) HashMap(java.util.HashMap) Attribute(com.tremolosecurity.saml.Attribute) TOTPKey(com.tremolosecurity.proxy.auth.otp.TOTPKey) Gson(com.google.gson.Gson) Token(com.tremolosecurity.json.Token) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 8 with Token

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

the class AuthTOTPInsert method bind.

public void bind(BindInterceptorChain chain, DistinguishedName dn, Password pwd, LDAPConstraints constraints) throws LDAPException {
    DistinguishedName localdn = new DistinguishedName(new DN(dn.getDN().toString()));
    logger.debug("In bind");
    SearchInterceptorChain schain = chain.createSearchChain();
    ArrayList<Attribute> searchattrs = new ArrayList<Attribute>();
    // searchattrs.add(new Attribute(this.attribute));
    logger.debug("searching...");
    Results res = new Results(chain.getInterceptors(), chain.getPos());
    logger.debug("Created res");
    schain.nextSearch(localdn, new Int(0), new Filter("(objectClass=*)"), searchattrs, new Bool(false), res, new LDAPSearchConstraints());
    logger.debug("ran search");
    res.start();
    logger.debug("res started");
    if (!res.hasMore()) {
        logger.debug("user not found");
        throw new LDAPException("Could not find " + localdn.getDN().toString(), LDAPException.NO_SUCH_OBJECT, "Could not find " + localdn.getDN().toString());
    }
    logger.debug("user found");
    LDAPEntry entry = res.next().getEntry();
    LDAPAttribute key = entry.getAttribute(this.attribute);
    if (key == null) {
        logger.debug("No key");
        throw new LDAPException("Invalid Credentials", LDAPException.NO_SUCH_OBJECT, "Invalid Credentials");
    }
    try {
        String keyjson = key.getStringValue();
        if (logger.isDebugEnabled())
            logger.debug("token json : '" + keyjson + "'");
        Gson gson = new Gson();
        Token token = gson.fromJson(new String(Base64.decode(keyjson)), 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.encyrptionKey), spec);
        byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
        String totpJson = new String(cipher.doFinal(encBytes));
        if (logger.isDebugEnabled())
            logger.debug("totp json : '" + totpJson + "'");
        TOTPKey totp = gson.fromJson(totpJson, TOTPKey.class);
        GoogleAuthenticatorConfigBuilder b = new GoogleAuthenticatorConfigBuilder();
        b.setWindowSize(this.window);
        GoogleAuthenticatorConfig cfg = b.build();
        GoogleAuthenticator ga = new GoogleAuthenticator(cfg);
        String spwd = new String(pwd.getValue());
        if (spwd.indexOf(':') == -1) {
            logger.debug("no colon");
            throw new LDAPException("Invalid credentials", LDAPException.INVALID_CREDENTIALS, "Invalid Credentials");
        }
        String scode = spwd.substring(spwd.indexOf(':') + 1);
        int code = Integer.parseInt(scode);
        if (!ga.authorize(totp.getSecretKey(), code)) {
            logger.debug("Verify failed");
            throw new LDAPException("Invalid credentials", LDAPException.INVALID_CREDENTIALS, "Invalid Credentials");
        }
        logger.debug("verify succeeded");
        pwd.setValue(spwd.substring(0, spwd.indexOf(':')).getBytes("UTF-8"));
        chain.nextBind(dn, pwd, constraints);
    } catch (Exception e) {
        logger.error("Could not work", e);
        if (e instanceof LDAPException) {
            throw ((LDAPException) e);
        } else {
            throw new LDAPException("Could not decrypt key", LDAPException.OPERATIONS_ERROR, "Could not decrypt key", e);
        }
    }
}
Also used : LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(net.sourceforge.myvd.types.Attribute) LDAPSearchConstraints(com.novell.ldap.LDAPSearchConstraints) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) DN(com.novell.ldap.util.DN) Token(com.tremolosecurity.json.Token) Int(net.sourceforge.myvd.types.Int) LDAPEntry(com.novell.ldap.LDAPEntry) Bool(net.sourceforge.myvd.types.Bool) SearchInterceptorChain(net.sourceforge.myvd.chain.SearchInterceptorChain) LDAPAttribute(com.novell.ldap.LDAPAttribute) GoogleAuthenticator(com.warrenstrange.googleauth.GoogleAuthenticator) DistinguishedName(net.sourceforge.myvd.types.DistinguishedName) GoogleAuthenticatorConfig(com.warrenstrange.googleauth.GoogleAuthenticatorConfig) GoogleAuthenticatorConfigBuilder(com.warrenstrange.googleauth.GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder) LDAPException(com.novell.ldap.LDAPException) LDAPException(com.novell.ldap.LDAPException) Results(net.sourceforge.myvd.types.Results) Filter(net.sourceforge.myvd.types.Filter) TOTPKey(com.tremolosecurity.proxy.auth.otp.TOTPKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 9 with Token

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

the class OpenUnisonUtils method main.

public static void main(String[] args) throws Exception {
    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());
    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true, "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");
    options.addOption("approvalId", true, "The approval id to act on");
    options.addOption("exportFile", true, "Path to export the workflow to");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);
    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }
    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);
    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }
    logger.info("Configuration loaded");
    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);
    KeyStore ks = loadKeyStore(ksPath, ttRead);
    logger.info("...loaded");
    if (action.equalsIgnoreCase("import-sp-metadata")) {
        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");
        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);
        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");
        String backupFileName = unisonXMLFile + ".bak";
        logger.info("Backing up to '" + backupFileName + "'");
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();
    } else if (action.equalsIgnoreCase("exportApprovalWorkflow")) {
        logger.info("Exporting approval");
        String approvalIdParam = loadOption(cmd, "approvalId", options);
        int approvalId = Integer.parseInt(approvalIdParam);
        logger.info("Exporting approval id : " + approvalId);
        Class.forName(ttRead.getProvisioning().getApprovalDB().getDriver());
        logger.info("Connecting to the database...");
        Connection con = DriverManager.getConnection(ttRead.getProvisioning().getApprovalDB().getUrl(), ttRead.getProvisioning().getApprovalDB().getUser(), ttRead.getProvisioning().getApprovalDB().getPassword());
        logger.info("...connected");
        String decryptionKeyName = ttRead.getProvisioning().getApprovalDB().getEncryptionKey();
        PreparedStatement ps = con.prepareStatement("SELECT workflowObj FROM approvals WHERE id=?");
        ps.setInt(1, approvalId);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            logger.error("No approval id : " + approvalId);
        }
        String json = rs.getString("workflowObj");
        Gson gson = new Gson();
        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, ks.getKey(ttRead.getProvisioning().getApprovalDB().getEncryptionKey(), ttRead.getKeyStorePassword().toCharArray()), spec);
        byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
        String jsonDecr = new String(cipher.doFinal(encBytes));
        // logger.info(jsonDecr);
        String exportPath = loadOption(cmd, "exportFile", options);
        logger.info("Writing decrypted object to " + exportPath);
        FileOutputStream fos = new FileOutputStream(exportPath);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
        out.write(jsonDecr);
        out.flush();
        out.close();
        logger.info("Shutting down connection");
        con.close();
    }
}
Also used : Options(org.apache.commons.cli.Options) TremoloType(com.tremolosecurity.config.xml.TremoloType) Gson(com.google.gson.Gson) Token(com.tremolosecurity.json.Token) BufferedWriter(java.io.BufferedWriter) HelpFormatter(org.apache.commons.cli.HelpFormatter) ResultSet(java.sql.ResultSet) CommandLineParser(org.apache.commons.cli.CommandLineParser) KeyGenerator(javax.crypto.KeyGenerator) DefaultParser(org.apache.commons.cli.DefaultParser) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) PrintWriter(java.io.PrintWriter) InputStreamReader(java.io.InputStreamReader) Connection(java.sql.Connection) SecureRandom(java.security.SecureRandom) PreparedStatement(java.sql.PreparedStatement) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) CommandLine(org.apache.commons.cli.CommandLine) SecretKey(javax.crypto.SecretKey) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) IvParameterSpec(javax.crypto.spec.IvParameterSpec) OutputStreamWriter(java.io.OutputStreamWriter) Cipher(javax.crypto.Cipher)

Example 10 with Token

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

the class ServiceActions method loadApprovalDetails.

public static ApprovalDetails loadApprovalDetails(String approver, int approvalID) throws ProvisioningException {
    Session session = null;
    Gson gson = new Gson();
    try {
        session = GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getHibernateSessionFactory().openSession();
        Query query = session.createQuery("SELECT apprv FROM Approvals apprv JOIN apprv.allowedApproverses allowed JOIN allowed.approvers approver WHERE apprv.id = :approval_id AND approver.userKey = :approver_id");
        query.setParameter("approval_id", approvalID);
        query.setParameter("approver_id", approver);
        List<com.tremolosecurity.provisioning.objects.Approvals> approvals = query.list();
        if (approvals.isEmpty()) {
            throw new ServletException("no approval found");
        }
        Approvals approval = approvals.get(0);
        ApprovalDetails sum = new ApprovalDetails();
        sum.setApproval(approval.getId());
        sum.setWorkflow(approval.getWorkflow().getId());
        sum.setLabel(approval.getLabel());
        sum.setUser(approval.getWorkflow().getUsers().getUserKey());
        sum.setWfStart(approval.getWorkflow().getStartTs().getTime());
        sum.setApprovalStart(approval.getCreateTs().getTime());
        sum.setReason(approval.getWorkflow().getRequestReason());
        String json = approval.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, GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getApprovalDB().getEncryptionKey()), spec);
        byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
        json = new String(cipher.doFinal(encBytes));
        Workflow wf = (Workflow) JsonReader.jsonToJava(json);
        sum.setUserObj(wf.getUser());
        String wfName = approval.getWorkflow().getName();
        sum.setWfName(wfName);
        sum.setWfLabel(approval.getWorkflow().getLabel());
        sum.setWfDescription(approval.getWorkflow().getDescription());
        return sum;
    } catch (Throwable t) {
        throw new ProvisioningException("Could not load approval", t);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
Also used : Query(org.hibernate.Query) Gson(com.google.gson.Gson) Approvals(com.tremolosecurity.provisioning.objects.Approvals) Workflow(com.tremolosecurity.provisioning.core.Workflow) Token(com.tremolosecurity.json.Token) ServletException(javax.servlet.ServletException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) Session(org.hibernate.Session)

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