Search in sources :

Example 1 with TremoloType

use of com.tremolosecurity.config.xml.TremoloType in project OpenUnison by TremoloSecurity.

the class OpenUnisonUtils method storeMethod.

private static void storeMethod(String unisonXMLFile, TremoloType tt, String ksPath, KeyStore ks) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, JAXBException, PropertyException {
    logger.info("Storing the keystore");
    ks.store(new FileOutputStream(ksPath), tt.getKeyStorePassword().toCharArray());
    logger.info("Saving the unison xml file");
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    OutputStream os = new FileOutputStream(unisonXMLFile);
    JAXBElement<TremoloType> root = new JAXBElement<TremoloType>(new QName("http://www.tremolosecurity.com/tremoloConfig", "tremoloConfig", "tns"), TremoloType.class, tt);
    marshaller.marshal(root, os);
    os.flush();
    os.close();
}
Also used : AuthnRequestMarshaller(org.opensaml.saml.saml2.core.impl.AuthnRequestMarshaller) EntityDescriptorMarshaller(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller) Marshaller(javax.xml.bind.Marshaller) TremoloType(com.tremolosecurity.config.xml.TremoloType) QName(javax.xml.namespace.QName) FileOutputStream(java.io.FileOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) JAXBContext(javax.xml.bind.JAXBContext) JAXBElement(javax.xml.bind.JAXBElement)

Example 2 with TremoloType

use of com.tremolosecurity.config.xml.TremoloType in project OpenUnison by TremoloSecurity.

the class OpenUnisonUtils method loadTremoloType.

private static TremoloType loadTremoloType(String unisonXMLFile, CommandLine cmd, Options options) throws Exception {
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    InputStream in = null;
    String envFile = cmd.getOptionValue("envFile");
    if (envFile != null) {
        BufferedReader fin = new BufferedReader(new InputStreamReader(new FileInputStream(envFile)));
        String line = null;
        while ((line = fin.readLine()) != null) {
            String name = line.substring(0, line.indexOf('='));
            String val = line.substring(line.indexOf('=') + 1);
            System.setProperty(name, val);
        }
        String withProps = OpenUnisonConfigLoader.generateOpenUnisonConfig(unisonXMLFile);
        in = new ByteArrayInputStream(withProps.getBytes("UTF-8"));
    } else {
        in = new FileInputStream(unisonXMLFile);
    }
    Object obj = unmarshaller.unmarshal(in);
    JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
    return cfg.getValue();
}
Also used : InputStreamReader(java.io.InputStreamReader) TremoloType(com.tremolosecurity.config.xml.TremoloType) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) JAXBContext(javax.xml.bind.JAXBContext) JAXBElement(javax.xml.bind.JAXBElement) Unmarshaller(javax.xml.bind.Unmarshaller) FileInputStream(java.io.FileInputStream)

Example 3 with TremoloType

use of com.tremolosecurity.config.xml.TremoloType in project OpenUnison by TremoloSecurity.

the class OpenUnisonUtils method loadTremoloType.

private static TremoloType loadTremoloType(String unisonXMLFile) throws Exception {
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    FileInputStream in = new FileInputStream(unisonXMLFile);
    Object obj = unmarshaller.unmarshal(in);
    JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
    return cfg.getValue();
}
Also used : TremoloType(com.tremolosecurity.config.xml.TremoloType) JAXBContext(javax.xml.bind.JAXBContext) JAXBElement(javax.xml.bind.JAXBElement) Unmarshaller(javax.xml.bind.Unmarshaller) FileInputStream(java.io.FileInputStream)

Example 4 with TremoloType

use of com.tremolosecurity.config.xml.TremoloType in project OpenUnison by TremoloSecurity.

the class OpenUnisonOnUndertow method main.

public static void main(String[] args) throws Exception {
    OpenUnisonConfig config = null;
    logger.info("Starting OpenUnison on Undertow " + OpenUnisonServletFilter.version);
    if (args.length == 0) {
        logger.error("One argument required, path to yaml or json config");
        System.exit(1);
    } else if (args[0].endsWith(".yaml")) {
        logger.info("Parsing YAML : '" + args[0] + "'");
        Yaml yaml = new Yaml();
        Map<String, Object> map = (Map<String, Object>) yaml.load(new FileInputStream(args[0]));
        JSONObject jsonObject = new JSONObject(map);
        String json = jsonObject.toJSONString();
        config = gson.fromJson(json, OpenUnisonConfig.class);
    } else {
        logger.info("Parsing JSON : '" + args[0] + "'");
        config = gson.fromJson(new InputStreamReader(new FileInputStream(args[0])), OpenUnisonConfig.class);
    }
    final OpenUnisonConfig fconfig = config;
    if (config.getContextRoot() == null) {
        config.setContextRoot("/");
    }
    logger.info("Config Open Port : '" + config.getOpenPort() + "'");
    logger.info("Disable HTTP2 : '" + config.isDisableHttp2() + "'");
    logger.info("Allow unescaped characters : '" + config.isAllowUnEscapedChars() + "'");
    logger.info("Config Open External Port : '" + config.getOpenExternalPort() + "'");
    logger.info("Config Secure Port : '" + config.getSecurePort() + "'");
    logger.info("Config Secure External Port : '" + config.getSecureExternalPort() + "'");
    logger.info("Config Context Root :  '" + config.getContextRoot() + "'");
    logger.info("Force to Secure : '" + config.isForceToSecure() + "'");
    logger.info("ActiveMQ Directory : '" + config.getActivemqDir() + "'");
    logger.info("Quartz Directory : '" + config.getQuartzDir() + "'");
    logger.info("Config TLS Client Auth Mode : '" + config.getClientAuth() + "'");
    logger.info("Config TLS Allowed Client Subjects : '" + config.getAllowedClientNames() + "'");
    logger.info("Config TLS Protocols : '" + config.getAllowedTlsProtocols() + "'");
    logger.info("Config TLS Ciphers : '" + config.getCiphers() + "'");
    logger.info("Config Path to Deployment : '" + config.getPathToDeployment() + "'");
    logger.info("Config Path to Environment File : '" + config.getPathToEnvFile() + "'");
    logger.info("Redirect to contex root : '" + config.isRedirectToContextRoot() + "'");
    logger.info("Support socket shutdown : " + config.isSocketShutdownListener());
    if (config.isSocketShutdownListener()) {
        logger.info("Socket shutdown host : '" + config.getSocketShutdownHost() + "'");
        logger.info("Socket shutdown port : '" + config.getSocketShutdownPort() + "'");
        logger.info("Socket shutdown command : '" + config.getSocketShutdownCommand() + "'");
    }
    logger.info("Override Queue Configuration : '" + config.getQueueConfiguration() != null + "'");
    logger.info("Creating unisonServiceProps");
    File f = File.createTempFile("unisonService", "props");
    logger.info("Temporary unisonServiceProps : '" + f.getAbsolutePath() + "'");
    Properties unisonServiceProps = new Properties();
    unisonServiceProps.put("com.tremolosecurity.openunison.forceToSSL", Boolean.toString(config.isForceToSecure()));
    unisonServiceProps.put("com.tremolosecurity.openunison.openPort", Integer.toString(config.getOpenPort()));
    unisonServiceProps.put("com.tremolosecurity.openunison.securePort", Integer.toString(config.getSecurePort()));
    unisonServiceProps.put("com.tremolosecurity.openunison.externalOpenPort", Integer.toString(config.getOpenExternalPort()));
    unisonServiceProps.put("com.tremolosecurity.openunison.externalSecurePort", Integer.toString(config.getSecureExternalPort()));
    if (config.getActivemqDir() != null) {
        unisonServiceProps.put("com.tremolosecurity.openunison.activemqdir", config.getActivemqDir());
    }
    if (config.getQuartzDir() != null) {
        unisonServiceProps.put("com.tremolosecurity.openunison.quartzdir", config.getQuartzDir());
    }
    unisonServiceProps.store(new FileOutputStream(f), "OpenUnison Configuration");
    System.getProperties().put("com.tremolosecurity.unison.unisonServicePropsPath", f.getAbsolutePath());
    System.getProperties().put("com.tremolosecurity.unison.unisonXML", config.getPathToDeployment() + "/webapp/WEB-INF/unison.xml");
    logger.info("Loading environment file : '" + config.getPathToEnvFile() + "'");
    Properties env = new Properties();
    env.load(new FileInputStream(config.getPathToEnvFile()));
    for (Object name : env.keySet()) {
        logger.info("Adding property : '" + name + "'");
        System.setProperty((String) name, env.getProperty((String) name));
    }
    if (config.getQueueConfiguration() != null) {
        QueueConfigType qc = new QueueConfigType();
        qc.setConnectionFactory(config.getQueueConfiguration().getConnectionFactory());
        qc.setEncryptionKeyName(config.getQueueConfiguration().getEncryptionKeyName());
        qc.setIsUseInternalQueue(config.getQueueConfiguration().isUseInternalQueue());
        qc.setKeepAliveMillis(config.getQueueConfiguration().getKeepAliveMillis());
        qc.setMaxConsumers(((Long) config.getQueueConfiguration().getMaxConsumers()).intValue());
        qc.setMaxProducers(((Long) config.getQueueConfiguration().getMaxProducers()).intValue());
        qc.setMaxSessionsPerConnection(((Long) config.getQueueConfiguration().getMaxSessionsPerConnection()).intValue());
        qc.setMultiTaskQueues(config.getQueueConfiguration().isMultiTaskQueues());
        qc.setNumQueues(((Long) config.getQueueConfiguration().getNumQueues()).intValue());
        qc.setSmtpQueueName(config.getQueueConfiguration().getSmtpQueueName());
        qc.setTaskQueueName(config.getQueueConfiguration().getTaskQueueName());
        for (QueueConfigParam param : config.getQueueConfiguration().getParams()) {
            ParamType pt = new ParamType();
            pt.setName(param.getName());
            if (param.getSourceType().equalsIgnoreCase("static")) {
                pt.setValue(param.getValue());
            } else {
                pt.setValue(System.getProperty(param.getValue()));
            }
            qc.getParam().add(pt);
        }
        GlobalEntries.getGlobalEntries().set("openunison.queueconfig", qc);
    }
    logger.info("Loading keystore for Undertow");
    String unisonXML = config.getPathToDeployment() + "/webapp/WEB-INF/unison.xml";
    logger.info("OpenUnison XML File : '" + unisonXML + "'");
    String unisonXMLContent = OpenUnisonConfigLoader.generateOpenUnisonConfig(unisonXML);
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Object obj = unmarshaller.unmarshal(new ByteArrayInputStream(unisonXMLContent.getBytes("UTF-8")));
    JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
    TremoloType unisonConfiguration = cfg.getValue();
    logger.info("Loading keystore : '" + unisonConfiguration.getKeyStorePath() + "'");
    logger.info("Building Undertow");
    Builder buildUndertow = Undertow.builder();
    buildUndertow.setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, 60000);
    logger.info("Check if enabling HTTP2 - " + config.isDisableHttp2());
    if (!config.isDisableHttp2()) {
        logger.info("Enabling HTTP2");
        buildUndertow.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
    }
    if (config.getOpenPort() > 0) {
        buildUndertow.addHttpListener(config.getOpenPort(), "0.0.0.0");
        logger.info("Adding open port : '" + config.getOpenPort() + "'");
    }
    if (config.getSecurePort() > 0) {
        setupTlsListener(config, unisonConfiguration, buildUndertow);
    }
    File pathToWebApp = new File(config.getPathToDeployment() + "/webapp");
    logger.info("Path to webapp : '" + pathToWebApp.getAbsolutePath() + "'");
    logger.info("Path directory? : '" + pathToWebApp.isDirectory() + "'");
    logger.info("Path exists : '" + pathToWebApp.exists() + "'");
    DeploymentInfo servletBuilder = Servlets.deployment().setClassLoader(OpenUnisonOnUndertow.class.getClassLoader()).setEagerFilterInit(true).setContextPath(config.getContextRoot()).setDeploymentName("openunison").addFilter(Servlets.filter("openunison", com.tremolosecurity.openunison.OpenUnisonServletFilter.class).addInitParam("mode", "appliance")).addFilterUrlMapping("openunison", "/*", DispatcherType.REQUEST).setResourceManager(new FileResourceManager(pathToWebApp, 1024, true, true)).addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp")).addServlet(Servlets.servlet("identityProvider", com.tremolosecurity.idp.server.IDP.class).addMapping("/auth/idp/*"));
    if (config.getWelcomePages() != null) {
        servletBuilder.addWelcomePages(config.getWelcomePages());
    }
    if (config.getErrorPages() != null) {
        logger.info("Adding error pages");
        ArrayList<ErrorPage> errorPages = new ArrayList<ErrorPage>();
        for (ErrorPageConfig ep : config.getErrorPages()) {
            if (ep.getCode() == 0) {
                logger.info("Adding default page: " + ep.getLocation());
                errorPages.add(new ErrorPage(ep.getLocation()));
            } else {
                logger.info("Adding page for " + ep.getCode() + " : " + ep.getLocation());
                errorPages.add(new ErrorPage(ep.getLocation(), ep.getCode()));
            }
        }
        servletBuilder.addErrorPages(errorPages);
    }
    JspServletBuilder.setupDeployment(servletBuilder, new HashMap<String, JspPropertyGroup>(), new HashMap<String, TagLibraryInfo>(), new HackInstanceManager());
    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    PathHandler path = Handlers.path(Handlers.redirect(config.getContextRoot())).addPrefixPath(config.getContextRoot(), manager.start());
    if (config.isForceToLowerCase()) {
        buildUndertow.setHandler(new OpenUnisonPathHandler(path));
    } else {
        buildUndertow.setHandler(path);
    }
    if (!config.getContextRoot().equals("/")) {
        if (!config.isRedirectToContextRoot()) {
            logger.info("Not redirecting to context");
            servletBuilder = Servlets.deployment().setClassLoader(OpenUnisonOnUndertow.class.getClassLoader()).setEagerFilterInit(true).setContextPath("/").setDeploymentName("root");
            manager = Servlets.defaultContainer().addDeployment(servletBuilder);
            manager.deploy();
            path.addPrefixPath("/", manager.start());
        } else {
            logger.info("Redirecting to context");
            path.addPrefixPath("/", new RedirectHandler(config.getContextRoot()));
        }
    }
    if (config.isAllowUnEscapedChars()) {
        buildUndertow.setServerOption(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, true);
    }
    undertow = buildUndertow.build();
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            logger.info("Shutting down");
            undertow.stop();
            GlobalEntries.getGlobalEntries().getConfigManager().clearThreads();
            if (myvd != null) {
                try {
                    myvd.shutdown();
                } catch (Exception e) {
                    logger.warn("Did not gracefullt stop directory service", e);
                }
            }
        }
    });
    if (config.isSocketShutdownListener()) {
        new Thread() {

            public void run() {
                logger.info("Starting shutdown socket listener");
                try {
                    ServerSocket socket = new ServerSocket(fconfig.getSocketShutdownPort(), 0, InetAddress.getByName(fconfig.getSocketShutdownHost()));
                    while (true) {
                        logger.info("shutdown waiting for input");
                        Socket clientSocket = null;
                        try {
                            clientSocket = socket.accept();
                        } catch (Throwable t) {
                            logger.warn("Could not accept connection", t);
                            continue;
                        }
                        logger.info("request received");
                        // PrintWriter out =
                        // new PrintWriter(clientSocket.getOutputStream(), true);
                        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        logger.info("reading data");
                        String command = in.readLine();
                        logger.info("'" + command + "'");
                        if (command != null) {
                            command.trim();
                        }
                        logger.info("'" + command + "'");
                        if (fconfig.getSocketShutdownCommand().equalsIgnoreCase(command)) {
                            logger.info("Stopping threads");
                            GlobalEntries.getGlobalEntries().getConfigManager().clearThreads();
                            logger.info("Shutting down undertow");
                            undertow.stop();
                            if (myvd != null) {
                                try {
                                    myvd.shutdown();
                                } catch (Exception e) {
                                    logger.warn("Did not gracefullt stop directory service", e);
                                }
                            }
                            logger.info("Closing input stream");
                            try {
                                in.close();
                            } catch (Throwable t) {
                            }
                            /*try {
									out.close();
								} catch (Throwable t) {}*/
                            logger.info("Closing client socket");
                            try {
                                clientSocket.close();
                            } catch (Throwable t) {
                            }
                            logger.info("Closing server socket");
                            try {
                                socket.close();
                            } catch (Throwable t) {
                            }
                            logger.info("Sleeping for 10 seconds");
                            try {
                                Thread.sleep(10000);
                                logger.info("Exiting");
                                System.exit(0);
                                return;
                            } catch (Exception e) {
                            }
                        } else {
                            command = null;
                            logger.info("invalid command");
                            try {
                                in.close();
                            } catch (Throwable t) {
                            }
                            /*try {
									out.close();
								} catch (Throwable t) {}
*/
                            try {
                                clientSocket.close();
                            } catch (Throwable t) {
                            }
                        }
                    }
                } catch (IOException e) {
                    logger.error("Could not start shutdown listener", e);
                }
            }
        }.start();
    }
    undertow.start();
    if (config.getLdapPort() != 0 || config.getLdapsPort() != 0) {
        myvd = (MyVDWrapper) Class.forName("com.tremolosecurity.openunison.myvd.MyVDOnUndertow").newInstance();
        myvd.startMyVD(config, unisonConfiguration);
    }
}
Also used : ErrorPage(io.undertow.servlet.api.ErrorPage) TremoloType(com.tremolosecurity.config.xml.TremoloType) DeploymentManager(io.undertow.servlet.api.DeploymentManager) RedirectHandler(io.undertow.server.handlers.RedirectHandler) JspServletBuilder(io.undertow.jsp.JspServletBuilder) GsonBuilder(com.google.gson.GsonBuilder) Builder(io.undertow.Undertow.Builder) ArrayList(java.util.ArrayList) PathHandler(io.undertow.server.handlers.PathHandler) JAXBContext(javax.xml.bind.JAXBContext) Properties(java.util.Properties) HackInstanceManager(io.undertow.jsp.HackInstanceManager) JspPropertyGroup(org.apache.jasper.deploy.JspPropertyGroup) FileResourceManager(io.undertow.server.handlers.resource.FileResourceManager) Unmarshaller(javax.xml.bind.Unmarshaller) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) TagLibraryInfo(org.apache.jasper.deploy.TagLibraryInfo) InputStreamReader(java.io.InputStreamReader) QueueConfigType(com.tremolosecurity.config.xml.QueueConfigType) ServerSocket(java.net.ServerSocket) JAXBElement(javax.xml.bind.JAXBElement) IOException(java.io.IOException) Yaml(org.yaml.snakeyaml.Yaml) FileInputStream(java.io.FileInputStream) ParamType(com.tremolosecurity.config.xml.ParamType) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) JSONObject(org.json.simple.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) JSONObject(org.json.simple.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket)

Example 5 with TremoloType

use of com.tremolosecurity.config.xml.TremoloType 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)

Aggregations

TremoloType (com.tremolosecurity.config.xml.TremoloType)7 FileInputStream (java.io.FileInputStream)5 JAXBContext (javax.xml.bind.JAXBContext)5 JAXBElement (javax.xml.bind.JAXBElement)5 Unmarshaller (javax.xml.bind.Unmarshaller)4 BufferedReader (java.io.BufferedReader)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileOutputStream (java.io.FileOutputStream)3 InputStreamReader (java.io.InputStreamReader)3 ParamType (com.tremolosecurity.config.xml.ParamType)2 QueueConfigType (com.tremolosecurity.config.xml.QueueConfigType)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 ApplicationType (com.tremolosecurity.config.xml.ApplicationType)1 ErrorPage (com.tremolosecurity.config.xml.ApplicationsType.ErrorPage)1 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)1 AuthMechParamType (com.tremolosecurity.config.xml.AuthMechParamType)1 CustomAzRuleType (com.tremolosecurity.config.xml.CustomAzRuleType)1