Search in sources :

Example 1 with TrustAllX509TrustManager

use of org.graylog2.security.TrustAllX509TrustManager in project graylog2-server by Graylog2.

the class LdapResource method testLdapConfiguration.

@POST
@Timed
@RequiresPermissions(RestPermissions.LDAP_EDIT)
@ApiOperation("Test LDAP Configuration")
@Path("/test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@NoAuditEvent("only used to test LDAP configuration")
public LdapTestConfigResponse testLdapConfiguration(@ApiParam(name = "Configuration to test", required = true) @Valid @NotNull LdapTestConfigRequest request) {
    final LdapConnectionConfig config = new LdapConnectionConfig();
    final URI ldapUri = request.ldapUri();
    config.setLdapHost(ldapUri.getHost());
    config.setLdapPort(ldapUri.getPort());
    config.setUseSsl(ldapUri.getScheme().startsWith("ldaps"));
    config.setUseTls(request.useStartTls());
    if (request.trustAllCertificates()) {
        config.setTrustManagers(new TrustAllX509TrustManager());
    }
    if (!isNullOrEmpty(request.systemUsername()) && !isNullOrEmpty(request.systemPassword())) {
        config.setName(request.systemUsername());
        config.setCredentials(request.systemPassword());
    }
    LdapNetworkConnection connection = null;
    try {
        try {
            connection = ldapConnector.connect(config);
        } catch (LdapException e) {
            return LdapTestConfigResponse.create(false, false, false, Collections.<String, String>emptyMap(), Collections.<String>emptySet(), e.getMessage());
        }
        if (null == connection) {
            return LdapTestConfigResponse.create(false, false, false, Collections.<String, String>emptyMap(), Collections.<String>emptySet(), "Could not connect to LDAP server");
        }
        boolean connected = connection.isConnected();
        boolean systemAuthenticated = connection.isAuthenticated();
        // the web interface allows testing the connection only, in that case we can bail out early.
        if (request.testConnectOnly()) {
            return LdapTestConfigResponse.create(connected, systemAuthenticated, false, Collections.<String, String>emptyMap(), Collections.<String>emptySet());
        }
        String userPrincipalName = null;
        boolean loginAuthenticated = false;
        Map<String, String> entryMap = Collections.emptyMap();
        String exception = null;
        Set<String> groups = Collections.emptySet();
        try {
            final LdapEntry entry = ldapConnector.search(connection, request.searchBase(), request.searchPattern(), "*", request.principal(), request.activeDirectory(), request.groupSearchBase(), request.groupIdAttribute(), request.groupSearchPattern());
            if (entry != null) {
                userPrincipalName = entry.getBindPrincipal();
                entryMap = entry.getAttributes();
                groups = entry.getGroups();
            }
        } catch (CursorException | LdapException e) {
            exception = e.getMessage();
        }
        try {
            loginAuthenticated = ldapConnector.authenticate(connection, userPrincipalName, request.password());
        } catch (Exception e) {
            exception = e.getMessage();
        }
        return LdapTestConfigResponse.create(connected, systemAuthenticated, loginAuthenticated, entryMap, groups, exception);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                LOG.warn("Unable to close LDAP connection.", e);
            }
        }
    }
}
Also used : LdapConnectionConfig(org.apache.directory.ldap.client.api.LdapConnectionConfig) LdapEntry(org.graylog2.shared.security.ldap.LdapEntry) LdapNetworkConnection(org.apache.directory.ldap.client.api.LdapNetworkConnection) IOException(java.io.IOException) TrustAllX509TrustManager(org.graylog2.security.TrustAllX509TrustManager) URI(java.net.URI) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) IOException(java.io.IOException) ValidationException(org.graylog2.plugin.database.ValidationException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 2 with TrustAllX509TrustManager

use of org.graylog2.security.TrustAllX509TrustManager in project graylog2-server by Graylog2.

the class UnboundLDAPConnector method connect.

public LDAPConnection connect(LDAPConnectorConfig ldapConfig) throws GeneralSecurityException, LDAPException {
    if (ldapConfig.serverList().isEmpty()) {
        LOG.warn("Cannot connect with empty server list");
        return null;
    }
    final String[] addresses = ldapConfig.serverList().stream().map(LDAPConnectorConfig.LDAPServer::hostname).toArray(String[]::new);
    final int[] ports = ldapConfig.serverList().stream().mapToInt(LDAPConnectorConfig.LDAPServer::port).toArray();
    final LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions();
    connectionOptions.setUseReuseAddress(true);
    connectionOptions.setConnectTimeoutMillis(connectionTimeout);
    StartTLSExtendedRequest startTLSRequest = null;
    SocketFactory socketFactory = null;
    if (ldapConfig.transportSecurity() != LDAPTransportSecurity.NONE) {
        SSLUtil.setEnabledSSLProtocols(tlsConfiguration.getEnabledTlsProtocols());
        final SSLUtil sslUtil;
        if (ldapConfig.verifyCertificates()) {
            sslUtil = new SSLUtil(trustManagerProvider.create(Arrays.asList(addresses)));
        } else {
            sslUtil = new SSLUtil(new TrustAllX509TrustManager());
        }
        if (ldapConfig.transportSecurity() == LDAPTransportSecurity.START_TLS) {
            // Use the StartTLS extended operation to secure the connection.
            startTLSRequest = new StartTLSExtendedRequest(sslUtil.createSSLContext());
        } else if (ldapConfig.transportSecurity() == LDAPTransportSecurity.TLS) {
            socketFactory = sslUtil.createSSLSocketFactory();
        }
    }
    final FailoverServerSet serverSet = new FailoverServerSet(addresses, ports, socketFactory, connectionOptions, null, null);
    final LDAPConnection connection = serverSet.getConnection();
    if (startTLSRequest != null) {
        final ExtendedResult startTLSResult = connection.processExtendedOperation(startTLSRequest);
        LDAPTestUtils.assertResultCodeEquals(startTLSResult, ResultCode.SUCCESS);
    }
    if (ldapConfig.systemUsername().isPresent()) {
        if (ldapConfig.systemPassword().isSet()) {
            final String systemPassword = encryptedValueService.decrypt(ldapConfig.systemPassword());
            final BindRequest bindRequest = new SimpleBindRequest(ldapConfig.systemUsername().get(), systemPassword);
            connection.bind(bindRequest);
        } else {
            LOG.warn("System username has been set to <{}> but no system password has been set. Skipping bind request.", ldapConfig.systemUsername().get());
        }
    }
    return connection;
}
Also used : LDAPConnectionOptions(com.unboundid.ldap.sdk.LDAPConnectionOptions) SocketFactory(javax.net.SocketFactory) BindRequest(com.unboundid.ldap.sdk.BindRequest) SimpleBindRequest(com.unboundid.ldap.sdk.SimpleBindRequest) StaticUtils.toUTF8String(com.unboundid.util.StaticUtils.toUTF8String) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) TrustAllX509TrustManager(org.graylog2.security.TrustAllX509TrustManager) SSLUtil(com.unboundid.util.ssl.SSLUtil) SimpleBindRequest(com.unboundid.ldap.sdk.SimpleBindRequest) FailoverServerSet(com.unboundid.ldap.sdk.FailoverServerSet) ExtendedResult(com.unboundid.ldap.sdk.ExtendedResult) StartTLSExtendedRequest(com.unboundid.ldap.sdk.extensions.StartTLSExtendedRequest)

Example 3 with TrustAllX509TrustManager

use of org.graylog2.security.TrustAllX509TrustManager in project graylog2-server by Graylog2.

the class LdapUserAuthenticator method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authtoken) throws AuthenticationException {
    // safe, we only handle this type
    final UsernamePasswordToken token = (UsernamePasswordToken) authtoken;
    final LdapSettings ldapSettings = ldapSettingsService.load();
    if (ldapSettings == null || !ldapSettings.isEnabled()) {
        LOG.trace("LDAP is disabled, skipping");
        return null;
    }
    final LdapConnectionConfig config = new LdapConnectionConfig();
    config.setLdapHost(ldapSettings.getUri().getHost());
    config.setLdapPort(ldapSettings.getUri().getPort());
    config.setUseSsl(ldapSettings.getUri().getScheme().startsWith("ldaps"));
    config.setUseTls(ldapSettings.isUseStartTls());
    if (ldapSettings.isTrustAllCertificates()) {
        config.setTrustManagers(new TrustAllX509TrustManager());
    }
    config.setName(ldapSettings.getSystemUserName());
    config.setCredentials(ldapSettings.getSystemPassword());
    final String principal = (String) token.getPrincipal();
    final char[] tokenPassword = firstNonNull(token.getPassword(), new char[0]);
    final String password = String.valueOf(tokenPassword);
    // do not try to look a token up in LDAP if there is no principal or password
    if (isNullOrEmpty(principal) || isNullOrEmpty(password)) {
        LOG.debug("Principal or password were empty. Not trying to look up a token in LDAP.");
        return null;
    }
    try (final LdapNetworkConnection connection = ldapConnector.connect(config)) {
        if (null == connection) {
            LOG.error("Couldn't connect to LDAP directory");
            return null;
        }
        final LdapEntry userEntry = ldapConnector.search(connection, ldapSettings.getSearchBase(), ldapSettings.getSearchPattern(), ldapSettings.getDisplayNameAttribute(), principal, ldapSettings.isActiveDirectory(), ldapSettings.getGroupSearchBase(), ldapSettings.getGroupIdAttribute(), ldapSettings.getGroupSearchPattern());
        if (userEntry == null) {
            LOG.debug("User {} not found in LDAP", principal);
            return null;
        }
        // needs to use the DN of the entry, not the parameter for the lookup filter we used to find the entry!
        final boolean authenticated = ldapConnector.authenticate(connection, userEntry.getDn(), password);
        if (!authenticated) {
            LOG.info("Invalid credentials for user {} (DN {})", principal, userEntry.getDn());
            return null;
        }
        // user found and authenticated, sync the user entry with mongodb
        final User user = syncFromLdapEntry(userEntry, ldapSettings, principal);
        if (user == null) {
            // in case there was an error reading, creating or modifying the user in mongodb, we do not authenticate the user.
            LOG.error("Unable to sync LDAP user {} (DN {})", userEntry.getBindPrincipal(), userEntry.getDn());
            return null;
        }
        return new SimpleAccount(principal, null, "ldap realm");
    } catch (LdapException e) {
        LOG.error("LDAP error", e);
    } catch (CursorException e) {
        LOG.error("Unable to read LDAP entry", e);
    } catch (Exception e) {
        LOG.error("Error during LDAP user account sync. Cannot log in user {}", principal, e);
    }
    // Return null by default to ensure a login failure if anything goes wrong.
    return null;
}
Also used : SimpleAccount(org.apache.shiro.authc.SimpleAccount) User(org.graylog2.plugin.database.users.User) LdapConnectionConfig(org.apache.directory.ldap.client.api.LdapConnectionConfig) LdapEntry(org.graylog2.shared.security.ldap.LdapEntry) LdapNetworkConnection(org.apache.directory.ldap.client.api.LdapNetworkConnection) TrustAllX509TrustManager(org.graylog2.security.TrustAllX509TrustManager) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) NotFoundException(org.graylog2.database.NotFoundException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) ValidationException(org.graylog2.plugin.database.ValidationException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapSettings(org.graylog2.shared.security.ldap.LdapSettings)

Example 4 with TrustAllX509TrustManager

use of org.graylog2.security.TrustAllX509TrustManager in project graylog2-server by Graylog2.

the class LdapResource method readGroups.

@GET
@ApiOperation(value = "Get the available LDAP groups", notes = "")
@RequiresPermissions(RestPermissions.LDAPGROUPS_READ)
@Path("/groups")
@Produces(MediaType.APPLICATION_JSON)
public Set<String> readGroups() {
    final LdapSettings ldapSettings = firstNonNull(ldapSettingsService.load(), ldapSettingsFactory.createEmpty());
    if (!ldapSettings.isEnabled()) {
        throw new BadRequestException("LDAP is disabled.");
    }
    if (isNullOrEmpty(ldapSettings.getGroupSearchBase()) || isNullOrEmpty(ldapSettings.getGroupIdAttribute())) {
        throw new BadRequestException("LDAP group configuration settings are not set.");
    }
    final LdapConnectionConfig config = new LdapConnectionConfig();
    final URI ldapUri = ldapSettings.getUri();
    config.setLdapHost(ldapUri.getHost());
    config.setLdapPort(ldapUri.getPort());
    config.setUseSsl(ldapUri.getScheme().startsWith("ldaps"));
    config.setUseTls(ldapSettings.isUseStartTls());
    if (ldapSettings.isTrustAllCertificates()) {
        config.setTrustManagers(new TrustAllX509TrustManager());
    }
    if (!isNullOrEmpty(ldapSettings.getSystemUserName()) && !isNullOrEmpty(ldapSettings.getSystemPassword())) {
        config.setName(ldapSettings.getSystemUserName());
        config.setCredentials(ldapSettings.getSystemPassword());
    }
    try (LdapNetworkConnection connection = ldapConnector.connect(config)) {
        return ldapConnector.listGroups(connection, ldapSettings.getGroupSearchBase(), ldapSettings.getGroupSearchPattern(), ldapSettings.getGroupIdAttribute());
    } catch (IOException | LdapException e) {
        LOG.error("Unable to retrieve available LDAP groups", e);
        throw new InternalServerErrorException("Unable to retrieve available LDAP groups", e);
    }
}
Also used : LdapConnectionConfig(org.apache.directory.ldap.client.api.LdapConnectionConfig) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) LdapNetworkConnection(org.apache.directory.ldap.client.api.LdapNetworkConnection) IOException(java.io.IOException) TrustAllX509TrustManager(org.graylog2.security.TrustAllX509TrustManager) URI(java.net.URI) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapSettings(org.graylog2.shared.security.ldap.LdapSettings) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

TrustAllX509TrustManager (org.graylog2.security.TrustAllX509TrustManager)4 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)3 LdapConnectionConfig (org.apache.directory.ldap.client.api.LdapConnectionConfig)3 LdapNetworkConnection (org.apache.directory.ldap.client.api.LdapNetworkConnection)3 ApiOperation (io.swagger.annotations.ApiOperation)2 IOException (java.io.IOException)2 URI (java.net.URI)2 BadRequestException (javax.ws.rs.BadRequestException)2 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)2 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)2 ValidationException (org.graylog2.plugin.database.ValidationException)2 LdapEntry (org.graylog2.shared.security.ldap.LdapEntry)2 LdapSettings (org.graylog2.shared.security.ldap.LdapSettings)2 Timed (com.codahale.metrics.annotation.Timed)1 BindRequest (com.unboundid.ldap.sdk.BindRequest)1 ExtendedResult (com.unboundid.ldap.sdk.ExtendedResult)1 FailoverServerSet (com.unboundid.ldap.sdk.FailoverServerSet)1