11. User Env User&gep Mgmt File Perm

Introduction

  • Use and configure user accounts and user groups.
  • Use and set environment variables.
  • Use the previous shell command history.
  • Use keyboard shortcuts.
  • Use and define aliases.
  • Use and set file permissions and ownership.

Accounts, Users and Groups

Identifying the Current User

  • To identify the current user, type **whoami**.
  • To list the currently logged-on users, type **who**.

Giving **who** the **-a** option will give more detailed information.

User Startup Files

![[Untitled 74.png|Untitled 74.png|left]]

In Linux, the command shell program ( bash or zsh) uses one or more startup files to configure the user environment. Files in the /etc directory define global settings for all users, while initialization files in the user’s home directory can include and/or override the global settings.

The startup files can do anything the user would like to do in every command shell, such as:

  • Customizing the prompt
  • Defining command line shortcuts and aliases
  • Setting the default text editor
  • Setting the path for where to find executable programs

Order of the Startup Files

The standard prescription is that when you first login to Linux, /etc/profile is read and evaluated, after which the following files are searched (if they exist) in the listed order:

  1. ~/.bash_profile
  2. ~/.bash_login
  3. ~/.profile

where ~/. denotes the user’s home directory.

The Linux login shell evaluates whatever startup file that it comes across first and ignores the rest. This means that if it finds ~/.bash_profile, it ignores ~/.bash_login and ~/.profile. Different distributions may use different startup files.

However, every time you create a new shell, or terminal window, etc., you do not perform a full system login; only a file named ~/.bashrc file is read and evaluated. Although this file is not read and evaluated along with the login shell, most distributions and/or users include the ~/.bashrc file from within one of the three user-owned startup files.

![[Untitled 1 39.png|left]]

Most commonly, users only fiddle with ~/.bashrc, as it is invoked every time a new command line shell initiates, or another program is launched from a terminal window, while the other files are read and executed only when the user first logs onto the system.

Creating Aliases

Customized commands or modifying the behavior of already existing ones can be done by creating aliases. These aliases are placed in  ~/.bashrc file so they are available to any command shells that are created. unalias removes an alias.

Typing alias with no arguments will list currently defined aliases.

Please note there should not be any spaces on either side of the equal sign and the alias definition needs to be placed within either single or double quotes if it contains any spaces.

![[Untitled 2 31.png|left]]

Account Types in Linux

Every User in Linux has an associated account.

  • User Account - Maintain user login, password, unique ID and group ID. (Account for Individual people who need access to system)
  • Super User Account (root) - UID (0), have unrestricted access and control of system.
  • System Accounts - Created during OS installation (sshd, mail, etc.). UID<100 or b/w 500 to 1000. Do not have dedicated /home.
  • Service Accounts - Similar to system accounts and created when services (nginx, mercury, etc.) are installed in system.

Purpose of User Accounts

  • Linux systems provide a multi-user environment which permits people and processes to have separate simultaneous working environments.
  • One special user account is for the root user, who is able to do anything on the system. To avoid making costly mistakes, and for security reasons, the root account should only be used when absolutely necessary.
  • Normal user accounts are for people who will work on the system. Some user accounts (like the daemon account) exist for the purpose of allowing processes to run as a user other than root.

Basics of Users and Groups

  • All Linux users are assigned a unique user ID (uid), which is just an integer; normal users start with a uid of 1000 or greater.
  • Linux uses groups for organizing users. Groups are collections of accounts with certain shared permissions.
  • Control of group membership is administered through the /etc/group file, which shows a list of groups and their members.
  • By default, every user belongs to a default or primary group.
  • When a user logs in, the group membership is set for their primary group and all the members enjoy the same level of access and privilege.
  • Permissions on various files and directories can be modified at the group level.
  • Users also have one or more group IDs (gid), which indicate the primary, principal, or default group of the user. The default group ID is the same as the user ID. These numbers are associated with names through the files /etc/passwd and /etc/group.
  • Groups are used to establish a set of users who have common interests for the purposes of access rights, privileges, and security considerations. Access rights to files (and devices) are granted on the basis of the user and the group they belong to.

Attributes of a User Account: /etc/passwd file contains one record (one line) for each user, each of which is a colon ( : ) separated list of fields:

username password UID GID comment on GECOS home shell
owl x 1000 1000 Owl /home/owl /bin/bash

Adding and Removing Users

  • Distributions have straightforward graphical interfaces for creating and removing users and groups and manipulating group membership. However, it is often useful to do it from the command line or from within shell scripts. Only the root user can add and remove users and groups.

  • Adding a new user is done with useradd and removing an existing user is done with **userdel**.

  • In the simplest form, an account for the new user **bjmoose** would be done with:

    **$ sudo useradd bjmoose**

    which, by default, sets the home directory to **/home/bjmoose**, populates it with some basic files (copied from **/etc/skel**) and adds a line to **/etc/passwd** such as:

    **bjmoose:x:1002:1002::/home/**

    **bjmoose:/bin/bash**

    and sets the default shell to **/bin/bash**.

  • The next available **UID** greater than **UID_MIN** (specified in **/etc/login.defs**) by default is assigned as bjmoose’s UID

  • A group called **bjmoose** with a **GID=UID** is also created and assigned as bjmoose’s primary group.

  • An entry of !! is placed in the password field of the /etc/shadow file for bjmoose’s entry, thus requiring the administrator to assign a password for the account to be usable.

  • Custom useradd command:

    sudo useradd -s /bin/csh -m -k /etc/skel -c "Bullwinkle J Moose" bmoose

    • -s /bin/csh: It specifies the login shell for the new user. In this case, the login shell is set to /bin/csh, which is the C Shell.
    • -m: It ensures that the user’s home directory is created.
    • -k /etc/skel: It sets the skeleton directory from which the contents are copied to the new user’s home directory. The skeleton directory typically contains default configuration files and directories.
    • -c "Bullwinkle J Moose": It specifies the comment or description for the user. In this case, the comment is set to “Bullwinkle J Moose”.
    • bmoose: It is the username for the new user. Replace it with the desired username.

  • Removing a user account is as easy as typing **userdel bjmoose**.

  • However, this will leave the **/home/bjmoose** directory intact. This might be useful if it is a temporary inactivation. 

  • To remove the home directory while removing the account one needs to use the **-r** option to **userdel**.

  • Typing **id** with no argument gives information about the current user, as in:

    **$ iduid=1002(bjmoose) gid=1002(bjmoose) groups=106(fuse),1002(bjmoose)**

    If given the name of another user as an argument, **id** will report information about that other user.

==Password Management==

  • Passwords can be changed with **passwd**.

  • Users can change their own password. Root can change any user password.

  • By default, the password choice is examined by **pam_cracklib.so**, which furthers making good password choices. A normal user changing their password would type the following command: **passwd**

    Output:

    Changing password for bjmoose
    (current) UNIX password: <bjmoose’s password>
    New UNIX password: <bjmoose’s-new-password>
    Retype new UNIX password: <bjmoose’s-new-password>
    passwd: all authentication tokens updated successfully


Note that when root changes a user’s password, root is not prompted for the current password.

Command:

$ sudo passwd rjsquirrel

Output:

New UNIX password: <rjsquirrel’s-new-password>
Retype new UNIX password: <rjsquirrel’s-password>
passwd: all authentication tokens updated successfully


Note that normal users will not be allowed to set bad passwords, such as ones that are too short, or based on dictionary words. However, root is allowed to do so.

==Adding and Removing Groups==

  • Adding a new group is done with **groupadd**:

    **$ sudo /usr/sbin/groupadd anewgroup**

  • The group can be removed with **groupdel**:

    **$ sudo /usr/sbin/groupdel anewgroup**

  • Adding a user to an already existing group is done with **usermod**.
    For example, you would first look at what groups the user already belongs to:

    **$ groups rjsquirrelrjsquirrel : rjsquirrel**

    and then add the new group:

    **$ sudo /usr/sbin/usermod -a -G anewgroup rjsquirrel**

    **$ groups rjsquirrelrjsquirrel: rjsquirrel anewgroup**

  • These utilities update **/etc/group** as necessary.

  • Make sure to use the **-a** option, for append, so as to avoid removing already existing groups. **groupmod** can be used to change group properties, such as the Group ID (gid) with the **-g** option or its name with then **-n** option.

  • Removing a user from the group is somewhat trickier. The **-G** option to usermod must give a complete list of groups. Thus, if you do:

    **$ sudo /usr/sbin/usermod -G rjsquirrel rjsquirrel**

    **$ groups rjsquirrelrjsquirrel : rjsquirrel**

    only the **rjsquirrel** group will be left.

Why Use **/etc/shadow**?

  • The default permissions of **/etc/passwd** are **644** **(-rw-r--r--)**; anyone can read the file.
  • This is unfortunately necessary because system programs and user applications need to read the information contained in the file. These system programs do not run as the user root and, in any event, only root may change the file.
  • Of particular concern are the hashed passwords themselves. If they appear in **/etc/passwd**, anyone may make a copy of the hashed passwords and then make use of utilities such as Crack and John the Ripper to guess the original clear text passwords given the hashed password. This is a security risk!
  • **/etc/shadow** has permission settings of **400 (-r--------)**, which means that only root can access this file. This makes it more difficult for someone to collect the hashed passwords.

Unless there is a compelling good reason not to, you should use the **/etc/shadow** file.

**/etc/shadow** Format

**/etc/shadow** contains one record (one line) for each user, as in:

**daemon:*:16141:0:99999:7:::**

**.....beav:$6$iCZyCnBJH9rmq7P.$RYNm10Jg3wrhAtUnahBZ/mTMg.RzQE6iBXyqaXHvxxbK TYqj.d9wpoQFuRp7fPEE3hMK3W2gcIYhiXa9MIA9w1:16316:0:99999:7:::**

Each record contains fields separated by colons ( : ):

  • **username**: unique user name
  • **password**: the hashed (sha512) value of the password
  • **lastchange**: days since Jan 1, 1970 that password was last changed
  • **mindays**: minimum days before password can be changed
  • **maxdays**: maximum days after which password must be changed
  • **warn**: days before password expires that the user is warned
  • **grace**: days after password expires that account is disabled
  • **expire**: date that account is/will be disabled
  • **reserved**: reserved field

The username in each record must match exactly that found in **/etc/passwd**, and also must appear in the identical order. All dates are stored as the number of days since Jan. 1, 1970 (the epoch date).

The password hash is the string **$6$** followed by an eight character salt value, which is then followed by a **$** and an 88 character (sha512) password hash.

==Password Aging (====**chage**====)==

  • It is generally considered important to change passwords periodically. This limits the amount of time a cracked password can be useful to an intruder and also can be used to lock unused accounts.

  • The downside is users can find this policy annoying and wind up writing down their ever-changing passwords and thus making them easier to steal.

  • The utility that manages this is chage:

    **chage** **[-m mindays]** **[-M maxdays]** **[-d lastday]** **[-I inactive]** **[-E expiredate]** **[-W warndays]** **[-l list information]** **user**

Using chage

  • Only the root user can use **chage**. The one exception to this is that any user can run with the -l option to determine when their password or account is due to expire.

To force a user to change their password at their next login, you can run the following command:

**sudo chage -d 0 USERNAME**

Examples of **chage**:

\#used to view the password and account expiration information for a user
sudo chage -l beaver

sudo chage -m 14 -M 30 wally

sudo chage -E 2012-4-1 eddie

sudo chage -d 0 june

==The root Account==

The root account is very powerful and has full access to the system. Other operating systems often call this the administrator account; in Linux, it is often called the superuser account.

==su and sudo==

  • When assigning elevated privileges, command **su** (switch or substitute user) can be used to launch a new shell running as another user (you must type the password of the user you are becoming).
  • Most often, this other user is root, and the new shell allows the use of elevated privileges until it is exited. It is almost always a bad (dangerous for both security and stability) practice to use **su** to become root. Resulting errors can include deletion of vital files from the system and security breaches.
  • Granting privileges using **sudo** is less dangerous and is preferred.
  • By default, **sudo** must be enabled on a per-user basis. However, some distributions (such as Ubuntu) enable it by default for at least one main user, or give this as an installation option.
  • By default, root logins through the network are generally prohibited for security reasons.
  • One can permit Secure Shell logins using ssh, which is configured with **/etc/ssh/sshd_config**, and PAM (Pluggable Authentication Modules), through the **pam_securetty.so** module and the associated **/etc/securetty** file. Root login is permitted only from the devices listed in **/etc/securetty**.
  • It is generally recommended that all root access be through **su** or **sudo** (causing an audit trail of all root access through **sudo**). Note some distributions (such as Ubuntu), by default actually prohibit logging in directly to the root account.
  • PAM can also be used to restrict which users are allowed to **su** to root. It might also be worth it to configure **auditd** to log all commands executed as root.

![[/Untitled 3 20.png|Untitled 3 20.png]]

==Elevating to root Account==

  • To temporarily become the superuser for a series of commands, type **su** and then be prompted for the root password.
  • To execute just one command with root privilege type **sudo <command>**. When the command is complete, you will return to being a normal unprivileged user.
  • **sudo** configuration files are stored in the **/etc/sudoers** file and in the /**etc/sudoers.d/** directory. By default, the **sudoers.d** directory is empty.

==Locked Accounts==

  • Linux ships with some locked accounts which means they can run programs, but can never login to the system and have no valid password associated with them. For example **/etc/passwd** has entries like:

    **bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin**

  • The **nologin** shell returns the following if a locked user tries to login to the system:

    This account is currently not available.

    or whatever message may be stored in **/etc/nologin.txt**.

  • Such locked accounts are created for special purposes, either by system services or applications; if you scan **/etc/passwd** for users with the nologin shell you can see who they are on your system.

  • It is also possible to lock the account of a particular user as in the following command:

    **$ sudo usermod -L bjmoose**

    which means the account stays on the system but logging in is impossible.

  • Unlocking can be done with the **-U** option. A customary practice is to lock a user’s account whenever they leave the organization or is on an extended leave of absence.

  • Another way to lock an account is to use **chage** to change the expiration date of an account, as in the following command:

    **$ sudo chage -E 2001-09-11 rjsquirrel**

    The actual date is irrelevant as long as it is in the past.

    Locked accounts have no valid password:

  • Usually represented by “!!” in **/etc/shadow**

Group Management

  • In Linux systems, groups are collections of users with a common purpose. They share files, directories, and privileges, distinguishing them from others on the system. Groups are beneficial for collaborative projects, and users can belong to multiple groups.

  • The /etc/group file defines groups, similar to how the /etc/passwd file defines users. Each line in the file follows this format:

    groupname:password:GID:user1,user2,...

Here’s what each component represents:

  • groupname: Name of the group.
  • password: Placeholder for the group password. Setting group passwords is only possible if /etc/gshadow exists.
  • GID: Group identifier. Values 0-99 are for system groups, while values 100 and above (up to GID_MIN) are considered special. Values beyond GID_MIN are for User Private Groups (UPG).
  • user1,user2,...: Comma-separated list of users who are members of the group. If a user’s primary group is the current group, they don’t need to be listed explicitly.

Group Membership

  • In Linux, a user has one primary group listed in both /etc/passwd and /etc/group. A user may belong to between 0 and 15 secondary groups.
  • The primary group’s GID is used when the user creates files or directories. Secondary group membership provides additional permissions.

To identify group membership, you can use either of the following commands:

  1. groups [user1 user2 ...]: Shows the groups for specified users. If no user is specified, it displays the groups for the current user.
  2. id -Gn [user1 user2 ...]: Shows the group names for specified users. If no user is specified, it displays the group names for the current user.

Note that the default groups can vary depending on the Linux distribution and installation specifics.

Group Management

  • Group accounts may be managed and maintained with:

    • **groupadd**: Add a new group
    • **groupmod**: Modify a group’s attributes
    • **groupdel**: Remove a group
    • **usermod**: Manage a user’s group memberships
  • These group manipulation utilities modify the **/etc/group** file and, if it exists, the **/etc/gshadow** file, and may only be executed by root. Example commands:

    $ sudo groupadd -r -g 215 staff
    $ sudo groupmod -g 101 blah
    $ sudo groupdel newgroup
    $ sudo usermod -G student,group1,group2 student


The usermod -G command is the total use list of groups, so it will delete and add groups all on one command line. Non-destructive use should utilize the -a option, which will preserve pre-existing group memberships when adding new ones.

User Private Groups

Linux uses User Private Groups (UPG).

  • The idea behind UPGs is that each user will have his or her own group. However, UPGs are not guaranteed to be private; additional members may be added to someone’s private group in **/etc/group**.
  • By default, users whose accounts are created with **useradd** have the primary group id equal to their user id **GID = UID** and their group name is also identical to the username.
  • As specified in **/etc/profile**, the **umask** is set to 002 for all users created with UPG. Under this scheme, user files are thus created with permissions **664 (rw-rw-r--)** and directories with **775 (rwxrwxr-x)**.

Environment Variables

  • Environment variables are values that can be utilized by the command shell, such as bash, or other utilities and applications.
  • A large number of environment variables can be listed with commands such as **env**, **set**, export, or **printenv**. Note that **set** may print out more lines than the other two methods.
  • Some environment variables are given preset values by the system (which can usually be overridden), while others are set directly by the user, either at the command line or within startup and other scripts.
  • An environment variable is simply a character string that contains information used by one or more applications. There are several ways to view the values of currently set environment variables.

==Setting Environment Variables==

  • By default, variables created within a script are only available to the current shell; child processes (sub-shells) will not have access to values that have been set or modified. Allowing child processes to see the values requires use of the export command.

  • All variables are prefixed with **$** when referenced Except when they are being defined:

    ==Task== ==Command==
    Show the value of a specific variable **echo $SHELL**
    Defining a Variable **$ MYCOLOR=blue**Note there can be no spaces around the equal (=) sign!
    Export a new variable value **export VARIABLE=value** (or **VARIABLE=value; export VARIABLE**)
    Add a variable permanently Edit ~/.bashrc and
    add the line 
    **export VARIABLE=value**Type **source ~/.bashrc** or just **. ~/.bashrc (dot ~/.bashrc)**
    or just start a new shell by typing 
    **bash**
  • You can also set environment variables to be fed as a one shot to a command as in:

    **$ SDIRS=s_0* KROOT=/lib/modules/$(uname -r)/build make modules_install** which feeds the values of the **SDIRS** and **KROOT** environment variables to the command **make modules_install**.

==Exporting Environment Variables==

  • By default, variables created within a script are only available to the current shell. Child processes (sub-shells) will not have access to the contents of these variables.

  • In order for variables to be visible to child processes, they need to be exported using the export command.

    Exporting a variable can be done in one step:

    **$ export VAR=value**

    or in two steps:

    **$ VAR=value ; export VAR**


Keep in mind that the child process is allowed to modify exported variables, but the change in this case will not propagate back to the parent shell since exported variables are not shared, but only copied.

$ export VERSION=$(uname-r)
$ export

Output:
declare -x BITS="64"
declare -x CCACHE_COMPRESS="1"
declare -x CCACHE_DIR="/mp/.ccache"
...
declare -x VERSION="4.0.3"

==The HOME Variable==

  • HOME is an environment variable that represents the home (or login) directory of the user. 
  • **cd** without arguments will change the current working directory to the value of HOME.
  • Note the tilde character (~) is often used as an abbreviation for $HOME. Thus, **cd $HOME** and **cd ~** are completely equivalent statements.
    ==Command== ==Explanation==
    **$ echo $HOME** /home/me

    **$ cd /bin**
    Show the value of the HOME environment variable, then change directory (cd) to /bin.
    **$ pwd** /bin Where are we? Use print (or present) working directory (pwd) to find out. As expected, /bin.
    **$ cd** Change directory without an argument…
    **$ pwd** /home/me …takes us back to HOME, as you can now see.

==The PATH Variable==

  • PATH is an ordered list of directories (the path) which is scanned when a command is given to find the appropriate program or script to run. Each directory in the path is separated by colons (:). A null (empty) directory name (or ./) indicates the current directory at any given time.

    • **:path1:path2** (In the example :path1:path2, there is a null directory before the first colon (:))
    • **path1::path2** (Similarly, for path1::path2 there is a null directory between path1 and path2.)
  • To prefix a private **bin** directory to your path:

    **$ export PATH=$HOME/bin:$PATH**``**$ echo $PATH****
    /home/student/bin:/usr/local/bin:/usr/bin:/bin/usr
    **

==The SHELL Variable==

  • The environment variable SHELL points to the user’s default command shell (the program that is handling whatever you type in a command window, usually bash) and contains the full path name to the shell:

    **$ echo $SHELL** /bin/bash

==The PS1 Variable and the Command Line Prompt==

  • Prompt Statement (PS) is used to customize prompt string in terminal windows to display the information user want.

  • PS1 is the primary prompt variable which controls what your command line prompt looks like. The following special characters can be included in PS1:

    **\u**- User name

    **\h** - Host name

    **\w**- Current working directory

    **\!** - History number of this command

    **\d** - Date

https://www.youtube.com/watch?v=cXc8IyYjLqg

History : Recalling Previous Commands

  • Bash keeps track of previously entered commands and statements in a history buffer.
  • It can recall previously used commands simply by using the **Up** and **Down** cursor keys.
  • To view the list of previously executed commands, type **history** at the command line.
  • The list of commands is displayed with the most recent command appearing last in the list.
  • This information is stored in ~/.bash_history.
  • If multiple terminals are open, the commands typed in each session are not saved until the session terminates.

==Using History Environment Variables==

Several associated environment variables can be used to get information about the history file.

  • **HISTFILE** : The location of the history file.
  • **HISTFILESIZE** : The maximum number of lines in the history file (default 500).
  • **HISTSIZE** : The maximum number of commands in the history file.
  • **HISTCONTROL** : How commands are stored.
  • **HISTIGNORE** : Which command lines can be unsaved.

![[/Untitled 4 16.png|Untitled 4 16.png]]

==Finding and Using Previous Commands==

==Key== ==Usage==
**Up**/**Down** arrow keys Browse through the list of commands previously executed
**!!** (Pronounced as bang-bang) Execute the previous command
**CTRL-R** Search previously used commands

press **CTRL-R** to do a reverse intelligent search. As you start typing, the search goes back in reverse order to the first command that matches the letters you have typed.

By typing more successive letters, you make the match more and more specific.

==Executing Previous Commands==

==Syntax== ==Task==
**!** Start a history substitution
**!$** Refer to the last argument in a line
**!n** Refer to the nth command line
**!string** Refer to the most recent command starting with string

All history substitutions start with !. When typing the command: ls -l /bin /etc /var!$ will refer to /var, the last argument to the command.

==Keyboard Shortcuts==

==Keyboard Shortcut== ==Task==
**CTRL-L** Clears the screen
**CTRL-D** Exits the current shell
**CTRL-Z** Puts the current process into suspended background
**CTRL-C** Kills the current process
**CTRL-H** Works the same as backspace
**CTRL-A** Goes to the beginning of the line
**CTRL-W** Deletes the word before the cursor
**CTRL-U** Deletes from beginning of line to cursor position
**CTRL-E** Goes to the end of the line
**Tab** Auto-completes files, directories, and binaries

File Permissions

==File Ownership==

  • In Linux and other UNIX-based operating systems, every file is associated with a user who is the owner. Every file is also associated with a group (a subset of all users) which has an interest in the file and certain rights, or permissions: read, write, and execute.
  • The following utility programs involve user and group ownership and permission setting:
==Command== ==Usage==
**chown** Used to change user ownership of a file or directory
**chgrp** Used to change group ownership
**chmod** Used to change the permissions on the file, which can be done separately for owner, group and the rest of the world (often named as other)

==File Permission Modes and== ==**chmod**==

  • Files have three kinds of permissions: read (**r**), write (**w**), execute (**x**). These are generally represented as in **rwx**.

  • These permissions affect three groups of owners: user/owner (**u**), group (**g**), and others (**o**).

  • As a result, you have the following three groups of three permissions:

    rwx: u: rwx: g:   rwx: o:

    ![[/Untitled 5 14.png|Untitled 5 14.png]]

  • This kind of syntax can be difficult to type and remember, so one often uses a shorthand which lets you set all the permissions in one step. This is done with a simple algorithm, and a single digit suffices to specify all three permission bits for each entity. This digit is the sum of:

    • 4 if read permission is desired
    • 2 if write permission is desired
    • 1 if execute permission is desired.

    Thus, 7 means read/write/execute, 6 means read/write, and 5 means read/execute.

    ![[/Untitled 6 12.png|Untitled 6 12.png]]

![[/Untitled 7 9.png|Untitled 7 9.png]]

![[/Untitled 8 8.png|Untitled 8 8.png]]

  • When you apply this to the **chmod** command, you have to give three digits for each degree of freedom.

**umask**

  • The default permissions given when creating a file are read/write for owner, group and world (0666), and for a directory it is read/write/execute for everyone (0777). However, if you run the following commands:

    touch afile$ mkdir adir$ ls -l | grep -e afile -e adir
    drwxrwxr-x 2 coop coop 4096 Sep 16 11:18 adir-rw-rw-r-- 1 coop coop    0 Sep 16 11:17 afile

    you will notice the actual permissions have changed to 664 for the file and 775 for the directory. They have been modified by the current **umask** whose purpose is to show which permissions should be denied. The current value can be shown by (command and output below):

    umask
    0002

    which is the most conventional value set by system administrators for users. This value is combined with the file creation permissions to get the actual result; i.e.,

    **0666 & ~002 = 0664; i.e., rw-rw-r--**

  • You can change the **umask** at any time with the **umask** command, as in:

    umask 0022
  • The default umask is set in /etc/profile. The root’s umask is 022.k

Special Permissions

Special permissions make up a fourth access level in addition to **user****group**, and **other**.

Special permissions allow for additional privileges over the standard permission sets (as the name suggests). There is a special permission option for each access level discussed previously.

==user + s (pecial) : SUID==

Commonly noted as **SUID**, the special permission for the user access level has a single function: ==A file with== ==_**SUID**_== ==always executes as the user who owns the file, regardless of the user passing the command==. If the file owner doesn’t have execute permissions, then use an uppercase **S** here.

Now, to see this in a practical light, let’s look at the /usr/bin/passwd command. This command, by default, has the SUID permission set:

ls -l /usr/bin/passwd
-rwsr-xr-x. 1 root root 33544 /usr/bin/passwd

Note the _**s**_ where _**x**_ would usually indicate execute permissions for the user.

==group + s (pecial) : SGID==

Commonly noted as **SGID**, this special permission has a couple of functions:

  • If set on a file, it allows the file to be executed as the group that owns the file (similar to SUID)
  • If set on a directory, any files created in the directory will have their group ownership set to that of the directory owner
ls -l
total 0
drwxrws---. 2 tcarrigan tcarrigan  69 Apr 7 11:31 my_articles

This permission set is noted by a lowercase s where the x would normally indicate execute privileges for the group. It is also especially useful for directories that are often used in collaborative efforts between members of a group. Any member of the group can access any new file. This applies to the execution of files, as well. SGID is very powerful when utilized properly.

As noted previously for SUID, if the owning group does not have execute permissions, then an uppercase S is used.

==other + t (sticky) : Sticky Bit==

The last special permission has been dubbed the “sticky bit.” This permission does not affect individual files. However, at the directory level, it restricts file deletion. Only the owner (and root) of a file can remove the file within that directory. A common example of this is the /tmp directory:

ls -ld /tmp/
drwxrwxrwt. 15 root root 4096 Sep 22 15:28 /tmp/

The permission set is noted by the lowercase t, where the x would normally indicate the execute privilege.

Setting special permissions

To set special permissions on a file or directory, you can utilize either of the two methods outlined for standard permissions above: Symbolic or numerical.

Let’s assume that we want to set SGID on the directory community_content.

To do this using the symbolic method, we do the following:

chmod g+s community_content/

Using the numerical method, we need to pass a fourth, preceding digit in our chmod command. The digit used is calculated similarly to the standard permission digits:

  • Start at 0
  • SUID = 4
  • SGID = 2
  • Sticky = 1

The syntax is:

chmod X### file | directory

Where X is the special permissions digit.

Here is the command to set SGID on community_content using the numerical method:

chmod 2770 community_content/
ls -ld community_content/
drwxrws---. 2 tcarrigan tcarrigan 113 Apr  7 11:32 community_content/

ACL (Access Control Lists) (setfacl, getfacl)

Think of a scenario in which a particular user is not a member of group created by you but still you want to give some read or write access, how can you do it without making user a member of group, here comes in picture Access Control Lists, ACL helps us to do this trick.

Basically, ACLs are used to make a flexible permission mechanism in Linux.

  • ACLs allow us to apply a more specific set of permissions to a file or directory without (necessarily) changing the base ownership and permissions. They let us “tack on” access for other users or groups.
\#1) To add permission for user (-m:modify)
setfacl -m "u:user:permissions" /path/to/file

\#2) To add permissions for a group
setfacl -m "g:group:permissions" /path/to/file 

\#3) To allow all files or directories to inherit 
\#ACL entries from the directory it is within (-d:default)
setfacl -dm "entry" /path/to/dir

\#4) To remove a specific entry (-x:remove)
setfacl -x "entry" /path/to/file

\#5) To remove all entries
setfacl -b path/to/file
\#deny all permissions to specific user
sudo setfacl -m user:aaron:--- examplefile

\#remove an ACL for a specific user or a specific group
sudo setfacl -x user:aaron examplefile

\#Apply operations to all files and directories
sudo setfacl -R -m user:aaron:rwx dir1/ 
\#Set File Access Control List (setfacl) 
setfacl -m user:owl:rw examplefile

\#to view the current ACL
getfacl test/declarations.h
# file: test/declarations.h
# owner: owl
# group: owl
user::rw-
group::rw-
other::r--
mask::rw- 
\#Mask defines the maximum permissions that this file or directory 
\#can have.

\#if we want to limit already existing permissions
\#setting maximum permissions we want 
\#would be the ability to read the file, no writing, and no executing.
sudo setfacl -m mask:r examplefile

getfacl examplefile
# file: examplefile
# owner: adm
# group: ftp
user: :rw-
user:aaron : rw-
group: : rw-        \#effective: r- -
mask::r- -          \#effective: r--
other: : r--
\#This tells us that even though the ACL says of user Aaron can read
\#and write, the effective real permissions are read-only
\#and that's because the mask limits the permissions.

Immutability and appendOnly features (lsattr,chattr)

  • Extended Attributes associate metadata not interpreted directly by the filesystem with files. Four namespaces exist: user, trusted, security, and system.
  • The system namespace is used for Access Control Lists (ACLs), and the security namespace is used by SELinux.
  • Flag values are stored in the file inode and may be modified and set only by the root user. They are viewed with **lsattr** and set with **chattr**.

Flags:

  • **i**: Immutable

    A file with the immutable attribute cannot be modified (not even by root). It cannot be deleted or renamed. No hard link can be created to it, and no data can be written to the file. Only the superuser can set or clear this attribute.

    • An immutable directory cannot be deleted or renamed, and files cannot be added or deleted under such a directory.
  • **a**: Append-only

    A file with the append-only attribute set can only be opened in append mode for writing. Only the superuser can set or clear this attribute.

    • An append-Only directory allows new files or sub directories to be created with 0 byte length; all such new created files and sub directories are marked as append-Only automatically.
  • **d**: No-dump

    A file with the no-dump attribute set is ignored when the dump program is run. This is useful for swap and cache files that you don’t want to waste time backing up.

  • **A**: No atime update

    A file with the no-atime-update attribute set will not modify its atime (access time) record when the file is accessed but not otherwise modified. This can increase the performance on some systems because it reduces the amount of disk I/O.

  • The immutable flag and the appendOnly flag can be set independently. If both immutability and appendOnly are set on a file, immutability restrictions will be in effect.

  • To set or unset these attributes, use the following command options:

    **chattr [operator] [flags] [filename]**

    **+** : Adding selected attributes to the existing attributes of the files.

    **–** : Causes selected attributes to be removed.

    **=**: Causes selected attributes to be the only attributes that the files have.

  • To display attributes for a file use **lsattr**

\#For demonstration purpose, let's use folder demo and file important_file.conf respectively
ls -l
	total 0
	drwxr-xr-x. 2 root root 6 Aug 31 18:02 demo
	-rwxrwxrwx. 1 root root 0 Aug 31 17:42 important_file.conf\
\#IMMUTABLE : add attributes on files to secure from deletion
\#SET ATTRIBUTES
\#The immutable bit +i can only be set by superuser 
#(i.e root) user or a user with sudo privileges can able to set.
\#To set attribute, we use the + sign and to unset use the – sign 
\#with the chattr command
sudo chattr +i demo/
sudo chattr +i important_file.conf

\#view attributes
lsattr
----i----------- ./demo
----i----------- ./important_file.conf

\#UNSET ATTRIBUTES
sudo chattr -i demo/ important_file.conf

lsattr
---------------- ./demo
---------------- ./important_file.conf
\#APPEND : Append data without Modifying existing data on a File
chattr +a example.txt

lsattr example.txt
-----a---------- example.txt

\#UNSET ATTRIBUTES
chattr -a example.txt
\#Secure Directories

\#To set permission
chattr -R +i myfolder

\#To unset permission
chattr -R -i myfolder

Knowledge Check (Verified Certificate track only)

![[Screenshot_from_2022-06-27_18-38-46.png]]

![[Screenshot_from_2022-06-27_18-33-11.png]]

![[Screenshot_from_2022-06-27_18-35-36.png]]

![[Screenshot_from_2022-06-27_18-36-23.png]]

![[Screenshot_from_2022-06-27_18-38-02.png]]

![[Screenshot_from_2022-06-27_18-35-00.png]]

![[Screenshot_from_2022-06-27_18-36-08.png]]

![[Screenshot_from_2022-06-27_18-37-05.png]]

![[Screenshot_from_2022-06-27_18-39-05.png]]

![[Screenshot_from_2022-06-27_18-38-28.png]]

Summary

  • Linux is a multi-user system.
  • To find the currently logged on users, you can use the who command.
  • To find the current user ID, you can use the **whoami** command.
  • The root account has full access to the system. It is never sensible to grant full root access to a user.
  • You can assign root privileges to regular user accounts on a temporary basis using the **sudo** command.
  • The shell program (bash) uses multiple startup files to create the user environment. Each file affects the interactive environment in a different way. /etc/profile provides the global settings.
  • Advantages of startup files include that they customize the user’s prompt, set the user’s terminal type, set the command-line shortcuts and aliases, and set the default text editor, etc.
  • An environment variable is a character string that contains data used by one or more applications. The built-in shell variables can be customized to suit your requirements.
  • The history command recalls a list of previous commands, which can be edited and recycled.
  • In Linux, various keyboard shortcuts can be used at the command prompt instead of long actual commands.
  • You can customize commands by creating aliases. Adding an alias to **~/.bashrc** will make it available for other shells.
  • File permissions can be changed by typing **chmod permissions filename**.
  • File ownership is changed by typing **chown owner filename**.
  • File group ownership is changed by typing **chgrp group filename**.