Search in sources :

Example 1 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent in project graylog2-server by Graylog2.

the class SessionsResource method newSession.

@POST
@ApiOperation(value = "Create a new session", notes = "This request creates a new session for a user or reactivates an existing session: the equivalent of logging in.")
@NoAuditEvent("dispatches audit events in the method body")
public SessionResponse newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Username and credentials", required = true) @Valid @NotNull SessionCreateRequest createRequest) {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (!(securityContext instanceof ShiroSecurityContext)) {
        throw new InternalServerErrorException("Unsupported SecurityContext class, this is a bug!");
    }
    final ShiroSecurityContext shiroSecurityContext = (ShiroSecurityContext) securityContext;
    // we treat the BASIC auth username as the sessionid
    final String sessionId = shiroSecurityContext.getUsername();
    // pretend that we had session id before
    Serializable id = null;
    if (sessionId != null && !sessionId.isEmpty()) {
        id = sessionId;
    }
    final String remoteAddrFromRequest = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
    final Subject subject = new Subject.Builder().sessionId(id).host(remoteAddrFromRequest).buildSubject();
    ThreadContext.bind(subject);
    final Session s = subject.getSession();
    try {
        subject.login(new UsernamePasswordToken(createRequest.username(), createRequest.password()));
        final User user = userService.load(createRequest.username());
        if (user != null) {
            long timeoutInMillis = user.getSessionTimeoutMs();
            s.setTimeout(timeoutInMillis);
        } else {
            // set a sane default. really we should be able to load the user from above.
            s.setTimeout(TimeUnit.HOURS.toMillis(8));
        }
        s.touch();
        // save subject in session, otherwise we can't get the username back in subsequent requests.
        ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
    } catch (AuthenticationException e) {
        LOG.info("Invalid username or password for user \"{}\"", createRequest.username());
    } catch (UnknownSessionException e) {
        subject.logout();
    }
    if (subject.isAuthenticated()) {
        id = s.getId();
        final Map<String, Object> auditEventContext = ImmutableMap.of("session_id", id, "remote_address", remoteAddrFromRequest);
        auditEventSender.success(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        // TODO is the validUntil attribute even used by anyone yet?
        return SessionResponse.create(new DateTime(s.getLastAccessTime(), DateTimeZone.UTC).plus(s.getTimeout()).toDate(), id.toString());
    } else {
        final Map<String, Object> auditEventContext = ImmutableMap.of("remote_address", remoteAddrFromRequest);
        auditEventSender.failure(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        throw new NotAuthorizedException("Invalid username or password", "Basic realm=\"Graylog Server session\"");
    }
}
Also used : Serializable(java.io.Serializable) User(org.graylog2.plugin.database.users.User) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownSessionException(org.apache.shiro.session.UnknownSessionException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Subject(org.apache.shiro.subject.Subject) DateTime(org.joda.time.DateTime) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) SecurityContext(javax.ws.rs.core.SecurityContext) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Session(org.apache.shiro.session.Session) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 2 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent 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 3 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent in project graylog2-server by Graylog2.

the class SidecarResource method register.

@PUT
@Timed
@Path("/{sidecarId}")
@ApiOperation(value = "Create/update a Sidecar registration", notes = "This is a stateless method which upserts a Sidecar registration")
@ApiResponses(value = { @ApiResponse(code = 400, message = "The supplied request is not valid.") })
@RequiresPermissions(SidecarRestPermissions.SIDECARS_UPDATE)
@NoAuditEvent("this is only a ping from Sidecars, and would overflow the audit log")
public Response register(@ApiParam(name = "sidecarId", value = "The id this Sidecar is registering as.", required = true) @PathParam("sidecarId") @NotEmpty String sidecarId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull RegistrationRequest request, @HeaderParam(value = "X-Graylog-Sidecar-Version") @NotEmpty String sidecarVersion) {
    final Sidecar newSidecar;
    final Sidecar oldSidecar = sidecarService.findByNodeId(sidecarId);
    List<ConfigurationAssignment> assignments = null;
    if (oldSidecar != null) {
        assignments = oldSidecar.assignments();
        newSidecar = oldSidecar.toBuilder().nodeName(request.nodeName()).nodeDetails(request.nodeDetails()).sidecarVersion(sidecarVersion).lastSeen(DateTime.now(DateTimeZone.UTC)).build();
    } else {
        newSidecar = sidecarService.fromRequest(sidecarId, request, sidecarVersion);
    }
    sidecarService.save(newSidecar);
    final CollectorActions collectorActions = actionService.findActionBySidecar(sidecarId, true);
    List<CollectorAction> collectorAction = null;
    if (collectorActions != null) {
        collectorAction = collectorActions.action();
    }
    RegistrationResponse sidecarRegistrationResponse = RegistrationResponse.create(SidecarRegistrationConfiguration.create(this.sidecarConfiguration.sidecarUpdateInterval().toStandardDuration().getStandardSeconds(), this.sidecarConfiguration.sidecarSendStatus()), this.sidecarConfiguration.sidecarConfigurationOverride(), collectorAction, assignments);
    return Response.accepted(sidecarRegistrationResponse).build();
}
Also used : CollectorActions(org.graylog.plugins.sidecar.rest.models.CollectorActions) ConfigurationAssignment(org.graylog.plugins.sidecar.rest.requests.ConfigurationAssignment) CollectorAction(org.graylog.plugins.sidecar.rest.models.CollectorAction) RegistrationResponse(org.graylog.plugins.sidecar.rest.responses.RegistrationResponse) Sidecar(org.graylog.plugins.sidecar.rest.models.Sidecar) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 4 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent in project graylog2-server by Graylog2.

the class AdministrationResource method administration.

@POST
@Timed
@ApiOperation(value = "Lists existing Sidecar registrations including compatible sidecars using pagination")
@RequiresPermissions({ SidecarRestPermissions.SIDECARS_READ, SidecarRestPermissions.COLLECTORS_READ, SidecarRestPermissions.CONFIGURATIONS_READ })
@NoAuditEvent("this is not changing any data")
public SidecarListResponse administration(@ApiParam(name = "JSON body", required = true) @Valid @NotNull AdministrationRequest request) {
    final String sort = Sidecar.FIELD_NODE_NAME;
    final String order = "asc";
    final String mappedQuery = sidecarStatusMapper.replaceStringStatusSearchQuery(request.query());
    SearchQuery searchQuery;
    try {
        searchQuery = searchQueryParser.parse(mappedQuery);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException("Invalid argument in search query: " + e.getMessage());
    }
    final long total = sidecarService.count();
    final Optional<Predicate<Sidecar>> filters = administrationFiltersFactory.getFilters(request.filters());
    final List<Collector> collectors = getCollectors(request.filters());
    final PaginatedList<Sidecar> sidecars = sidecarService.findPaginated(searchQuery, filters.orElse(null), request.page(), request.perPage(), sort, order);
    final List<SidecarSummary> sidecarSummaries = sidecarService.toSummaryList(sidecars, activeSidecarFilter);
    final List<SidecarSummary> summariesWithCollectors = sidecarSummaries.stream().map(collector -> {
        final List<String> compatibleCollectors = collectors.stream().filter(c -> c.nodeOperatingSystem().equalsIgnoreCase(collector.nodeDetails().operatingSystem())).map(Collector::id).collect(Collectors.toList());
        return collector.toBuilder().collectors(compatibleCollectors).build();
    }).filter(collectorSummary -> !filters.isPresent() || collectorSummary.collectors().size() > 0).collect(Collectors.toList());
    return SidecarListResponse.create(request.query(), sidecars.pagination(), total, false, sort, order, summariesWithCollectors, request.filters());
}
Also used : SearchQuery(org.graylog2.search.SearchQuery) CollectorActions(org.graylog.plugins.sidecar.rest.models.CollectorActions) Produces(javax.ws.rs.Produces) SidecarService(org.graylog.plugins.sidecar.services.SidecarService) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) Configuration(org.graylog.plugins.sidecar.rest.models.Configuration) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) PaginatedList(org.graylog2.database.PaginatedList) AdministrationFilter(org.graylog.plugins.sidecar.filter.AdministrationFilter) MediaType(javax.ws.rs.core.MediaType) CollectorService(org.graylog.plugins.sidecar.services.CollectorService) SidecarConfiguration(org.graylog.plugins.sidecar.system.SidecarConfiguration) ClusterConfigService(org.graylog2.plugin.cluster.ClusterConfigService) Consumes(javax.ws.rs.Consumes) Locale(java.util.Locale) Map(java.util.Map) PluginRestResource(org.graylog2.plugin.rest.PluginRestResource) BadRequestException(javax.ws.rs.BadRequestException) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) Predicate(java.util.function.Predicate) CollectorAction(org.graylog.plugins.sidecar.rest.models.CollectorAction) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) BulkActionRequest(org.graylog.plugins.sidecar.rest.requests.BulkActionRequest) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) SidecarSummary(org.graylog.plugins.sidecar.rest.models.SidecarSummary) Response(javax.ws.rs.core.Response) BulkActionsRequest(org.graylog.plugins.sidecar.rest.requests.BulkActionsRequest) Optional(java.util.Optional) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) ConfigurationService(org.graylog.plugins.sidecar.services.ConfigurationService) Sidecar(org.graylog.plugins.sidecar.rest.models.Sidecar) SearchQueryParser(org.graylog2.search.SearchQueryParser) ApiResponses(io.swagger.annotations.ApiResponses) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) ImmutableList(com.google.common.collect.ImmutableList) AdministrationFiltersFactory(org.graylog.plugins.sidecar.filter.AdministrationFiltersFactory) AuditEvent(org.graylog2.audit.jersey.AuditEvent) Api(io.swagger.annotations.Api) SidecarRestPermissions(org.graylog.plugins.sidecar.permissions.SidecarRestPermissions) SearchQuery(org.graylog2.search.SearchQuery) AdministrationRequest(org.graylog.plugins.sidecar.rest.requests.AdministrationRequest) POST(javax.ws.rs.POST) ActiveSidecarFilter(org.graylog.plugins.sidecar.filter.ActiveSidecarFilter) SidecarAuditEventTypes(org.graylog.plugins.sidecar.audit.SidecarAuditEventTypes) RestResource(org.graylog2.shared.rest.resources.RestResource) SidecarListResponse(org.graylog.plugins.sidecar.rest.responses.SidecarListResponse) ActionService(org.graylog.plugins.sidecar.services.ActionService) ApiResponse(io.swagger.annotations.ApiResponse) Collector(org.graylog.plugins.sidecar.rest.models.Collector) PUT(javax.ws.rs.PUT) SidecarStatusMapper(org.graylog.plugins.sidecar.mapper.SidecarStatusMapper) Predicate(java.util.function.Predicate) SidecarSummary(org.graylog.plugins.sidecar.rest.models.SidecarSummary) Collector(org.graylog.plugins.sidecar.rest.models.Collector) BadRequestException(javax.ws.rs.BadRequestException) Sidecar(org.graylog.plugins.sidecar.rest.models.Sidecar) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 5 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent in project graylog2-server by Graylog2.

the class PipelineResource method parse.

@ApiOperation(value = "Parse a processing pipeline without saving it")
@POST
@Path("/parse")
@NoAuditEvent("only used to parse a pipeline, no changes made in the system")
public PipelineSource parse(@ApiParam(name = "pipeline", required = true) @NotNull PipelineSource pipelineSource) throws ParseException {
    final Pipeline pipeline;
    try {
        pipeline = pipelineRuleParser.parsePipeline(pipelineSource.id(), pipelineSource.source());
    } catch (ParseException e) {
        throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity(e.getErrors()).build());
    }
    final DateTime now = DateTime.now(DateTimeZone.UTC);
    return PipelineSource.builder().title(pipeline.name()).description(pipelineSource.description()).source(pipelineSource.source()).stages(pipeline.stages().stream().map(stage -> StageSource.create(stage.stage(), stage.match(), stage.ruleReferences())).collect(Collectors.toList())).createdAt(now).modifiedAt(now).build();
}
Also used : DateTimeZone(org.joda.time.DateTimeZone) PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) SearchQueryParser(org.graylog2.search.SearchQueryParser) GET(javax.ws.rs.GET) ParseException(org.graylog.plugins.pipelineprocessor.parser.ParseException) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) PaginatedList(org.graylog2.database.PaginatedList) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) MediaType(javax.ws.rs.core.MediaType) Lists(com.google.common.collect.Lists) QueryParam(javax.ws.rs.QueryParam) PipelineService(org.graylog.plugins.pipelineprocessor.db.PipelineService) Consumes(javax.ws.rs.Consumes) SearchQueryField(org.graylog2.search.SearchQueryField) AuditEvent(org.graylog2.audit.jersey.AuditEvent) PluginRestResource(org.graylog2.plugin.rest.PluginRestResource) DefaultValue(javax.ws.rs.DefaultValue) PipelineRuleParser(org.graylog.plugins.pipelineprocessor.parser.PipelineRuleParser) BadRequestException(javax.ws.rs.BadRequestException) Api(io.swagger.annotations.Api) SearchQuery(org.graylog2.search.SearchQuery) NotFoundException(org.graylog2.database.NotFoundException) DELETE(javax.ws.rs.DELETE) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) Pipeline(org.graylog.plugins.pipelineprocessor.ast.Pipeline) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) DateTime(org.joda.time.DateTime) RestResource(org.graylog2.shared.rest.resources.RestResource) PipelineDao(org.graylog.plugins.pipelineprocessor.db.PipelineDao) NotNull(javax.validation.constraints.NotNull) PipelineProcessorAuditEventTypes(org.graylog.plugins.pipelineprocessor.audit.PipelineProcessorAuditEventTypes) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) PaginatedPipelineService(org.graylog.plugins.pipelineprocessor.db.PaginatedPipelineService) PUT(javax.ws.rs.PUT) PaginatedResponse(org.graylog2.rest.models.PaginatedResponse) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) BadRequestException(javax.ws.rs.BadRequestException) ParseException(org.graylog.plugins.pipelineprocessor.parser.ParseException) DateTime(org.joda.time.DateTime) Pipeline(org.graylog.plugins.pipelineprocessor.ast.Pipeline) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Aggregations

ApiOperation (io.swagger.annotations.ApiOperation)33 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)33 POST (javax.ws.rs.POST)30 Path (javax.ws.rs.Path)27 Timed (com.codahale.metrics.annotation.Timed)14 ApiResponses (io.swagger.annotations.ApiResponses)10 Produces (javax.ws.rs.Produces)10 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)10 BadRequestException (javax.ws.rs.BadRequestException)9 Consumes (javax.ws.rs.Consumes)6 Stream (org.graylog2.plugin.streams.Stream)6 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)5 PUT (javax.ws.rs.PUT)5 Search (org.graylog.plugins.views.search.Search)5 RequiresAuthentication (org.apache.shiro.authz.annotation.RequiresAuthentication)4 ValidationResult (org.graylog2.plugin.rest.ValidationResult)4 Api (io.swagger.annotations.Api)3 ApiParam (io.swagger.annotations.ApiParam)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3