29
Overview A user is anyone who uses a computer. In this case, we are describing the names which represent those users. It may be Mary or Bill, and they may use the names Dragonlady or Pirate in place of their real name. All that matters is that the computer has a name for each account it creates, and it is this name by which a person gains access to use the computer. Some system services also run using restricted or privileged user accounts. Managing users is done for the purpose of security by limiting access in certain specific ways. The superuser (root) has complete access to the operating system and its configuration; it is intended for administrative use only. Unprivileged users can use the su and sudo programs for controlled privilege escalation. Any individual may have more than one account, as long as they use a different name for each account they create. Further, there are some reserved names which may not be used such as "root". Users may be grouped together into a "group", and users may be added to an existing group to utilize the privileged access it grants. Note: The beginner should use these tools carefully and stay away from having anything to do with any other existing user account, other than their own. Permissions and ownership From In UNIX Everything is a File : The UNIX operating system crystallizes a couple of unifying ideas and concepts that shaped its design, user interface, culture and evolution. One of the most important of these is probably the mantra: "everything is a file," widely regarded as one of the defining points of UNIX. This key design principle consists of providing a unified paradigm for accessing a wide range of input/output resources: documents, directories, hard-drives, CD-ROMs, modems, keyboards, printers, monitors, terminals and even some inter-process and network communications. The trick is to provide a common abstraction for all of these resources, each of which the UNIX fathers called a "file." Since every "file" is exposed through the same API, you can use the same set of basic commands to read/write to a disk, keyboard, document or network device. From Extending UNIX File Abstraction for General-Purpose Networking : A fundamental and very powerful, consistent abstraction provided in UNIX and compatible operating systems is the file abstraction. Many OS services and device interfaces are implemented to provide a file or file system metaphor to applications. This enables new uses for, and greatly increases the power of, existing applications — simple tools designed with specific uses in mind can, with UNIX file abstractions, be used in novel ways. A simple tool, such as cat, designed to read one or more files and output the contents to standard output, can be used to read from I/O devices through special device files, typically found under the /dev directory. On many systems, audio recording and playback can be done simply with the commands, " cat /dev/audio > myfile" and " cat myfile > /dev/audio," respectively.

nuxiL basic shell

  • Upload
    allen

  • View
    10

  • Download
    4

Embed Size (px)

DESCRIPTION

linux commandssource: wiki linux

Citation preview

Page 1: nuxiL basic shell

Overview

A user is anyone who uses a computer. In this case, we are describing the names which represent those users.

It may be Mary or Bill, and they may use the names Dragonlady or Pirate in place of their real name. All that

matters is that the computer has a name for each account it creates, and it is this name by which a person

gains access to use the computer. Some system services also run using restricted or privileged user accounts.

Managing users is done for the purpose of security by limiting access in certain specific ways. The superuser

(root) has complete access to the operating system and its configuration; it is intended for administrative use

only. Unprivileged users can use the su and sudo programs for controlled privilege escalation.

Any individual may have more than one account, as long as they use a different name for each account they

create. Further, there are some reserved names which may not be used such as "root".

Users may be grouped together into a "group", and users may be added to an existing group to utilize the

privileged access it grants.

Note: The beginner should use these tools carefully and stay away from having anything to do with any

other existing user account, other than their own.

Permissions and ownership

From In UNIX Everything is a File:

The UNIX operating system crystallizes a couple of unifying ideas and concepts that shaped its

design, user interface, culture and evolution. One of the most important of these is probably the

mantra: "everything is a file," widely regarded as one of the defining points of UNIX.

This key design principle consists of providing a unified paradigm for accessing a wide range of

input/output resources: documents, directories, hard-drives, CD-ROMs, modems, keyboards, printers,

monitors, terminals and even some inter-process and network communications. The trick is to provide

a common abstraction for all of these resources, each of which the UNIX fathers called a "file." Since

every "file" is exposed through the same API, you can use the same set of basic commands to

read/write to a disk, keyboard, document or network device.

From Extending UNIX File Abstraction for General-Purpose Networking:

A fundamental and very powerful, consistent abstraction provided in UNIX and compatible operating

systems is the file abstraction. Many OS services and device interfaces are implemented to provide a

file or file system metaphor to applications. This enables new uses for, and greatly increases the

power of, existing applications — simple tools designed with specific uses in mind can, with UNIX file

abstractions, be used in novel ways. A simple tool, such as cat, designed to read one or more files and

output the contents to standard output, can be used to read from I/O devices through special device files, typically found under the /dev directory. On many systems, audio recording and playback can

be done simply with the commands, "cat /dev/audio > myfile" and "cat myfile >

/dev/audio," respectively.

Every file on a GNU/Linux system is owned by a user and a group. In addition, there are three

types of access permissions: read, write, and execute. Different access permissions can be

applied to a file's owning user, owning group, and others (those without ownership). One can

determine a file's owners and permissions by viewing the long listing format of the ls command:

Page 2: nuxiL basic shell

$ ls -l /boot/

total 13740drwxr-xr-x 2 root root 4096 Jan 12 00:33 grub-rw-r--r-- 1 root root 8570335 Jan 12 00:33 initramfs-linux-fallback.img-rw-r--r-- 1 root root 1821573 Jan 12 00:31 initramfs-linux.img-rw-r--r-- 1 root root 1457315 Jan 8 08:19 System.map26-rw-r--r-- 1 root root 2209920 Jan 8 08:19 vmlinuz-linux

The first column displays the file's permissions (for example, the file initramfs-

linux.img has permissions -rw-r--r--). The third and fourth columns display the file's

owning user and group, respectively. In this example, all files are owned by the root user and

the root group.

$ ls -l /media/

total 16drwxrwx--- 1 root vboxsf 16384 Jan 29 11:02 sf_Shared

In this example, the sf_Shared directory is owned by the root user and the vboxsf group. It is

also possible to determine a file's owners and permissions using the stat command:

Owning user:

$ stat -c %U /media/sf_Shared/

root

Owning group:

$ stat -c %G /media/sf_Shared/

vboxsf

Access rights:

$ stat -c %A /media/sf_Shared/

drwxrwx---

Access permissions are displayed in three groups of characters, representing the permissions of the owning user, owning group, and others, respectively. For example, the characters -rw-r--

r-- indicate that the file's owner has read and write permission, but not execute (rw-), whilst

users belonging to the owning group and other users have only read permission (r-- and r--).

Page 3: nuxiL basic shell

Meanwhile, the characters drwxrwx--- indicate that the file's owner and users belonging to the

owning group all have read, write, and execute permissions (rwx and rwx), whilst other users

are denied access (---). The first character represents the file's type.

List files owned by a user or group with the find utility:

# find / -group [group]# find / -user [user]

A file's owning user and group can be changed with the chown (change owner) command. A file's

access permissions can be changed with the chmod (change mode) command.

See man chown, man chmod, and Linux file permissions for additional detail.

File list

Warning: Do not edit these files by hand. There are utilities that properly handle locking and

avoid invalidating the format of the database. See #User management and #Group

management for an overview.

File Purpose

/etc/shadow Secure user account information

/etc/passwd User account information

/etc/gshadowContains the shadowed information for group

accounts

/etc/group Defines the groups to which users belong

/etc/sudoers List of who can run what by sudo

/home/* Home directories

User management

To list users currently logged on the system, the who command can be used.

To add a new user, use the useradd command:

Page 4: nuxiL basic shell

# useradd -m -g [initial_group] -G [additional_groups] -s [login_shell] [username]

-m creates the user home directory as /home/username. Within their home directory, a

non-root user can write files, delete them, install programs, and so on.

-g defines the group name or number of the user's initial login group. If specified, the group

name must exist; if a group number is provided, it must refer to an already existing group. If not specified, the behaviour of useradd will depend on the USERGROUPS_ENAB variable

contained in /etc/login.defs. The default behaviour (USERGROUPS_ENAB yes) is to

create a group with the same name as the username, with GID equal to UID.

-G introduces a list of supplementary groups which the user is also a member of. Each

group is separated from the next by a comma, with no intervening spaces. The default is for

the user to belong only to the initial group.

-s defines the path and file name of the user's default login shell. After the boot process is

complete, the default login shell is the one specified here. Ensure the chosen shell package

is installed if choosing something other than Bash.

Warning: In order to be able to log in, the login shell must be one of those listed in /etc/shells, otherwise the pam_shell module will deny the login request. In particular,

do not use the /usr/bin/bash path instead of /bin/bash, unless it is properly configured

in /etc/shells.

Note: The password for the newly created user must then be defined, using passwd as

explained below.

When the login shell is intended to be non-functional, for example when the user account is created for a specific service, /usr/bin/nologin may be specified in place of a regular shell

to politely refuse a login (see nologin(8)).

Example adding a user

On a typical desktop system, use the following command to add a new user named archie,

specify Bash as their login shell and add them to the wheel group (see the entry in #User

groups for details):

# useradd -m -G wheel -s /bin/bash archie

Tip: Bash is the default value for the shell (as indicated by useradd -D), so you can omit the -

s option except if you want to use something else.

This command will also automatically create a group called archie with the same GID as the

UID of the user archie and makes this the default group for archie on login. Making each

user have their own group (with group name same as user name and GID same as UID) is the

preferred way to add users.

You could also make the default group something else, e.g. users:

Page 5: nuxiL basic shell

# useradd -m -g users -G wheel archie

However, using a single default group (users in the example above) is not recommended for

multi-user systems. The reason is that typically, the method for facilitating shared write access for specific groups of users is setting user umask value to 002, which means that the default group

will by default always have write access to any file you create. See also User Private Groups.

In the recommended scenario, where the default group has the same name as the user name, all

files are by default writeable only for the user who created them. To allow write access to a

specific group, shared files/folders can be made writeable by default for everyone in this group

and the owning group can be automatically fixed to the group which owns the parent directory by

setting the group sticky bit on this directory:

# chmod g+s our_shared_directory

Otherwise the file creator's default group (usually the same as the user name) is used.

Other examples of user management

To add a user to other groups use (additional_groups is a comma-separated list):

# usermod -aG additional_groups username

Alternatively, gpasswd may be used. Though the username can only be added (or removed) from

one group at a time.

# gpasswd --add username group

Warning: If the -a option is omitted in the usermod command above, the user is removed from

all groups not listed in additional_groups (i.e. the user will be member only of those groups

listed in additional_groups).

To enter user information for the GECOS field (e.g. the full user name), type:

# chfn username

(this way chfn runs in interactive mode).

To specify the user's password, type:

# passwd username

To mark a user's password as expired, requiring them to create a new password the first time

they log in, type:

Page 6: nuxiL basic shell

# chage -d 0 username

User accounts may be deleted with the userdel command.

# userdel -r username

The -r option specifies that the user's home directory and mail spool should also be deleted.

Tip: The AUR packages adduserAUR, adduser-defaultsAUR or adduser-debAUR provide

an adduser script that allows carrying out the jobs of useradd, chfn and passwd interactively. See

also FS#32893.

User database

Local user information is stored in the /etc/passwd file. To list all user accounts on the

system:

$ cat /etc/passwd

There is one line per account, and each is of the format:

account:password:UID:GID:GECOS:directory:shell

where:

account is the user name

password is the user password

UID is the numerical user ID

GID is the numerical primary group ID for the user

GECOS is an optional field used for informational purposes; usually it contains the full user

name

directory is the user's $HOME directory

shell is the user command interpreter (defaults to /bin/sh)

Note: Arch Linux uses shadowed passwords. The passwd file is world-readable, so storing

passwords (hashed or otherwise) in this file would be insecure. Instead, the password field will

contain a placeholder character (x) indicating that the hashed password is saved in the access-

restricted file /etc/shadow.

Page 7: nuxiL basic shell

This article or section needs expansion.

Reason: The tools pwck and pwconv should be mentioned. Brief usage example for

them best also mentions handling .pacnew files generated by filesystem updates.

(Discuss inArchWiki:Requests#User_and_group_pacnew_files)

Group management

/etc/group is the file that defines the groups on the system (man group for details).

Display group membership with the groups command:

$ groups [user]

If user is omitted, the current user's group names are displayed.

The id command provides additional detail, such as the user's UID and associated GIDs:

$ id [user]

To list all groups on the system:

$ cat /etc/group

Create new groups with the groupadd command:

# groupadd [group]

Add users to a group with the gpasswd command:

# gpasswd -a [user] [group]

Modify an existing group with groupmod; e.g. to rename old_group group

to new_group whilst preserving gid (all files previously owned by old_group will be owned

by new_group):

# groupmod -n [new_group] [old_group]

To delete existing groups:

# groupdel [group]

To remove users from a group:

Page 8: nuxiL basic shell

# gpasswd -d [user] [group]

If the user is currently logged in, he/she must log out and in again for the change to take effect.

This article or section needs expansion.

Reason: The tools grpck and grpconv should be mentioned. Brief usage example for

them best also mentions handling .pacnew files generated by filesystem updates.

(Discuss inArchWiki:Requests#User_and_group_pacnew_files)

Group list

User groups

Workstation/desktop users often add their non-root user to some of following groups to allow

access to peripherals and other hardware and facilitate system administration:

Grou

pAffected files Purpose

games /var/games Access to some game software.

rfkill /dev/rfkillRight to control wireless devices power state (used

by rfkill).

users Standard users group.

uucp

/dev/ttyS[0-9], /

dev/tts/[0-9], /

dev/ttyACM[0-9]

Serial and USB devices such as modems, handhelds, RS-

232/serial ports.

wheel Administration group, commonly used to give access to

the sudo and su utilities (neither uses it by default, configurable in /etc/pam.d/su and /etc/pam.d/su-

l). It can also be used to gain full read access

Page 9: nuxiL basic shell

to journal files.

System groups

The following groups are used for system purposes and are not likely to be used by novice Arch

users:

Group Affected files Purpose

bin none Historical

daemon

dbus used internally by dbus

ftp /srv/ftp used by FTP servers like Proftpd

fuse Used by fuse to allow user mounts.

http

kmem /dev/port, /dev/mem, /dev/kmem

mail /usr/bin/mail

mem

nobody Unprivileged group.

polkitd polkit group.

proc /proc/pid/ A group authorized to learn

processes information otherwise

Page 10: nuxiL basic shell

prohibited by hidepid= mount

option of the proc filesystem. The

group must be explicitly set with the gid= mount option.

root /*Complete system administration and

control (root, admin).

smmsp sendmail group.

systemd-

journal/var/log/journal/*

Provides access to the complete

systemd logs. Otherwise, only user

generated messages are displayed.

tty /dev/tty, /dev/vcc, /dev/vc, /dev/ptmx Eg. to acces /dev/ACMx

Software groups

These groups are used by certain non-essential software. Sometimes they are used just

internally, in these cases you should not add your user into these groups. See the main page for

the software for details.

Group Affected files Purpose

adbusers devices nodes under /dev/Right to

access Android De

bugging Bridge.

avahi

bumblebee /run/bumblebee.socket

Right to launch

applications with

Bumblebee to

utilize NVIDIA

Optimus GPUs.

Page 11: nuxiL basic shell

cdemu /dev/vhba_ctlRight to

use CDemu drive

emulation.

clamav /var/lib/clamav/*, /var/log/clamav/*Used by Clam

AntiVirus.

gdm X server authorization directory (ServAuthDir) GDM group.

locate/usr/bin/locate, /var/lib/locate, /var/lib/

mlocate, /var/lib/slocate

Right to

use updatedb com

mand.

mpd/var/lib/mpd/*, /var/log/mpd/*, /var/run/mpd/*,

optionally music directoriesMPD group.

networkma

nager

Requirement for

your user to

connect wirelessly

with NetworkMana

ger. This group is

not included with

Arch by default so it

must be added

manually.

ntp /var/lib/ntp/* NTPd group.

thinkpad /dev/misc/nvramUsed by ThinkPad

users for access to

tools such as tpb.

vboxsf virtual machines' shared foldersUsed

by VirtualBox.

Page 12: nuxiL basic shell

vboxusers /dev/vboxdrvRight to use

VirtualBox

software.

vmware

Right to

use VMware softwa

re.

wireshark

Right to capture

packets

with Wireshark.

Deprecated or unused groups

Following groups are currently of no use for anyone:

Group Purpose

log Access to log files in /var/log/ created by syslog-ng.

sshSshd can be configured to only allow members of this group to login. This is true for any arbitrary group; the ssh group is not created by default, hence non-standard.

stb-

adminUnused! Right to access system-tools-backends

kvm

Adding a user to the kvm group used to be required to allow non-root users to access

virtual machines using KVM. This has been deprecated in favor of using udev rules, and

this is done automatically.

Pre-systemd groups

This article or section needs expansion.

Page 13: nuxiL basic shell

Reason: Input group introduced with systemd 215 [1] (Discuss in Talk:Users and

groups#)

These groups used to be needed before arch migrated to systemd. That is no longer the case,

as long as the logind session is not broken (see General troubleshooting#Session

permissions to check it). The groups can even cause some functionality to break.

See SysVinit#Migration to systemd for details.

Gro

upAffected files Purpose

audio /dev/audio, /dev/snd/*, /dev/rtc0

Direct access to

sound hardware,

for all sessions

(requirement is

imposed by

both ALSA and O

SS). Local

sessions already

have the ability to

play sound and

access mixer

controls.

camer

a

Access to Digital

Cameras.

disk /dev/sda[1-9], /dev/sdb[1-9]

Access to block

devices not

affected by other

groups such as optical, fl

oppy,

and storage.

floppy /dev/fd[0-9]Access to floppy

drives.

lp /etc/cups, /var/log/cups, /var/cache/cups, /var/

spool/cups, /dev/parport[0-9]Access to printer

hardware;

Page 14: nuxiL basic shell

enables the user

to manage print

jobs.

netwo

rk

Right to change

network settings

such as when

using NetworkMa

nager.

optica

l/dev/sr[0-9], /dev/sg[0-9]

Access to optical

devices such as

CD and DVD

drives.

power

Right to use Pm-

utils (suspend,

hibernate...) and

power

management

controls.

scann

er/var/lock/sane

Access to

scanner

hardware.

storag

e

Access to

removable drives

such as USB hard

drives, flash/jump

drives, MP3

players; enables

the user to mount

storage devices.

sys Right to

administer

Page 15: nuxiL basic shell

printers in CUPS.

video /dev/fb/0, /dev/misc/agpgart

Access to video

capture devices,

2D/3D hardware

acceleration,

framebuffer

(X can be

used without belo

nging to this

group). Local

sessions already

have the ability to

use hardware

acceleration and

video capture.

Procedure

Warning: Make certain that you are not logged in as the user whose name you are about to change! Open a new tty (Ctrl+Alt+F1) and log in as root or as another user and su to root. usermod should prevent you

from doing this by mistake.

Change A User's Login

This will change only the user's login name.

# usermod -l newname oldname

Change the Real Name

This will change the real name of the username.

# usermod -c "New Real Name" username

Change A User's $HOME

This will only change the home directory of username. You do not need to manually create the new directory.

The move is fully automatic.

# usermod -d /my/new/home username

Change A User's $HOME and Move Contents

Page 16: nuxiL basic shell

This will move the contents of username's home directory to /my/new/home and set the user's home

directory to the new one. Again, this is an automatic move.

# usermod -m -d /my/new/home username

Link A User's former $HOME to new $HOME

This will created a link between username's former home directory to the new one. Doing this will allow

programs to find files that have hardcoded paths.

Warning: Make sure there is no trailing / on /my/old/home

# ln -s /my/new/home/ /my/old/home

Change Group Name

If you want to change the user's group also:

# groupmod -n newname oldname

Note: This will change a group name but not the numerical GID of the group.

For further information see the man pages for usermod and groupmod.

Manually With /etc/passwd

When possible, you should use the above commands to modify usernames and home directories, however for

those of you who want to know the 'guts' of the operations, it can be done manually.

/etc/passwd File Format

Each line of the file follows a specific format. There are seven fields, each delimited by (":") a colon.

<login name>:<password>:<numerical UID>:<numerical GID>:<Real name/comments>:<home directory>:<user command interpreter>

Warning: It is unsafe to set the <password> field in /etc/passwd. Passwords should be changed (by root)

with the passwd command!

<login name> This field can not be blank. Standard *NIX naming rules apply.

<password> would be an encrypted password, however it should be marked with a lowercase "x" (without quotes) to signify the password is located in /etc/shadow.

Each user and group name has a corresponding numerical UID and GID (User ID and Group ID). In Arch,

the first login name (after root) is UID 1000 by default. Subsequent UID/GID entries for users should be

greater than 1000. GID should match the primary group for the particular user. Numeric values for GIDs are listed in /etc/group.

<Real name/comments> is used by services such as finger. This field is optional and may be left blank.

<home directory> is used by the login command to set the $HOME environment variable. Several services

with their own users use "/" which is safe for services, but not recommended for normal users.

Page 17: nuxiL basic shell

<user command interpreter> is the path to the user's default shell. This is normally Bash, but there are

several other command line interpreters available. The default setting is "/bin/bash" (without quotes) for

users. If you use another CLI, set the path to it here. This field is optional.

Example (user):

jack:x:1001:100:Jack Smith,some comment here,,:/home/jack:/bin/bash

Broken down, this means: user jack (whose password is in /etc/shadow) is UID 1001 and his primary group

is 100 (users). Jack Smith is his full name and there is a comment associated to his account. His home directory is /home/jack and he is using Bash.

Viewing permissions

In order to use chmod to change permissions of a file or directory, you will first need to know what the current

mode of access is. You can view the contents of a directory in the terminal by "cd" to that directory and then

using:

$ ls -l

The -l switch is important because using ls without it will only display the names of files or folders in the

directory.

Below is an example of using ls -l on my home directory:

$ ls -l

total 128-rw-r--r-- 1 ben users 832 Jul 6 17:22 #chmodwiki#drwxr-xr-x 2 ben users 4096 Jul 5 21:03 Desktopdrwxr-xr-x 6 ben users 4096 Jul 5 17:37 Documentsdrwxr-xr-x 2 ben users 4096 Jul 5 13:45 Downloadsdrwxr-xr-x 2 ben users 4096 Jun 24 03:36 Moviesdrwxr-xr-x 2 ben users 4096 Jun 24 03:38 Music-rw-r--r-- 1 ben users 57047 Jun 24 13:57 Namoroka_wallpaper.pngdrwxr-xr-x 2 ben users 4096 Jun 26 00:09 Picturesdrwxr-xr-x 3 ben users 4096 Jun 24 05:03 R-rw-r--r-- 1 ben users 354 Jul 6 17:15 chmodwiki-rw-r--r-- 1 ben users 5120 Jun 27 08:28 data-rw-r--r-- 1 ben users 3339 Jun 27 08:28 datadesign-rw-r--r-- 1 ben users 2048 Jul 6 12:56 dustprac-rw-r--r-- 1 ben users 1568 Jun 27 14:11 dustpracdesign-rw-r--r-- 1 ben users 1532 Jun 27 14:07 dustpracdesign~-rw-r--r-- 1 ben users 229 Jun 27 14:01 ireland.R-rw-r--r-- 1 ben users 570 Jun 27 17:02 noattach.R

Page 18: nuxiL basic shell

-rw-r--r-- 1 ben users 588 Jun 5 15:35 noattach.R~

What the columns mean

The first column is the type of each file:

- denotes a normal file.

d denotes a directory, i.e. a folder containing other files or folders.

p denotes a named pipe (aka FIFO).

l denotes a symbolic link.

The letters after that are the permissions, this first column is what we will be most interested in. The second

one is how many links there are in a file, we can safely ignore it. The third column has two values/names: The

first one (in my example 'ben') is the name of the user that owns the file. The second value ('users' in the

example) is the group that the owner belongs to (Read more about groups).

The next column is the size of the file or directory in bytes and information after that are the dates and times the

file or directory was last modified, and of course the name of the file or directory.

What the permissions mean

The first three letters, after the first - or d, are the permissions the owner has. The next three letters are

permissions that apply to the group. The final three letters are the permissions that apply to everyone else.

Each set of three letters is made up of r w and x. r is always in the first position, w is always in the second

position, and x is always in the third position. r is the read permission, w is the write permission, and x is the

execute permission. If there is a hyphen (-) in the place of one of these letters it means the permission is not

granted, and if the letter is present then it is granted.

Folders

In case of folders the mode bits can be interpreted as follows:

r (read) stands for the ability to read the table of contents of the given directory,

w (write) stands for the ability to write the table of contents of the given directory (create new files, folders;

rename, delete existing files, folders) if and only if execute bit is set. Otherwise this permission is

meaningless.

x (execute) stands for the ability to enter the given directory with command cd and access files, folders in

that directory.

Let's see some examples to clarify, taking one directory from above:

# Ben has full access to the Documents directory.# He can list, create files and rename, delete any file in Documents,# regardless of file permissions.# His ability to access a file depends on the file's permission. drwx------ 6 ben users 4096 Jul 5 17:37 Documents

# Ben has full access except he can not create, rename, delete

Page 19: nuxiL basic shell

# any file.# He can list the files and (if file's permission empowers) # may access an existing file in Documents.dr-x------ 6 ben users 4096 Jul 5 17:37 Documents

# Ben can not do 'ls' in Documents but if he knows# the name of an existing file then he may list, rename, delete or# (if file's permission empowers him) access it.# Also, he is able to create new files.d-wx------ 6 ben users 4096 Jul 5 17:37 Documents

# Ben is only capable of (if file's permission empowers him) # access those files in Documents which he knows of.# He can not list already existing files or create, rename,# delete any of them.d--x------ 6 ben users 4096 Jul 5 17:37 Documents

You should keep in mind that we elaborate on directory permissions and it has nothing to do with the individual

file permissions. When you create new file it is the directory what changes, that is why you need write

permission to the directory.

Note: To keep out graphical file managers, you ought to remove r, not x.

Files

Let's look at another example, this time of a file, not a directory:

-rw-r--r-- 1 ben users 5120 Jun 27 08:28 data

- rw- r-- r-- 1 ben users 5120 Jun 27 08:28 data (Split the permissions coloumn again for easier interpretation)

Here we can see the first letter is not d but -. So we know it is a file, not a directory. Next the owners

permissions are rw- so the owner has the ability to read and write but not execute. This may seem odd that the

owner does not have all three permissions, but the x permission is not needed as it is a text/data file, to be read

by a text editor such as Gedit, EMACS, or software like R, and not an executable in it's own right (if it contained

something like python programming code then it very well could be). The group's permssions are set to r--, so

the group has the ability to read the file but not write/edit it in any way - it is essentially like setting something to

Read-Only. We can see that the same permissions apply to everyone else as well.

Changing permissions using the chmod command

chmod is a command in Linux and other Unix-like operating systems. It allows you to change the permissions

(or access mode) of a file or directory.

Text method

Page 20: nuxiL basic shell

To change the permissions-or access mode-of a file, we use the chmod command in a terminal. Below is the

command's general structure:

chmod who=permissions filename

Where Who is any from a range of letters, and each signifies who you are going to give the permission to. They

are as follows:

u - The user that own the file.g - The group the file belongs to.o - The other users i.e. everyone else.a - all of the above - use this instead of having to type ugo.

The permissions are the same as already discussed (r, w, and x).

Let's have a look at some examples now using this command. Suppose we became very protective of the

Documents directory and wanted to deny everybody but ourselves, permissions to read, write, and execute (or

in this case search/look) in it:

Before: drwxr-xr-x 6 ben users 4096 Jul 5 17:37 DocumentsCommand 1: chmod g= DocumentsCommand 2: chmod o= DocumentsAfter: drwx------ 6 ben users 4096 Jul 6 17:32 Documents

Here, because we want to deny permissions, we do not put any letter after the = where permissions would be

entered. Now you can see that only the owner's permissions are rwx and all other permissions are -'s.

This can be reverted with:

Before: drwx------ 6 ben users 4096 Jul 6 17:32 DocumentsCommand 1: chmod g=rx DocumentsCommand 2: chmod o=rx DocumentsAfter: drwxr-xr-x 6 ben users 4096 Jul 6 17:32 Documents

In the next example, we want to grant read and execute permissions to the group, and other users, so we put

the letters for the permissions (r and x) after the =, with no spaces.

You can simplify this to put more than one who letter in the same command e.g:

chmod go=rx Documents

Note: It does not matter which order you put the who letters or the permission letters in a chmod command:

you could have chmod go=rx File or chmod og=xr File. It is all the same.

Page 21: nuxiL basic shell

Now let's consider a second example, say we want to change our data file so that we have read and write

permissions, and fellow users in our group users who may be colleagues working with us ondata, can also

read and write to it, but other users can only read it:

Before: -rw-r--r-- 1 ben users 5120 Jun 27 08:28 dataCommand1: chmod g=rw dataAfter: -rw-rw-r-- 1 ben users 5120 Jun 27 08:28 data

This is exactly like the first example, but with a data file, not a directory, and we grant a write permission (just

so as to give an example of granting every permission).

Text method shortcuts

The chmod command lets us add and subtract permissions from an existing set using + or - instead of =. This

is different to the above commands, which essentially re-write the permissions (i.e. to change a permission from r-- to rw-, you still need to include r as well as w after the = in the chmod command. If you missed out r, it

would take away the r permission as they are being re-written with the =. Using + and - avoid this by adding or

taking away from the current set of permissions).

Let's try this + and - method with the previous example of adding write permissions to the group:

Before: -rw-r--r-- 1 ben users 5120 Jun 27 08:28 data

Command: chmod g+w dataAfter: -rw-rw-r-- 1 ben users 5120 Jun 27 08:28 data

Another example, denying write permissions to all (a):

Before: -rw-rw-r-- 1 ben users 5120 Jun 27 08:28 data

Command: chmod a-w dataAfter: -r--r--r-- 1 ben users 5120 Jun 27 08:28 data

Copying permissions

It is possible to tell chmod to copy the permissions from one class, say the owner, and give those same

permissions to group or even all. To do this, instead of putting r, w, or x after the =, we put another who letter.

e.g:

Before: -rw-r--r-- 1 ben users 5120 Jun 27 08:28 dataCommand: chmod g=u dataAfter: -rw-rw-r-- 1 ben users 5120 Jun 27 08:28 data

This command essentially translates to "change the permissions of group (g=), to be the same as the owning

user (=u). Note that you cannot copy a set of permissions as well as grant new ones e.g.:

Page 22: nuxiL basic shell

chmod g=wu data

In that case, chmod will have a small fit and throw you an error.

Numeric method

chmod can also set permissions using numbers.

Using numbers is another method which allows you to edit the permissions for all three owner, group, and

others at the same time. This basic structure of the code is this:

chmod xxx file/directory

Where xxx is a 3 digit number where each digit can be anything from 1 to 7. The first digit applies to

permissions for owner, the second digit applies to permissions for group, and the third digit applies to

permissions for all others.

In this number notation, the values r, w, and x have their own number value:

r=4w=2x=1

To come up with a three digit number you need to consider what permissions you want owner, group, and user

to have, and then total their values up. For example, say I wanted to grant the owner of a directory read write

and execution permissions, and I wanted group and everyone else to have just read and execute permissions. I

would come up with the numerical values like so:

Owner: rwx = 4+2+1=7Group: r-x = 4+0+1=5 (or just 4+1=5)Other: r-x = 4+0+1=5 (or just 4+1=5)Final number = 755Command: chmod 755 filename

This is the equivalent of using the following:

chmod u=rwx filenamechmod go=rx filename

Most folders/directories are set to 755 to allow reading and writing and execution to the owner, but deny writing

to everyone else, and files are normally 644 to allow reading and writing for the owner but just reading for

everyone else, refer to the last note on the lack of x permissions with non executable files - its the same deal

here.

Page 23: nuxiL basic shell

To see this in action with examples consider the previous example I've been using but with this numerical

method applied instead:

Before: -rw-r--r-- 1 ben users 5120 Jun 27 08:28 dataCommand: chmod 664 dataAfter: -rw-rw-r-- 1 ben users 5120 Jun 27 08:28 data

If this were an executable the number would be 774 if I wanted to grant executable permission to the owner

and group. Alternatively if I wanted everyone to only have read permission the number would be 444.

Treating r as 4, w as 2, and x as 1 is probably the easiest way to work out the numerical values for

using chmod xxx filename, but there is also a binary method, where each permission has a binary number,

and then that is in turn converted to a number. It is a bit more convoluted, but I include it for completeness.

Consider this permission set:

- rwx r-x r--

If you put a 1 under each permission granted, and a 0 for every one not granted, the result would be something

like this:

- rwx rwx r-x 111 111 101

You can then convert these binary numbers:

000=0 100=4001=1 101=5010=2 110=6011=3 111=7

The value of the above would therefore be 775.

Consider we wanted to remove the writable permission from group:

- rwz r-x r-x 111 101 101

The value would therefore be 755 and you would use chmod 755 filename to remove the writable permission.

You will notice you get the same three digit number no matter which method you use. Whether you use text or

numbers will depend on personal preference and typing speed. When you want to restore a directory or file to

default permissions i.e. read and write (and execute) permission to the owner but deny write permission to

everyone else, it may be faster to use chmod 755/644 directory/filename. But if you are changing the

permissions to something out of the norm, it may be simpler and quicker to use the text method as opposed to

trying to convert it to numbers, which may lead to a mistake. It could be argued that there isn't any real

significant difference in the speed of either method for a user that only needs to use chmod on occasion.

Page 24: nuxiL basic shell

Bulk chmod

Generally directories and files should not have the same permissions. If it is necessary to bulk modify a

directory tree, use find to selectively modify one or the other.

To chmod only directories to 755:

$ find directory -type d -exec chmod 755 {} +

To chmod only files to 644:

$ find directory -type f -exec chmod 644 {} +

Changing ownership using the chown command

Whilst this is an article dedicated to chmod, chown deserves mention as well. Where chmod changes the

access mode of a file or directory, chown changes the owner of a file or directory, which is quicker and easier

than altering the permissions in some cases, but do be careful when you do so.

Consider the following example, making a new partition with GParted for backup data. Gparted does this all as

root so everything belongs to root. This is all well and good but when it came to writing data to the mounted

partition, permission was denied.

brw-rw---- 1 root disk 8, 9 Jul 6 16:02 sda9drwxr-xr-x 5 root root 4096 Jul 6 16:01 Backup

As you can see the device in /dev is owned by root, as is where it is mounted (/media/Backup). To change

the owner of where it is mounted one can do the following:

Before: drwxr-xr-x 5 root root 4096 Jul 6 16:01 BackupCommand: chown ben Backup (cd'd to /media first)After drwxr-xr-x 5 ben root 4096 Jul 6 16:01 Backup

Now the partition can have backup data written to it as instead of altering the permissions, as the owner

already has rwx permissions, the owner has been altered to the user ben. Alternatives would be to alter the

permissions for everyone else (undesirable as it's a backup permission) or adding the user to the group root.

Access Control Lists

Access Control Lists provides an additional, more flexible permission mechanism for file systems by allowing

to set permissions for any user or group to any file.

The presence of ACLs can be identified by a plus (+) sign in the output of ls command.

File attributes

Page 25: nuxiL basic shell

Apart from the file mode bits that control user and group read, write and execute permissions, several file

systems support file attributes that enable further customization of allowable file operations. This section

describes some of these attributes and how to work with them.

Warning: By default, file attributes are not preserved by cp, rsync, and probably others.

chattr and lsattr

For ext2 and ext3 file systems, the e2fsprogs package contains the programs lsattr and chattr that list and

change a file's attributes, respectively. Though some are not honored by all file systems, the available

attributes are:

a : append only

c : compressed

d : no dump

e : extent format

i : immutable

j : data journalling

s : secure deletion

t : no tail-merging

u : undeletable

A : no atime updates

C : no copy on write

D : synchronous directory updates

S : synchronous updates

T : top of directory hierarchy

For example, if you want to set the immutable bit on some file, use the following command:

# chattr +i /path/to/file

To remove an attribute on a file just change + to -.

Extended attributes

From attr(5): "Extended attributes are name:value pairs associated permanently with files and directories".

There are four extended attribute classes: security, system, trusted and user.

Warning: By default, extended attributes are not preserved by cp, rsync, and probably others.

User extended attributes

User extended attributes can be used to store arbitrary information about a file. To create one:

$ setfattr -n user.checksum -v "3baf9ebce4c664ca8d9e5f6314fb47fb" foo.bar

Use getfattr to display extended attributes:

Page 26: nuxiL basic shell

$ getfattr -d foo.bar# file: foo.baruser.checksum="3baf9ebce4c664ca8d9e5f6314fb47fb"