Search in sources :

Example 1 with QueueConfigType

use of com.tremolosecurity.config.xml.QueueConfigType 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 2 with QueueConfigType

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

the class ForRemoval method loadUnisonConfiguration.

@Override
public JAXBElement<TremoloType> loadUnisonConfiguration(Unmarshaller unmarshaller) throws Exception {
    InputStream in;
    if (configXML.startsWith("WEB-INF")) {
        in = new ByteArrayInputStream(OpenUnisonConfigLoader.generateOpenUnisonConfig(ctx.getRealPath("/" + configXML)).getBytes("UTF-8"));
    } else {
        in = new ByteArrayInputStream(OpenUnisonConfigLoader.generateOpenUnisonConfig(configXML).getBytes("UTF-8"));
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder loader = factory.newDocumentBuilder();
    Document document = loader.parse(in);
    DocumentTraversal traversal = (DocumentTraversal) document;
    TreeWalker walker = traversal.createTreeWalker(document.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
    traverseLevel(walker, "");
    StringWriter writer = new StringWriter();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    transformer = tf.newTransformer();
    transformer.transform(new DOMSource(document), new StreamResult(writer));
    String xmlString = writer.getBuffer().toString();
    ByteArrayInputStream bais = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
    Object obj = unmarshaller.unmarshal(bais);
    JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
    this.unisonConfig = cfg.getValue();
    QueueConfigType qct = (QueueConfigType) GlobalEntries.getGlobalEntries().get("openunison.queueconfig");
    if (qct != null) {
        logger.info("Overriding Queue Configuration");
        if (cfg.getValue().getProvisioning() == null) {
            cfg.getValue().setProvisioning(new ProvisioningType());
        }
        cfg.getValue().getProvisioning().setQueueConfig(qct);
    }
    return cfg;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TremoloType(com.tremolosecurity.config.xml.TremoloType) QueueConfigType(com.tremolosecurity.config.xml.QueueConfigType) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) TreeWalker(org.w3c.dom.traversal.TreeWalker) JAXBElement(javax.xml.bind.JAXBElement) Document(org.w3c.dom.Document) ProvisioningType(com.tremolosecurity.config.xml.ProvisioningType) StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DocumentTraversal(org.w3c.dom.traversal.DocumentTraversal)

Aggregations

QueueConfigType (com.tremolosecurity.config.xml.QueueConfigType)2 TremoloType (com.tremolosecurity.config.xml.TremoloType)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 FileInputStream (java.io.FileInputStream)2 JAXBElement (javax.xml.bind.JAXBElement)2 GsonBuilder (com.google.gson.GsonBuilder)1 ParamType (com.tremolosecurity.config.xml.ParamType)1 ProvisioningType (com.tremolosecurity.config.xml.ProvisioningType)1 Builder (io.undertow.Undertow.Builder)1 HackInstanceManager (io.undertow.jsp.HackInstanceManager)1 JspServletBuilder (io.undertow.jsp.JspServletBuilder)1 PathHandler (io.undertow.server.handlers.PathHandler)1 RedirectHandler (io.undertow.server.handlers.RedirectHandler)1 FileResourceManager (io.undertow.server.handlers.resource.FileResourceManager)1 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)1 DeploymentManager (io.undertow.servlet.api.DeploymentManager)1 ErrorPage (io.undertow.servlet.api.ErrorPage)1 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1