The useradd
command in Linux is used to create a new user account. One of its options, -Z
or --selinux-user SEUSER
, allows you to specify the SELinux user mapping (SEUSER) for the new user. SELinux (Security-Enhanced Linux) is a security module in Linux that provides mandatory access control policies. Mapping a user to an SELinux user context ensures that the user has the appropriate security context when interacting with files and processes on the system.
Here are several examples illustrating the usage of the -Z
option with the useradd
command:
Example 1: Creating a user ‘testuser1’ and mapping it to the SELinux user ‘staff_u’:
$ sudo useradd -Z staff_u testuser1
Output: No output unless there’s an error. To verify, use id -Z
or ls -Z /home/testuser1
to check the SELinux context.
Example 2: Creating a user ‘testuser2’ with the default SELinux user context:
$ sudo useradd testuser2
Output: No output. Verify using id -Z testuser2
to confirm the SELinux context.
Example 3: Creating a user ‘testuser3’ with a custom SELinux user context ‘user_u’:
$ sudo useradd -Z user_u testuser3
Output: Verify the SELinux context with id -Z testuser3
or ls -Z /home/testuser3
.
Example 4: Creating a user ‘testuser4’ with SELinux user ‘system_u’ and adding to additional groups:
$ sudo useradd -Z system_u -G admin,testgroup testuser4
Output: Ensure the user ‘testuser4’ has the correct SELinux context and group memberships.
Example 5: Creating a user ‘testuser5’ with SELinux user ‘user_u’ and specifying home directory:
$ sudo useradd -Z user_u -d /opt/testuser5 testuser5
Output: Check SELinux context and home directory ownership with ls -Z /opt/testuser5
.
Example 6: Creating a user ‘testuser6’ without specifying SELinux context:
$ sudo useradd testuser6
Output: Confirm SELinux context using id -Z testuser6
.
Example 7: Creating a system user ‘testuser7’ with SELinux user ‘system_u’ and no home directory:
$ sudo useradd -r -Z system_u testuser7
Output: Verify SELinux context and check if home directory is not created.
Example 8: Creating a user ‘testuser8’ with SELinux user ‘user_u’ and specifying a different shell:
$ sudo useradd -Z user_u -s /bin/bash testuser8
Output: Ensure SELinux context and shell setting using id -Z testuser8
and grep testuser8 /etc/passwd
.
Example 9: Creating a user ‘testuser9’ with SELinux user ‘unconfined_u’ and setting expiration date:
$ sudo useradd -Z unconfined_u -e 2025-01-01 testuser9
Output: Check SELinux context and expiration date using id -Z testuser9
and sudo chage -l testuser9
.
Example 10: Creating a user ‘testuser10’ with SELinux user ‘user_u’ and disabling password login:
$ sudo useradd -Z user_u -p '!' testuser10
Output: Verify SELinux context and password settings with id -Z testuser10
and grep testuser10 /etc/shadow
.
Discussion about this post