I've been reading in most hardening guides for linux, that you should check for files and directories without valid user or valid group. What I can't find, is how this could be used for an attack, or how this could be a weakness, besides it being "improper".
Every file should belong to a user or group, for the primary reason of enforcing file permissions.
A basic but very key concept of protecting a system is the principle of least privilege: allow users minimal access needed to get the job done.
For example, your web development team might need access to your /www directory, but they should not need to have access your system files. Setting up proper ownership and access control for your files makes it easier to enforce the principle of least privileged by limiting the amount of access each user is allowed.
The wording of this question is a bit strange: each file belongs to exactly one user and exactly one group. Each file has separate sets of permissions (rwx) for the owning user, the owning group (minus the owning user if he's in the group), and others. It's impossible for a file not to have that one user and group.
If the filesystem has ACLs, there may be more users and groups with specified permissions on each file.
Users and groups are encoded as integers in the filesystem. These integers are called user ID (uid) and group ID (gid). The association between these integers and user and group names lives at a higher level, they are provided by the standard library. The associations are recorded in local databases such as
Occasionally you may see a file that belongs to a user or group that doesn't have a name. There can be many reasons for this, but most are an indication that something is wrong.
Note that in all of these cases except for the temporarily unavailable network database, the fact that you see a number instead of seeing the wrong name is down to luck. If a user ID has been removed and reassigned, the new user with this ID will have control over the files left over from the old user with this ID — as far as the OS is concerned, this is the same user. If a file is viewed in the wrong user scope, and the ID happens to be assigned to different user names in the two scopes, the you won't get any warning. So while seeing an unnamed user or group is a symptom that something is wrong, you cannot rely on the symptom appearing. Unnamed users and groups should be part of a filesystem audit, but they aren't the main focus.
Files always have a owner-id and a group-id. But if the files are copied from another system (e. g. extracted from a tar archive), there may be no name assigned to those ids.
At a later time a new user or group may be created which gets the next available id. This id, however, may be the same id as the one used improperly before.
As a result the new user/group gets access to those files.