Search in sources :

Example 16 with ConstraintMapping

use of org.eclipse.jetty.security.ConstraintMapping in project tycho by eclipse.

the class HttpServer method doStartServer.

private static HttpServer doStartServer(String username, String password, int port) throws Exception {
    Server server = new Server();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);
    Connector connector = new SocketConnector();
    connector.setPort(port);
    server.addConnector(connector);
    if (username != null) {
        HashLoginService userRealm = new HashLoginService("default");
        userRealm.putUser(username, new Password(password), new String[] { Constraint.ANY_ROLE });
        Constraint constraint = new Constraint("default", Constraint.ANY_ROLE);
        constraint.setAuthenticate(true);
        ConstraintMapping constraintMapping = new ConstraintMapping();
        constraintMapping.setPathSpec("/*");
        constraintMapping.setConstraint(constraint);
        ConstraintSecurityHandler securedHandler = new ConstraintSecurityHandler();
        securedHandler.setAuthenticator(new BasicAuthenticator());
        securedHandler.addConstraintMapping(constraintMapping);
        securedHandler.setLoginService(userRealm);
        // chain handlers together
        securedHandler.setHandler(contexts);
        server.setHandler(securedHandler);
    }
    server.start();
    return new HttpServer(port, server, contexts);
}
Also used : SocketConnector(org.eclipse.jetty.server.bio.SocketConnector) Connector(org.eclipse.jetty.server.Connector) HashLoginService(org.eclipse.jetty.security.HashLoginService) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Server(org.eclipse.jetty.server.Server) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) Constraint(org.eclipse.jetty.util.security.Constraint) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) SocketConnector(org.eclipse.jetty.server.bio.SocketConnector) Password(org.eclipse.jetty.util.security.Password)

Example 17 with ConstraintMapping

use of org.eclipse.jetty.security.ConstraintMapping in project CCDD by nasa.

the class CcddWebServer method createServer.

/**
 ********************************************************************************************
 * Create the web server
 ********************************************************************************************
 */
private void createServer() {
    try {
        // Create the web server using the currently specified port
        server = new Server(Integer.valueOf(ccddMain.getProgPrefs().get(WEB_SERVER_PORT, DEFAULT_WEB_SERVER_PORT)));
        // Stop the web server when the application exits
        server.setStopAtShutdown(true);
        // Create the login service
        HashLoginService loginService = new HashLoginService("CCDDRealm") {

            /**
             ********************************************************************************
             * Override the login method so that the supplied user name and password can be
             * authenticated by the PostgreSQL server
             ********************************************************************************
             */
            @Override
            public UserIdentity login(String user, Object password) {
                UserIdentity identity = null;
                try {
                    // Convert the password object to a string
                    String passwordS = password.toString();
                    // the user+password is authenticated initially
                    if (validUser == null || !validUser.equals(user) || !validPassword.equals(passwordS)) {
                        // Attempt to connect to the database using the supplied user and
                        // password
                        DriverManager.getConnection(dbControl.getDatabaseURL(dbControl.getDatabaseName()), user, passwordS);
                        // Store the authenticated user and password for future login requests
                        validUser = user;
                        validPassword = passwordS;
                    }
                    // User+password combination is valid, so set the user identity using the
                    // generic login credentials
                    identity = super.login("valid", "valid");
                } catch (SQLException se) {
                    validUser = null;
                    validPassword = null;
                    // The supplied user+password combination is not valid; set the user
                    // identity using invalid credentials so that the request is rejected
                    identity = super.login("invalid", "invalid");
                }
                return identity;
            }
        };
        // Create the user credentials that are used by the login service if the user's
        // PostgreSQL credentials are authenticated
        loginService.putUser("valid", Credential.getCredential("valid"), new String[] { "user" });
        server.addBean(loginService);
        // Set the security handler that secures content behind a particular portion of a URL
        // space
        ConstraintSecurityHandler security = new ConstraintSecurityHandler();
        server.setHandler(security);
        // Set a constraint that requires authentication and in addition that an authenticated
        // user be a member of a given set of roles for authorization purposes
        Constraint constraint = new Constraint();
        constraint.setName("auth");
        constraint.setAuthenticate(true);
        constraint.setRoles(new String[] { "user" });
        // Bind the URL pattern with the previously created constraint.
        ConstraintMapping mapping = new ConstraintMapping();
        mapping.setPathSpec("/*");
        mapping.setConstraint(constraint);
        // Apply the constraint mapping to the handler, set an authenticator to check the
        // user's credentials, and set the login service which contains the single valid user
        security.setConstraintMappings(Collections.singletonList(mapping));
        security.setAuthenticator(new BasicAuthenticator());
        security.setLoginService(loginService);
        // Create the web server request access handler
        accessHandler = new CcddWebDataAccessHandler(ccddMain);
        security.setHandler(accessHandler);
    } catch (Exception e) {
        // Inform the user that creating the web server failed
        eventLog.logFailEvent(ccddMain.getMainFrame(), "Web Server Error", "Cannot create web server; cause '" + e.getMessage() + "'", "<html><b>Cannot create web server");
    }
}
Also used : HashLoginService(org.eclipse.jetty.security.HashLoginService) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Server(org.eclipse.jetty.server.Server) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) SQLException(java.sql.SQLException) Constraint(org.eclipse.jetty.util.security.Constraint) UserIdentity(org.eclipse.jetty.server.UserIdentity) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) SQLException(java.sql.SQLException)

Example 18 with ConstraintMapping

use of org.eclipse.jetty.security.ConstraintMapping in project symmetric-ds by JumpMind.

the class SymmetricWebServer method setupBasicAuthIfNeeded.

protected void setupBasicAuthIfNeeded(Server server) {
    if (StringUtils.isNotBlank(basicAuthUsername)) {
        ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
        Constraint constraint = new Constraint();
        constraint.setName(Constraint.__BASIC_AUTH);
        constraint.setRoles(new String[] { SecurityConstants.EMBEDDED_WEBSERVER_DEFAULT_ROLE });
        constraint.setAuthenticate(true);
        ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec("/*");
        // sh.setConstraintMappings(new ConstraintMapping[] {cm});
        sh.addConstraintMapping(cm);
        sh.setAuthenticator(new BasicAuthenticator());
        HashLoginService loginService = new HashLoginService();
        loginService.putUser(basicAuthUsername, new Password(basicAuthPassword), null);
        sh.setLoginService(loginService);
        server.setHandler(sh);
    }
}
Also used : ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) HashLoginService(org.eclipse.jetty.security.HashLoginService) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) Constraint(org.eclipse.jetty.util.security.Constraint) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) Password(org.eclipse.jetty.util.security.Password)

Example 19 with ConstraintMapping

use of org.eclipse.jetty.security.ConstraintMapping in project gitblit by gitblit.

the class GitBlitServer method start.

/**
 * Start Gitblit GO.
 */
protected final void start(Params params) {
    final File baseFolder = getBaseFolder(params);
    FileSettings settings = params.FILESETTINGS;
    if (!StringUtils.isEmpty(params.settingsfile)) {
        if (new File(params.settingsfile).exists()) {
            settings = new FileSettings(params.settingsfile);
        }
    }
    if (params.dailyLogFile) {
        // Configure log4j for daily log file generation
        InputStream is = null;
        try {
            is = getClass().getResourceAsStream("/log4j.properties");
            Properties loggingProperties = new Properties();
            loggingProperties.load(is);
            loggingProperties.put("log4j.appender.R.File", new File(baseFolder, "logs/gitblit.log").getAbsolutePath());
            loggingProperties.put("log4j.rootCategory", "INFO, R");
            if (settings.getBoolean(Keys.web.debugMode, false)) {
                loggingProperties.put("log4j.logger.com.gitblit", "DEBUG");
            }
            PropertyConfigurator.configure(loggingProperties);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    logger = LoggerFactory.getLogger(GitBlitServer.class);
    logger.info("\n" + Constants.getASCIIArt());
    System.setProperty("java.awt.headless", "true");
    String osname = System.getProperty("os.name");
    String osversion = System.getProperty("os.version");
    logger.info("Running on " + osname + " (" + osversion + ")");
    String javaversion = System.getProperty("java.version");
    String javavendor = System.getProperty("java.vendor");
    logger.info("JVM version " + javaversion + " (" + javavendor + ")");
    QueuedThreadPool threadPool = new QueuedThreadPool();
    int maxThreads = settings.getInteger(Keys.server.threadPoolSize, 50);
    if (maxThreads > 0) {
        threadPool.setMaxThreads(maxThreads);
    }
    Server server = new Server(threadPool);
    server.setStopAtShutdown(true);
    // conditionally configure the https connector
    if (params.securePort > 0) {
        File certificatesConf = new File(baseFolder, X509Utils.CA_CONFIG);
        File serverKeyStore = new File(baseFolder, X509Utils.SERVER_KEY_STORE);
        File serverTrustStore = new File(baseFolder, X509Utils.SERVER_TRUST_STORE);
        File caRevocationList = new File(baseFolder, X509Utils.CA_REVOCATION_LIST);
        // generate CA & web certificates, create certificate stores
        X509Metadata metadata = new X509Metadata("localhost", params.storePassword);
        // set default certificate values from config file
        if (certificatesConf.exists()) {
            FileBasedConfig config = new FileBasedConfig(certificatesConf, FS.detect());
            try {
                config.load();
            } catch (Exception e) {
                logger.error("Error parsing " + certificatesConf, e);
            }
            NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
            certificateConfig.update(metadata);
        }
        metadata.notAfter = new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
        X509Utils.prepareX509Infrastructure(metadata, baseFolder, new X509Log() {

            @Override
            public void log(String message) {
                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new FileWriter(new File(baseFolder, X509Utils.CERTS + File.separator + "log.txt"), true));
                    writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message));
                    writer.newLine();
                    writer.flush();
                } catch (Exception e) {
                    LoggerFactory.getLogger(GitblitAuthority.class).error("Failed to append log entry!", e);
                } finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        });
        if (serverKeyStore.exists()) {
            /*
				 * HTTPS
				 */
            logger.info("Setting up HTTPS transport on port " + params.securePort);
            GitblitSslContextFactory factory = new GitblitSslContextFactory(params.alias, serverKeyStore, serverTrustStore, params.storePassword, caRevocationList);
            if (params.requireClientCertificates) {
                factory.setNeedClientAuth(true);
            } else {
                factory.setWantClientAuth(true);
            }
            ServerConnector connector = new ServerConnector(server, factory);
            connector.setSoLingerTime(-1);
            connector.setIdleTimeout(settings.getLong(Keys.server.httpIdleTimeout, 30000L));
            connector.setPort(params.securePort);
            String bindInterface = settings.getString(Keys.server.httpsBindInterface, null);
            if (!StringUtils.isEmpty(bindInterface)) {
                logger.warn(MessageFormat.format("Binding HTTPS transport on port {0,number,0} to {1}", params.securePort, bindInterface));
                connector.setHost(bindInterface);
            }
            if (params.securePort < 1024 && !isWindows()) {
                logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
            }
            server.addConnector(connector);
        } else {
            logger.warn("Failed to find or load Keystore?");
            logger.warn("HTTPS transport DISABLED.");
        }
    }
    // conditionally configure the http transport
    if (params.port > 0) {
        /*
			 * HTTP
			 */
        logger.info("Setting up HTTP transport on port " + params.port);
        HttpConfiguration httpConfig = new HttpConfiguration();
        if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
            httpConfig.setSecureScheme("https");
            httpConfig.setSecurePort(params.securePort);
        }
        httpConfig.setSendServerVersion(false);
        httpConfig.setSendDateHeader(false);
        ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
        connector.setSoLingerTime(-1);
        connector.setIdleTimeout(settings.getLong(Keys.server.httpIdleTimeout, 30000L));
        connector.setPort(params.port);
        String bindInterface = settings.getString(Keys.server.httpBindInterface, null);
        if (!StringUtils.isEmpty(bindInterface)) {
            logger.warn(MessageFormat.format("Binding HTTP transport on port {0,number,0} to {1}", params.port, bindInterface));
            connector.setHost(bindInterface);
        }
        if (params.port < 1024 && !isWindows()) {
            logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
        }
        server.addConnector(connector);
    }
    // tempDir is where the embedded Gitblit web application is expanded and
    // where Jetty creates any necessary temporary files
    File tempDir = com.gitblit.utils.FileUtils.resolveParameter(Constants.baseFolder$, baseFolder, params.temp);
    if (tempDir.exists()) {
        try {
            FileUtils.delete(tempDir, FileUtils.RECURSIVE | FileUtils.RETRY);
        } catch (IOException x) {
            logger.warn("Failed to delete temp dir " + tempDir.getAbsolutePath(), x);
        }
    }
    if (!tempDir.mkdirs()) {
        logger.warn("Failed to create temp dir " + tempDir.getAbsolutePath());
    }
    // Get the execution path of this class
    // We use this to set the WAR path.
    ProtectionDomain protectionDomain = GitBlitServer.class.getProtectionDomain();
    URL location = protectionDomain.getCodeSource().getLocation();
    // Root WebApp Context
    WebAppContext rootContext = new WebAppContext();
    rootContext.setContextPath(settings.getString(Keys.server.contextPath, "/"));
    rootContext.setServer(server);
    rootContext.setWar(location.toExternalForm());
    rootContext.setTempDirectory(tempDir);
    // Set cookies HttpOnly so they are not accessible to JavaScript engines
    HashSessionManager sessionManager = new HashSessionManager();
    sessionManager.setHttpOnly(true);
    // Use secure cookies if only serving https
    sessionManager.setSecureRequestOnly((params.port <= 0 && params.securePort > 0) || (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)));
    rootContext.getSessionHandler().setSessionManager(sessionManager);
    // Ensure there is a defined User Service
    String realmUsers = params.userService;
    if (StringUtils.isEmpty(realmUsers)) {
        logger.error(MessageFormat.format("PLEASE SPECIFY {0}!!", Keys.realm.userService));
        return;
    }
    // Override settings from the command-line
    settings.overrideSetting(Keys.realm.userService, params.userService);
    settings.overrideSetting(Keys.git.repositoriesFolder, params.repositoriesFolder);
    settings.overrideSetting(Keys.git.daemonPort, params.gitPort);
    settings.overrideSetting(Keys.git.sshPort, params.sshPort);
    // Start up an in-memory LDAP server, if configured
    try {
        if (!StringUtils.isEmpty(params.ldapLdifFile)) {
            File ldifFile = new File(params.ldapLdifFile);
            if (ldifFile != null && ldifFile.exists()) {
                URI ldapUrl = new URI(settings.getRequiredString(Keys.realm.ldap.server));
                String firstLine = new Scanner(ldifFile).nextLine();
                String rootDN = firstLine.substring(4);
                String bindUserName = settings.getString(Keys.realm.ldap.username, "");
                String bindPassword = settings.getString(Keys.realm.ldap.password, "");
                // Get the port
                int port = ldapUrl.getPort();
                if (port == -1)
                    port = 389;
                InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(rootDN);
                config.addAdditionalBindCredentials(bindUserName, bindPassword);
                config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", port));
                config.setSchema(null);
                InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
                ds.importFromLDIF(true, new LDIFReader(ldifFile));
                ds.startListening();
                logger.info("LDAP Server started at ldap://localhost:" + port);
            }
        }
    } catch (Exception e) {
        // Completely optional, just show a warning
        logger.warn("Unable to start LDAP server", e);
    }
    // Set the server's contexts
    server.setHandler(rootContext);
    // redirect HTTP requests to HTTPS
    if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
        logger.info(String.format("Configuring automatic http(%1$s) -> https(%2$s) redirects", params.port, params.securePort));
        // Create the internal mechanisms to handle secure connections and redirects
        Constraint constraint = new Constraint();
        constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL);
        ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec("/*");
        ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
        sh.setConstraintMappings(new ConstraintMapping[] { cm });
        // Configure this context to use the Security Handler defined before
        rootContext.setHandler(sh);
    }
    // Setup the Gitblit context
    GitblitContext gitblit = newGitblit(settings, baseFolder);
    rootContext.addEventListener(gitblit);
    try {
        // start the shutdown monitor
        if (params.shutdownPort > 0) {
            Thread shutdownMonitor = new ShutdownMonitorThread(server, params);
            shutdownMonitor.start();
        }
        // start Jetty
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(100);
    }
}
Also used : ProtectionDomain(java.security.ProtectionDomain) Scanner(java.util.Scanner) InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) Server(org.eclipse.jetty.server.Server) HashSessionManager(org.eclipse.jetty.server.session.HashSessionManager) Constraint(org.eclipse.jetty.util.security.Constraint) X509Metadata(com.gitblit.utils.X509Utils.X509Metadata) FileWriter(java.io.FileWriter) InMemoryDirectoryServerConfig(com.unboundid.ldap.listener.InMemoryDirectoryServerConfig) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) Properties(java.util.Properties) URI(java.net.URI) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter) ServerConnector(org.eclipse.jetty.server.ServerConnector) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) GitblitContext(com.gitblit.servlet.GitblitContext) GitblitAuthority(com.gitblit.authority.GitblitAuthority) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) NewCertificateConfig(com.gitblit.authority.NewCertificateConfig) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) InputStream(java.io.InputStream) InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) X509Log(com.gitblit.utils.X509Utils.X509Log) IOException(java.io.IOException) CmdLineException(org.kohsuke.args4j.CmdLineException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) Constraint(org.eclipse.jetty.util.security.Constraint) Date(java.util.Date) LDIFReader(com.unboundid.ldif.LDIFReader) File(java.io.File)

Example 20 with ConstraintMapping

use of org.eclipse.jetty.security.ConstraintMapping in project elasticsearch-jetty by sonian.

the class RestConstraintSecurityHandlerTests method constraintMapping.

protected ConstraintMapping constraintMapping(String method, String url, String... roles) {
    ConstraintMapping constraintMapping = new ConstraintMapping();
    Constraint constraint = new Constraint();
    constraintMapping.setMethod(method);
    constraintMapping.setPathSpec(url);
    if (roles.length > 0) {
        constraint.setAuthenticate(true);
        constraint.setRoles(roles);
    }
    constraintMapping.setConstraint(constraint);
    return constraintMapping;
}
Also used : ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Constraint(org.eclipse.jetty.util.security.Constraint)

Aggregations

ConstraintMapping (org.eclipse.jetty.security.ConstraintMapping)50 Constraint (org.eclipse.jetty.util.security.Constraint)47 ConstraintSecurityHandler (org.eclipse.jetty.security.ConstraintSecurityHandler)35 HashLoginService (org.eclipse.jetty.security.HashLoginService)20 BasicAuthenticator (org.eclipse.jetty.security.authentication.BasicAuthenticator)17 Server (org.eclipse.jetty.server.Server)12 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)9 ArrayList (java.util.ArrayList)6 Password (org.eclipse.jetty.util.security.Password)6 Test (org.junit.Test)6 File (java.io.File)5 HttpConstraint (javax.servlet.annotation.HttpConstraint)5 HttpMethodConstraint (javax.servlet.annotation.HttpMethodConstraint)5 IOException (java.io.IOException)4 LoginService (org.eclipse.jetty.security.LoginService)4 ServerConnector (org.eclipse.jetty.server.ServerConnector)4 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)4 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)4 HashSet (java.util.HashSet)3 ConstraintAware (org.eclipse.jetty.security.ConstraintAware)3