Search in sources :

Example 1 with Permissions

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

the class UserPermissionMigrationPeriodical method doRun.

@Override
public void doRun() {
    final List<User> users = userService.loadAll();
    final String adminRoleId = roleService.getAdminRoleObjectId();
    final String readerRoleId = roleService.getReaderRoleObjectId();
    for (User user : users) {
        if (user.isLocalAdmin()) {
            log.debug("Skipping local admin user.");
            continue;
        }
        final Set<String> fixedPermissions = Sets.newHashSet();
        final Set<String> fixedRoleIds = Sets.newHashSet(user.getRoleIds());
        final Set<String> permissionSet = Sets.newHashSet(user.getPermissions());
        boolean hasWildcardPermission = permissionSet.contains("*");
        if (hasWildcardPermission && !user.getRoleIds().contains(adminRoleId)) {
            // need to add the admin role to this user
            fixedRoleIds.add(adminRoleId);
        }
        final Set<String> basePermissions = permissions.readerPermissions(user.getName());
        final boolean hasCompleteReaderSet = permissionSet.containsAll(basePermissions);
        //   - it has the wildcard permissions
        if (!user.getRoleIds().isEmpty() && hasCompleteReaderSet && hasWildcardPermission) {
            log.debug("Not migrating user {}, it has already been migrated.", user.getName());
            continue;
        }
        if (hasCompleteReaderSet && !user.getRoleIds().contains(readerRoleId)) {
            // need to add the reader role to this user
            fixedRoleIds.add(readerRoleId);
        }
        // filter out the individual permissions to dashboards and streams
        final List<String> dashboardStreamPermissions = Lists.newArrayList(Sets.filter(permissionSet, permission -> !basePermissions.contains(permission) && !"*".equals(permission)));
        // add the minimal permission set back to the user
        fixedPermissions.addAll(permissions.userSelfEditPermissions(user.getName()));
        fixedPermissions.addAll(dashboardStreamPermissions);
        log.info("Migrating permissions to roles for user {} from permissions {} and roles {} to new permissions {} and roles {}", user.getName(), permissionSet, user.getRoleIds(), fixedPermissions, fixedRoleIds);
        user.setRoleIds(fixedRoleIds);
        user.setPermissions(Lists.newArrayList(fixedPermissions));
        try {
            userService.save(user);
        } catch (ValidationException e) {
            log.error("Unable to migrate user permissions for user " + user.getName(), e);
        }
    }
    log.info("Marking user permission migration as done.");
    clusterConfigService.write(UserPermissionMigrationState.create(true));
}
Also used : Logger(org.slf4j.Logger) RoleService(org.graylog2.users.RoleService) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Sets(com.google.common.collect.Sets) Inject(javax.inject.Inject) Periodical(org.graylog2.plugin.periodical.Periodical) List(java.util.List) Lists(com.google.common.collect.Lists) ClusterConfigService(org.graylog2.plugin.cluster.ClusterConfigService) UserService(org.graylog2.shared.users.UserService) Predicate(com.google.common.base.Predicate) ValidationException(org.graylog2.plugin.database.ValidationException) UserPermissionMigrationState(org.graylog2.cluster.UserPermissionMigrationState) User(org.graylog2.plugin.database.users.User) Permissions(org.graylog2.shared.security.Permissions) User(org.graylog2.plugin.database.users.User) ValidationException(org.graylog2.plugin.database.ValidationException)

Example 2 with Permissions

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

the class RolesResource method read.

@GET
@Path("{rolename}")
@ApiOperation("Retrieve permissions for a single role")
public RoleResponse read(@ApiParam(name = "rolename", required = true) @PathParam("rolename") String name) throws NotFoundException {
    checkPermission(RestPermissions.ROLES_READ, name);
    final Role role = roleService.load(name);
    return RoleResponse.create(role.getName(), Optional.fromNullable(role.getDescription()), role.getPermissions(), role.isReadOnly());
}
Also used : Role(org.graylog2.shared.users.Role) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 3 with Permissions

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

the class LdapUserAuthenticator method updateFromLdap.

private void updateFromLdap(User user, LdapEntry userEntry, LdapSettings ldapSettings, String username) {
    final String displayNameAttribute = ldapSettings.getDisplayNameAttribute();
    final String fullName = firstNonNull(userEntry.get(displayNameAttribute), username);
    user.setName(username);
    user.setFullName(fullName);
    user.setExternal(true);
    if (user.getTimeZone() == null) {
        user.setTimeZone(rootTimeZone);
    }
    final String email = userEntry.getEmail();
    if (isNullOrEmpty(email)) {
        LOG.debug("No email address found for user {} in LDAP. Using {}@localhost", username, username);
        user.setEmail(username + "@localhost");
    } else {
        user.setEmail(email);
    }
    // TODO This is a crude hack until we have a proper way to distinguish LDAP users from normal users
    if (isNullOrEmpty(user.getHashedPassword())) {
        ((UserImpl) user).setHashedPassword("User synced from LDAP.");
    }
    // map ldap groups to user roles, if the mapping is present
    final Set<String> translatedRoleIds = Sets.newHashSet(Sets.union(Sets.newHashSet(ldapSettings.getDefaultGroupId()), ldapSettings.getAdditionalDefaultGroupIds()));
    if (!userEntry.getGroups().isEmpty()) {
        // ldap search returned groups, these always override the ones set on the user
        try {
            final Map<String, Role> roleNameToRole = roleService.loadAllLowercaseNameMap();
            for (String ldapGroupName : userEntry.getGroups()) {
                final String roleName = ldapSettings.getGroupMapping().get(ldapGroupName);
                if (roleName == null) {
                    LOG.debug("User {}: No group mapping for ldap group <{}>", username, ldapGroupName);
                    continue;
                }
                final Role role = roleNameToRole.get(roleName.toLowerCase(Locale.ENGLISH));
                if (role != null) {
                    LOG.debug("User {}: Mapping ldap group <{}> to role <{}>", username, ldapGroupName, role.getName());
                    translatedRoleIds.add(role.getId());
                } else {
                    LOG.warn("User {}: No role found for ldap group <{}>", username, ldapGroupName);
                }
            }
        } catch (NotFoundException e) {
            LOG.error("Unable to load user roles", e);
        }
    } else if (ldapSettings.getGroupMapping().isEmpty() || ldapSettings.getGroupSearchBase().isEmpty() || ldapSettings.getGroupSearchPattern().isEmpty() || ldapSettings.getGroupIdAttribute().isEmpty()) {
        // no group mapping or configuration set, we'll leave the previously set groups alone on sync
        // when first creating the user these will be empty
        translatedRoleIds.addAll(user.getRoleIds());
    }
    user.setRoleIds(translatedRoleIds);
    // preserve the raw permissions (the ones without the synthetic self-edit permissions or the "*" admin one)
    user.setPermissions(user.getPermissions());
}
Also used : Role(org.graylog2.shared.users.Role) UserImpl(org.graylog2.users.UserImpl) NotFoundException(org.graylog2.database.NotFoundException)

Example 4 with Permissions

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

the class MongoDbAuthorizationRealm method doGetAuthorizationInfo.

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    LOG.debug("Retrieving authorization information for {}", principals);
    final User user = userService.load(principals.getPrimaryPrincipal().toString());
    if (user == null) {
        return new SimpleAuthorizationInfo();
    } else {
        final SimpleAuthorizationInfo info = new UserAuthorizationInfo(user);
        final List<String> permissions = user.getPermissions();
        if (permissions != null) {
            info.setStringPermissions(Sets.newHashSet(permissions));
        }
        info.setRoles(user.getRoleIds());
        LOG.debug("User {} has permissions: {}", principals, permissions);
        return info;
    }
}
Also used : User(org.graylog2.plugin.database.users.User) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo)

Example 5 with Permissions

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

the class UsersResource method get.

@GET
@Path("{username}")
@ApiOperation(value = "Get user details", notes = "The user's permissions are only included if a user asks for his " + "own account or for users with the necessary permissions to edit permissions.")
@ApiResponses({ @ApiResponse(code = 404, message = "The user could not be found.") })
public UserSummary get(@ApiParam(name = "username", value = "The username to return information for.", required = true) @PathParam("username") String username) {
    final User user = userService.load(username);
    if (user == null) {
        throw new NotFoundException("Couldn't find user " + username);
    }
    // if the requested username does not match the authenticated user, then we don't return permission information
    final boolean allowedToSeePermissions = isPermitted(USERS_PERMISSIONSEDIT, username);
    final boolean permissionsAllowed = getSubject().getPrincipal().toString().equals(username) || allowedToSeePermissions;
    return toUserResponse(user, permissionsAllowed, Optional.empty());
}
Also used : User(org.graylog2.plugin.database.users.User) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

User (org.graylog2.plugin.database.users.User)9 ApiOperation (io.swagger.annotations.ApiOperation)7 Permissions (org.graylog2.shared.security.Permissions)7 ApiResponses (io.swagger.annotations.ApiResponses)6 Test (org.junit.Test)6 Path (javax.ws.rs.Path)5 NotFoundException (javax.ws.rs.NotFoundException)4 AuditEvent (org.graylog2.audit.jersey.AuditEvent)4 Role (org.graylog2.shared.users.Role)4 GET (javax.ws.rs.GET)3 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)3 Lists (com.google.common.collect.Lists)2 Sets (com.google.common.collect.Sets)2 UsingDataSet (com.lordofthejars.nosqlunit.annotation.UsingDataSet)2 URI (java.net.URI)2 List (java.util.List)2 Set (java.util.Set)2 Inject (javax.inject.Inject)2 BadRequestException (javax.ws.rs.BadRequestException)2 POST (javax.ws.rs.POST)2