You are on page 1of 382
LPI101 LPIC-1 EXAM PREP (COURSE 1) RHELS.4 SLES11 U804 31 any claims, demands, loses, damages, costs of expenses ia om om cnpecton wth the uso of tis courseware. A rope of har respective owners. Version: LPI1¢1S-R548110884~D82 Table of Contents Chapter 1 MANAGE FILE PERMISSIONS AND OWNERSHIP LPI Objectives Covered Filesystem Hierarchy Standard Navigating the Filesystem Displaying Directory Contents ‘Two Types of Disk Space Determining Disk Usage With df and du File Ownership Default Group Ownership File and Directory Permissions File Creation Permissions with umask Changing File Permissions SUID and SGID on files ‘SGID and Sticky Bit on Directories User Private Group Scheme Lab Tasks 1. Files and Directories 2. Disk and Filesystem Usage 3. File and Directory Ownership and Permissions Chapter 2 ‘CREATE, DELETE, FIND, AND DISPLAY FILES LPI Objectives Covered Directory Manipulation File Manipulation Deleting and Creating Files Physical Unix File Structure Filesystem Links File Extensions and Content Displaying Files Previewing Files Displaying Binary Files Searching the Filesystem Altermate Search Method Manually Installed Shared Libraries Lab Tasks 1. File and Directory Manipulation Commands 2. File Examination & Search Commands Chapter 3 WORK WITH ARCHIVES AND COMPRESSION LPI Objectives Covered Archives with tar Archives with cpio ‘The gzip Compression Utility ‘The bzip2 Compression Utility ‘The PKZIP Archiving/Compression format Lab Tasks 1. Archiving and Compression 2. Using tar and cpio for Backups Chapter 4 PROCESS TEXT STREAMS USING FILTERS LPI Objectives Covered Producing File Statistics Searching Inside Files The Streaming Editor Text Processing with awk Replacing Text Characters Text Sorting Duplicate Removal Utility Extracting Columns of Text Combining Files and Merging Text Lab Tasks 1. Text Processing Chapter 5 WORK ON THE COMMAND LINE LPI Objectives Covered Role of Command Shell Shells Identifying the Shell Changing the Shell sh: Prompts bash: Bourne Again Shell bash: Command Editing bash: Command Completion Shell and Environment Variables Key Environment Variables Lab Tasks Boovansen+ COVATEON= 1. Linux Shells 2. Shell Variables 3, Bash History 4, Aliases. Chapter 6 USE STREAMS, PIPES AND REDIRECTS LPI Objectives Covered File Redirection Piping Commands Together Filename Matching File Globbing and Wildcard Patterns, Brace Expansion General Quoting Rules Nesting Commands Multiple and Multiline Commands Lab Tasks 1. Connecting Commands 2. Wildcard File Matching 3. Shell Meta-Characters 4, Command Substitution Chapter 7 ‘SEARCH TEXT FILES USING REGULAR EXPRESSIONS LPI Objectives Covered Regular Expression Overview Regular Expressions RE Character Classes RE Quantifiers RE Parenthesis Lab Tasks 1. Pattern Matching with Regular Expressions 2. Extended Regular Expressions 3. Using Regular Expressions With sed Chapter 8 PERFORM BASIC FILE EDITING OPERATIONS USING VI LPI Objectives Covered Text Editing viand Vim Learning vi Basic vi Intermediate vi 16 20, 22 warvasen 10 12 13 18 20 23 Bocovamsens Noasens Lab Tasks 1. Text Editing with Vim Chapter 9 CREATE, MONITOR AND KILL PROCESSES. LPI Objectives Covered ‘What is a Process? Process Creation Process States ‘Viewing Processes Signals Tools to Send Signals Job Control Basics Jobs Managing Processes Tuning Process Scheduling Lab Tasks 1, Job Control Basics 2. Process Management and Job Control Basics Chapter 10 USE RPM, YUM, AND DEBIAN PACKAGE MANAGEMENT LPI Objectives Covered Managing Software Working With RPMs Querying and Verifying with rpm Installing Debian Packages Querying and Verifying with dpkg The alien Package Conversion Too! Managing Software Dependencies Using the YUM command Configuring YUM The dselect & APT Frontends to dpkg Aptitude Configuring APT Compiling/Installing from Source Installing Source RPM Packages Lab Tasks| 1. Querying the RPM Database 2. Installing Software via RPM & Source and Rebuiding SRPMs 10 " Chapter 11 WORK WITH PARTITIONS, FILESYSTEMS, AND DISK QUOTAS LPI Objectives Covered Partition Considerations Filesystem Planning Partitioning Disks with fdisk Partitioning Disks with parted Filesystem Creation Filesystem Support Unix/Linux Filesystem Features ‘Swap Selecting a Filesystem Filesystem Maintenance Mounting Filesystems Mounting Filesystems NFS SMB Filesystem Table (/etci/fstab) Configuring Disk Quotas Setting Quotas, Viewing and Monitoring Quotas Lab Tasks 1, Hot Adding Swap 2. Accessing NFS Shares 3. Setting User Quotes Chapter 12 LINUX BOOT PROCESS LPI Objectives Covered Booting Linux on PCs LILO Options GRUB Configuration Kernel Boot Parameters Isbinfinit System Init Styles Linux Runlevels Jetcfinittab Jetc/event.d/* Jetc/rc.sysinit SUSE /etcinit.d/boot Ubuntu /etc/event.d/rcS Runlevel Implementation Shutdown and Reboot iv Wonaan— 10 12 13 15 7 20 21 22 23 24 25 26 27 29 31 Lab Tasks: 1, Boot Process 2. GRUB Command Line 3. Basic GRUB Security Chapter 13 DETERMINE AND CONFIGURE HARDWARE SETTINGS LPI Objectives Covered ‘Managing Linux Device Files Hardware Discovery Tools Configuring New Hardware with Kudzu Configuring New Hardware with hwinfo PC Architecture and Bus DMA & IRQ. USB Devices USB Configuration Configuring Kernel Components and Modules Kemel Modules Handling Module Dependencies Configuring the Kernel via /procf Kernel Hardware Info ~ /sys/ Jsys/ Structure Lab Tasks 1. PC Hardware and Linux Appendix A LINUX FUNDAMENTALS UNIX Design Principles FSF and GNU GPL. General Public License The Linux Kernel Popular Uses of Linux Components of a Distribution Standardization Red Hat Linux Products SUSE Linux Products Debian Ubuntu Logging In got root? Switching User Contexts Gathering Login Session Info Gathering System Info 23 24 32 36 Help from Commands and Documentation Getting Help with man & info SMANPATH, whatis and apropos Lab Tasks 1. Login and Discovery 2. Help with Commands 3. Switching Users With su 18 19 2 22 27 31 Typographic Conventions ‘The fonts, layout, and typographic conventions of this book have been carefully chosen to increase readability. Please take a moment to familiarize yourself with them. A Warning and Solut ‘A common problem with computer training and reference materials is the confusion of the numbers "zero" and ‘one’ with the letters “oh* and ‘ell’. To avoid this confusion, this book uses a fixed-width font thet makes each letter and number distinct. Typefaces Used and Their Meanings ‘The following typeface conventions have been followed in this book: fixed-width normal + Used to denote file names and directories. For example, the /etc/passwd file or /ete/sysconfig/directory. Also used for computer text, particularily command line output fixed-vidth italic = Indicates that a substitution is required. For ‘example, the string station is commonly used to indicate that the student is expected to replace X with his or her own station number, such as station3 fixed-width bold => Used to set apart commands. For exemple. the ‘sed command. Also used to indicate input a user might type on the command line. For example, ssh -K station} fixed-width bold italic > Used when a substitution is required within a command or user input. For example, ssh ~X stations. fixed-width underlined + Used to denote URLs. For example, hnttp://wwy qurulabs .com variable-width bold > Used within labs to indicate a required student action that is not typed on the command line. Occasional variations from these conventions occur to increase clarity. This is most apparent in the labs where bold text is only used to indicate commands the student must enter or actions the student must perform. vi 0 O The number The letter "zero" "oh The number The letter "one" "el, Typographic Conven' Terms and Definitions The following format is used to introduce and define a series of terms: deprecate = To indicate that something is considered obsolete, with the intent of future removal. frob = To manipulate or adjust, typically for fun, as opposed to tweak. grok = To understand. Connotes intimate and exhaustive knowledge. hork + To break, generally beyond hope of repair. hosed + A metaphor referring to a Cray that crashed after the disconnection of coolant hoses. Upon correction, users were assured the system was rehosed. mung (or munge) + Mash Until No Good: to modify a file, often irreversibly. troll = To bait, or provoke, an argument, often targeted towards the newbie. Also used to refer to a person that regularly trolls. twiddle = To make small, often aimless, changes. Similar to frob, When discussing a command, this same format is also used to show and describe a list of common or important command options. For example, the following ssh options: -X = Enables X11 forwarding. In older versions of OpenSSH that do not include -¥, this enables trusted X11 forwarding. In newer versions of OpenSSH, this enables a more secure, limited type of forwarding, -¥ = Enables trusted X11 forwarding. Although less secure, trusted forwarding may be required for compatibility with certain programs. Representing Keyboard Keystrokes When it is necessary to press a series of keys, the series of keystrokes will be represented without a space between each key. For example, the following means to press the ‘)’ key three times: GIGI When itis necessary to press keys at the same time, the combination will be represented with a plus between each key. For example, the following means to press the “ctr,” alt,” and "backspace" keys at the same time. [== }Geea], Uppercase letters are treated the same: B&)) Line Wrapping Occasionally content that should be on a single line, such as command line input or URLs, must be broken across multiple lines in order to fit ‘on the page. When this is the case, a special symbol is used to indicate to the reader what has happened. When copying the content, the line breaks should not be included. For example, the following hypothetical PAM configuration should only take two actual lines password required /1ib/security/pam_cracklib.so retry=3> types minlen=12 deredit=2 ucredit=2 leredit= ocredit=2 password required /Lib/security/pam_unix.so use_authtok Edits Representing Fi File edits are represented using a consistent layout similar to the unified iff format. When a line should be added, it is shown in bold with a plus sign to the left. When a line should be deleted, it is shown struck out with a minus sign to the left. When a line should be modified, it is shown twice. The old version of the line is shown siruck out with a minus sign to the left. The new version of the line is shown below the old version, bold and with a plus sign to the left. Unmodified lines are often included to provide context for the edit. For example, the following describes modification of an existing line and addition of a new line to the OpenSSH server configuration file File: /etc/ssh/sshd_config FoginGraceTime am sBotlehesttegee es PernitRootLogin no AllowUsers sjansen #Strictiodes yes Note that the standard file edit representation may not be used when it is important that the edit be performed using a specific editor or method. In these rare cases, the editor specific actions will be given instead. Lab Conventions Lab Task Headers Every lab task begins with three standard informational headers “Objectives,' *Requirements,' and "Relevance", Some tasks also include a "Notices" section. Each section has a distinct purpose. Objectives = An outline of what will be accomplished in the lab task. Requirements = A list of requirements for the task. For example, Whether it must be performed in the graphical environment, or whether multiple computers are needed for the lab task Relevance = A brief example of how concepts presented in the lab task might be applied in the real world, Notices > Special information or warnings needed to successfully complete the lab task. For example, unusual prerequisites or common sources of difficulty, Command Prompts Though different shells, and distributions, have different prompt characters, examples will use a $ prompt for commands to be run as a normal user (like guru or visitor}, and commands with a # prompt should be run as the root user. For example: § whoami. guru $ su - Password: password 4 whoami, root Occasionally the prompt will contain additional information. For example, when portions of a lab task should be performed on two different stations always of the same distribution), the prompt will be expanded to. stationx$ whoami guru stationx$ ssh root@stationy rootlstationy’s password: password stationy# whoami root viii Variable Data Substitutions In some lab tasks, students are required to replace portions of commands with variable data. Variable substitution are represented using italic fonts. For example, x and ¥. Substitutions are used most often in lab tasks requiring more than one computer. For example, if a student on stationd were working with a student on station2, the lab task would refer to stationX and stationY stationx$ ssh root@stationy and each would be responsible for interpreting the X and ¥ as 4 and 2. station{$ ssh root@station2 Truncated Command Examples ‘Command output is occasionally omitted or truncated in examples. There are two type of omissions: complete or partial. Sometimes the existence of a command's output, and not its content, is, all that matters. Other times, a commend’s output is too variable to reliably represent. In both cases, wher @ command should produce output, but an example of that output is not provided, the following format is used $ cat /ete/passud + output omitted... In general, at least a partial output example is included after commands. When example output has been trimmad to include only certain lines, the following format is used $ cat /etc/passwd root:x:@:0:root:/root ‘bin/bash ‘lint Savage: /home/clints:/bin/zsh Lab Conventions Distribution Specific Information This courseware is designed to support multiple Linux distributions. When there are minor differences between the enterprise and enthusiast distributions, the enterprise distributions are preferred for examples, screenshots, etc. When the differences are more significant, each version is labeled with the appropriate base strings: RHEL = Red Hat Enterprise Linux SLES = SUSE Linux Enterprise Server U = Ubuntu The specific supported version is appended to the base distribution strings, so for Red Hat Enterprise Linux version 5 the complete string is: RHEL. Certain lab tasks are designed to be completed on only a sub-set of ‘the supported Linux distributions. If the distribution you are using is not shown in the list of supported distributions for the lab task, then you should skip that task. Certain lab steps are only to be performed on a sub-set of the supported Linux distributions. In this case, the step will start with a standardized string that indicates which distributions the step should be performed on. ‘When completing lab tasks, skip any steps that do not list your chosen distribution. For example: 1) This step should only be performed on RHEL4 and FC3. Because of a bug in RHEL4's and FC3's Japanese fonts. Sometimes commands or command output is distribution specific. In these cases, the matching distribution string will be shown to the left of the command or output. For example § grep -i linux /etc/*-release | cut -d: ~£2 wesalRed Hat Enterprise Linux Server release 5.3 (Tikanga) isusit] SUSE Linux Enterprise Server 11 (i586) Action Lists Some lab steps consist of a list of conceptually related actions. A description of each action and its effect is shown to the right or under the action. Alternating actions are shaded to aid readability. For example, the following action list describes one possible way to launch and use ‘xkil1 to kill a graphical application a xki le) Open the "Run Application” dialog. Launch xkill. The cursor should change, usually to a skull and crossbones. Click on a window of the application to kill Indicate which process to kill by clicking on it. All of the application's windows should disappear. Callouts Occasionally lab steps will feature a shaded line that extends to a note in the right margin. This note, referred to as a "callout," is used to provide additional commentary. This commentary is never necessary to complete the lab succesfully and could in theory be ignored. However, callouts do provide valuable information such as insight into why a particular ‘command or option is being used, the meaning of less obvious command ‘output, and tips or tricks such as alternate ways of accomplishing the task at hand. + On SLES10, the sux commanc Isuesto| $ sux ~ Password: password ‘copies the HIT-HAGIC-COOKIE- # xclock so that graphical applications ccan be run after switching to another user account. The ‘normal su command does not do this. at aise: her ec eT elet rsaolagA quit ortt nee eS ag lucie somite ont 1) be: darasa aittuse fering ee face eo lly MELinr pnt ier acd ty selabonw « 0 dol pritaiongy Hifi ewan cathe aimabnl amubmtin 2 varit to HA. 3 unre Sour Seana ‘atpatiosd tebele-w Sava nd oe dooms tnkea put pie p henner Free igi phone oe Secon: neha amitogacearet uate ene ants ae Berne ab Tip ai wiper leicttety, stadia’ ania Bena! eal Fevecd aeinpenrclonins SUE: The root directory /bin/ => Essential command binaries Tboot/ = Static files of the boot loader, kernel, and initial RAM disk Idev/ = Device files Jetc/ = Host-specific system configuration ‘Ihome/ => User home directories /1ib/ Essential shared libraries and kernel modules /media/ = Mount point for removable media (LSB addition) /nnt/ -+ Mount point for mounting a filesystem temporarily Jopt/ = Add-on application software packages /root/ = Home directory for the root user /sbin/ = Essential system binaries Isxv/ = Data files for system services (LSB addition) /tmp/ + Temporary files /ust/ = Second hierarchy. Non-essential read-only data (see /usr/ breakout for details) Ivar/ => Variable data files. Includes spool directories and files, administrative and logging data, and transient and temporary files (see /var/ breakout for details) The /usr/ Hierarchy This directory contains application binaries and libraries. No host specific configuration or files should be stored in this directory and as such a single /usr/ filesystem can be shared among multiple ‘computers (usually via NFS). On Linux systems, the most disk space 1-4 will be consumed under the /usr/ hierarchy, perhaps with the exception of data directories: /home/, /srv/, and /var/. Whereas the files and directories in /usr/ can be recreated by reinstalling applications, it is not usually backed up /usr/bin/ = Most user commands Jusr/include/ => Header files included by C programs Jusr/Lib/ = Shared Libraries Jasr/local/ = Local hierarchy (empty after main installation) /asr/sbin/ — Non-vital system binaries Jusr/share/ => Architecture-independent data The /var/ Hierarchy This directory contains data that changes on a regular basis (variable data). When applications run, any temporary or permanent files that are created are normally stored under /var/. Additionally, operating system and application log files are stored here. Best practice is to have /var/ be a separate filesystem so that an errant application can't cause the Toot filesystem to run out of space. /var/cache/ = Application cache data War/Lib/ = Variable state information Ivar/local/ = Variable data for /usr/local Ivar/lock/ = Lock files /var/log/ = Log files and directories Ivar/opt/ = Variable deta for /opt /var/run/ = Data relevant to running processes /wax/spool/ > Application spool data /var/tmp/ = Temporary files preserved between system reboots Linux kernel Virtual Hierarchies Following the Unix philosophy of representing everything as a file, the Linux kermel has special virtual filesystems that provide information and tunables parameters. Since the filesystems are virtual, they don't actually use any space on disk. /proc/ => Contains per process info directories and other tunables /sys/ = Exposes kernel kobject data structures /dev/pts/ => Automates ownership of ttys /dev/shn/ => RAM drive for POSIX shared memory operations, /selinux/ = Information and tunables for SELinux Navigating the Filesystem ‘The cd command changes the current directory. Typing ed /use/ at the command line will change the current working directory to be the Jusr/ directory. To find out the current directory, use the pwd ‘command. When typed at the command line, the output will be an absolute path such as /var/ftp/pub/. You can tell this is an absolute path because it begins with a /. Relative paths can also be used when changing directories. If your current directory is /usr/ and you type ed local/bin your current directory would be changed to /usr/locat/bin/ absolute path = Always begins with a / and describes a location from the top, or root, of the filesystem. relative path > Never begins with a /, and instead describes a location from, or relative to, the current directory. Special Cases When typed alone without any parameters, the ed command takes you to your home directory. Note that if you are logged in as the root user, you will be taken to /root/ directory, which is the root user's home directory, The . character represents the current directory. Typing ed . at the command line has no effect because you will stay in the same directory. Typing cd .. will take you to the parent of the current directory. For example, if you are in /home/foo/ and type ed .., you will end up in the /home/ directory. The .. may be used in a relative Navigating the Filesystem Changing and displaying directories ¢ cd, pwd Absolute vs. relative addressing Special cases ed (without parameters) cd ~username ocd 2d - ee and ss path and multiple times in that path. The - character represents the previous working directory when passed to the ed command. Repeatedly running ed ~ will have the effect of bouncing between two directories. Examples Assuming the following directory structure and current working directory, see the effect of running the listed ed commands § tree /home /home/ == bob cal - jill § pwd 7nome/bob/eal/ jan Sed. # would change to /home/bcb/cal/ $ cd ../feb # would change to /home/bcb/cal/feb/ $ cd w/e # would change to /home/beb/ $ cd .e/ee/e/ GAY $ cd /home/ji1t $ ed ~jill 4 would change to /home/jill/ # would change to /home/}il1/ 4 would change to /home/}il1/ Displaying Directory Contents The ls command is used to list the contents of a directory and is similar to the dir command in MS-DOS / Windows. Here are a few examples of the Ls command starting with the default output. and then showing the effect of various options: $s bin ete lib pub testfile Show all files (including "hidden" dot-files) $ is -a + ++ shiddenfile bin ete pub testfile Show long listing: root root 4896 Jun 1 22:18 bin root root 4896 Jun 1 22:18 etc drwxr-sr-x 2 root ftp 4896 Aug 28 @1:13 pub stw-rw-r-- 1 root root # Aug 31 21:48 testfile Show long listing of all files with human readable file sizes: § 1s -lah total 24k dewxr-xr-x § root root 4.8k Aug 31 21:49 drwar-x1-x 12 root root 4.8k Aug 28 @1:15 1-6 Displaying Directory Contents 1s List directory contents ‘¢ +2 show all files {including . hidden files) © -Llong listings ‘= -d show directories not contents -h human readable file sizes # -R recursively list sub-directories © -8 sort file list by size root root @ Aug shiddenfite root root 4.k Jun bin root root 4.8k Jun ete drwxr-sr-x 2 root ftp 4.8k Aug 2 ab -tw-rv-r-- 1 root root @ Aug testfile Sorting File Listings Output from the Ls command can be sorted a wide variety of ways, as shown in the following examples: Long listing sorted by file size: $ ls -18 ++ + output omitted . . . Long listing sorted file's change timestamp: $ Is -le ++ + output omitted . . . Long listing sorted by file's access (instead of the default modify) timestamp: $ 1s -tu ++. oiltput omitted . . Two Types of Disk Space Data Blocks The file's data. inode Tables ‘* Data about the file's data. ‘Two Types of Disk Space Linux filesystems divide disk space into two fundamental types of storage: data blocks and inode tables. As their name implies, data blocks are used to store data. (Some modem filesystems may use a more powerful format called "extents," but the concept is the same.) Data about the data blocks, sometimes referred to as metadata, is stored in inode tables, (a table containing multiple inodes). Each file on the system uses exactly one inode. When a new filesystem is created, inode tables are pre-allocated. ‘Some Linux filesystems can turn unused data blocks into inode tables, but others cannot. As a result, it is possible to run out of inodes before running out of disk space. Although popular, the extended filesystem (ext2, ext3, and ext4) cannot dynamically allocate new inode tables. The filesystem must be backed up and recreated with more inodes. In contrast, XFS, JFS, and btrfs can dynamically add inodes as needed. The d€ command shows how much disk space each filesystem is using and where it is mounted. It can also show the filesystem type when the =8 option is added. To get a human readable (-h) summary of how much disk space is available run $ af -hT Filesystem Type Size Used avail Uset Mounted on Idev/hda2 ext3 252M 1364 12M 578 / Idev/hda3 ext3 2.86 1.66 238M 88% /usr Idev/hdaS ext3 2.86 386 1.56 208 /usr/local Iéev/ndel ext3 26¢ 9.1G 11G 46% /hone ei rtentne © By default, af uses powers of 1024. To instead use powers of 1000, add the --si option $ af --si /home Filesystem Type Size Used Avail Use’ Mounted on [dev/hdel ext3 226 9.86 126 46% /hone By default, af shows data block usage. To show inode usage instead, add the -i options: $ a€ -hti /home Filesystem Type Size Used Avail Use’ Mounted on fdev/ndel ext3 22M 8888 224 1% /hone 18 Determining Disk Usage With df and du af Report disk space usage per filesystem “h human readable output ¢ =i list inode information instead of biock usage # -T include filesystem type # =-si use powers of 1000 instead of 1024 4u Report disk usage per file and directory © -h human readable sizes =s summarize, only display total for each argument + =x do not inciude files on a different flesystem use powers of 1000 instead of 1024 Determining Disk Usage by File The du command scans the size of all fles in a directory and its sub-directories, then prints a report. When du is not given any arguments, it reports on the current directory. Where du can only report on directories it can read, non-root users will get incorrect totals when scanning directories which do not grant them read or execute permission ‘The following example prints a human readable (-h) summary (-s) of how much disk space the /home/ directory is using: # du -hs /home 9.16 /home By default, du uses powers of 1024. To instead use powers of 1000, add the --si option: # du -hs 9.86 /home si /home To show only files on the current filesystem, excluding filesystems, mounted on sub-directories, add the -x option: $ du -hs /usr 2.86 /usr # du -hsx /usr 1.66 /usr File Ownershi Every file is owned by a specific user (or UID) and a specific group (or GID). The chown command can be used to change just the user, or the user and group of a file. Here is an example of changing the owner of file gane.mov to nobody and its group to users. Note that the use of the 1s =1 command is just to show the change, and is not a necessary step in changing the file's ownership # 1s -1 game.mov srwerw-r-- 1 jh jnh 6551550 Apr 17 12:63 game.mov + chown nobody.users gane.mov # Is -1 game.nov =rw-rv-r-- 1 nobody users 655155@ Apr 17 12:63 game.mov The basic format for the chown command is as follows. chown user.group filenane A colon (:) can be used in place of the period (.) separator character. Also, either the user or group name can be omitted. If the username is omitted (but the separator character is present), then the chown ‘command behaves like the chgrp command, and only the group ownership is changed. If the group name is omitted (but the separator character is present, then the group will be set to the login group of the specified user. If both the group name and the separator character are omitted, then only the username is changed. For example, to change only the owner you could run the following: # chown user filename File Ownership Each file is owned by a specific UID and GID ‘chown - Change the user (UID) ownership ’® Only root can change ownership to another user '* Can also be used to change group at the same time chgrp ~ Modify just the group (GID) ownership, An alternate command to change only the group of a file is the chgrp ‘command. For example: $ chgrp group filename The chgrp command is commonly used by normal users to change the group ownership of their files. The chowm command is normally used only by the root user. Default Group Ownership Each user can be a member of many groups (listed in the /ete/group file under several groups). Only one group will be a user's primary group (listed in the user's entry in /etc/password). When a user creates a file, by default the file will be owned by the user's primary group. If they want the file to be owned by one of their other groups, they must use the chgrp command to modify the group membership. Amore convenient way to accomplish this is to temporarily log-in to another group, making that group your substitute primary group. This. way, any new files that you create will automatically be owned by the desired group, and you will not need to change the group membership manually. Examine the example below and note the use of the newgrp command. § id -gn guru $ touch filel $ ls -l filel -rw-rw-r-- 1 guru guru @ Mar 3 61:12 filel § neugrp projectx § dd -gn projectx $ touch file2 § Is -l file2 -rw-rw-r-- 1 guru projectx @ Mar 3 @1:12 file2 § exit 1-10 Default Group Ownership Newly created files will usually be given GID ownership based on the current active group of the person who creates the file newgrp newgroup - log in to a new group © newly created files will be owned by the new group © users can only change to their own groups ‘ root user can change to any group # exit to switch back File and Directory Permissions Below is sample output from Is -1. Observe the first character of each line: foo and bar are directories (indicated by the d), and meta is, a regular file object (indicated by the ~) $ Is-l sru-rv-r-- 1 guru projectx —@ Mar 3. 61:13 file drwxrwsr-x 3 djk users 4896 Aug 31 28:35 bar drwarwxr-x 2 jah users 4096 Aug 31 28:35 foo srwerw-r-- 1 kbk bk @ Sep 1 69:48 data_file The next nine characters show the file's permissions for user, group, and others (or everyone else) as shown below, with parentheses. added for clarity: =(rw-)(rw-) (r--) 1 Kok kbk @ Sep 1 09:48 data_file ‘The owner and group have read and write access to data_file (rw-), while everyone else have read access only (r--). This is called symbolic representation because letters such as r, w, and x are used to indicate file access permission. File and Directory Permissions Ls -1 List file permissions « first character represents type of file ¢.-,1.b.c.s.p) ‘Then permission sets for: ‘© user -UID that awns the file (sometimes called owner) ‘© group -GID that owns the file ‘= everyone else {sometimes called other) Permissions can be represented in two ways '» symbolic representation (e.g. rwxr~xr-) numeric representation (e.g. €755) Permissions: Numerical Representation Permissions can also be represented in a more compact numerical form where: r= 4; w = 2; x= 1 To find the numerical representation, add the values o' the set permission within each triplet to yield a final 3 digit mode. For example using the previously shown data_file file, adding the numbers in each section results in permissions of 664 as shown here: (2) (ra-) (r--) ~(42-)(42-) (4--) 6 6 4 FACLs If multiple users need access to the same file, they mast be members of the group, or the owner, with permissions to that file. While simple to understand and administer, this is not very flexible. If more than one group of users need to have different permissions for the same file, multiple copies of the same file would need to be created and kept synchronized. File Access Control Lists (FACLs) provide the flexibility to assign permissions for multiple users and groups to a single file, and are matched in the same order as regular Unix permissions, i.e. user, group, then other, (see ACCESS CHECK ALGORITHM of acl(5) for details). 111 Controlling Initial File and Directory Permissions When new files and directories are created in Linux, default permissions are initially set. These permissions are calculated by taking the default permissions of the files/directories created and subtracting the umask value from it. The umask is a four digit octal number that represents the value of permissions that will be masked out. In other words, permissions specified in the umask represent the permissions that will be automatically withheld when you create @ new file. Files and directories have different default permissions when they are created. The default permissions applied to files is 8666. For directories, the default permissions are 8777. The following example. illustrates the process of how initial file permissions are calculated: 666 Default File permission. 962 © Umask value 664 Initial file permission (rw-rw-r- Viewing and Setting the umask Value The umask command is the utility that is provided to view or change the current umask. The umask comes preset in configuration files and to view the current umask issue the command without any options: § umask 9082 The umask may be changed at any time simply by typing umask 112 le Creation Permissions with umask Default permissions for newly created filesystem objects * files: 666 * directories: 777 umask ‘© defines what permissions to withholc from the default permissions ‘© used to display or change your umas« ‘= usually set in the user or system shel dot files ‘* used to provide the user private group (UPG) scheme followed by the new desired value. Notice that the leading digit is not required if itis zero, {and is zero by default: § umask 622 5 umask 8622 [SLES11] Tho folowing apples to SLES1? on In SUSE Linux Enterprise Server, the default umask for all users is set to 822 (defined by pan_unask(8)), SUSE makes all users’ default group the users group. When creating files, write access will only be granted to the user who created the file and not to anyone in the users group. [UB08] The folowing apes to UBC only All users in Ubuntu have a default umask of 822 (defined in /etc/profile). Users are assigned a group name (the default primary group) matching their user name (and typically UID number). It is recommended to change the umask default to 862. This preserves write access by only the file owner, while facilitating the administrative ease of allowing users to share files to other groups without requiring a change of permissicns. It is important to avoid the common inclination of users to grant 777 permissions. Security Implications The default umask for an unprivileged user in Red Hat Enterprise Linux is 882. This means all files created will have permissions of 664: read/write for user and group, and read for others. ‘The root account has a default umask of #22. All files created by the root user have default permissions of 644 (rw-r~ allowing only read access to anyone other than root. Note that a default umask of 682 gives away write permission to all group members. In the User Private Group (UPG) scheme, the default group is a private group with the same group name as the username. The result is that newly created files are only writable by that user, readable by everyone. A more secure configuration would be 9687, restricting access only to the file owner (i.e. 668 for files). Remember that not all Unix systems use UPG, or maintain the same default unask. Care should be taken when running commands such as sep ~xp foo stationY: to make sure that the resulting group ownership and its permissions reflect the same local access, 1-13 Changing File Permissions ‘The chmod command is used to alter the permissions of a file. It may be used to add or remove permissions symbolically. For example, to add execute permissions for the owner of a file you would run: § chmod utx filename Or, to add read and write permissions for the group that owns the file, you would run: § chmod gtrw filename Instead of adding permissions, the symbolic syntax of chmod can also be used to subtract or set to some absolute value as shown in these examples’ § chmod o-w file_name $ chnod u=twx,g=rx,o= file name The chnod command can also explicitly set permissions using a numerical representation, For example, to set permissions on a file to rwxrwxr--, you would run $ chmod 774 file_nane In addition to the standard read, write, and execute permissions, chnod can also set special permissions. These are the setuid bit, the setgid bit, and the sticky bit. The following examples show setting each of these special permissions along with brief descriptions of the effect of those permissions (Note: the effect of these special 1-14 Changing File Permissions chnod Modify file permissions. -R recursively modify permissions supports both numeric and symbolic notation special permissions set UID (SUID) set GID {SGID) sticky Special permissions cause different behavior for files and directories permissions are described more fully in the upcoming pages} $ chmod uts file_name ‘Adds the setuid bit so that, if executabla, this file will execute with the permissions of its owner. $ chmod gts file_nane ‘Adds the setgid bit so that, if executable, this file will execute with the permissions of its group. When this is set on a directory, all files created in the directory will have the same group as the directory. § chmod ott directory name ‘Adds the sticky bit so that users can only delete files from this, directory that they created, $ chmod -R gtk directory_name Adds read, write, and execute permissicns recursively to the directory specified, but does not add the x-bit for non-directories. Changing File Permissions with nautilus Nautilus, the GNOME file manager, can also be used to alter file permissions. To do so, right-click on a fie within a Nautilus window, select Properties, then choose the tab entitled Permissions. Read and write permissions may be modified, and with regular files, the execute bit may be globally set. However special permissions (c.g. setuid) are not included, Access: Others Access: Execute: ‘SELinux Context: Last changed: None 1 Allow executing file as program @ Temporary data < Fri 12 Feb 2010 07:40:28 AM MST 1-15 Special Permissions on Files: SUID New Linux users often wonder why anyone would ever want to use the SUID bit. Having a program that will run with the power of root for any user sounds like a dangerous proposition. AS it turns out, setting the SUID bit on certain programs is not only helpful, it is required. Take, for example, the passwd command. Any user on the system may use the passwd command to change their password. Users’ passwords are stored in the file /etc/shadow. A quick check of the permissions on this file will reveal that it is read / write only to the root user. In order to update the entry for their password, a user must have root level access to the file. This access is provided by setting the SUID bit on the passwd program. The passwd program will only allow a user to change their own password. This limitation is imposed based on the UID of the user running the program, but not on the users security context Special Permissions on Files: SGID When executable files with the SGID bit set are run, they will run with an effective group id (EGID) of the group that owns the executable {instead of the primary group of the user executing the file}. Remove All Unnecessary SUID/SGID Executables Executables with either the SUID, or SGID bits, (or both) set can be 2 security risk. It is especially important to pay attention to SUID root executables. In some cases, there are ways to reconfigure @ program 1-16 SUID and SGID on files ‘The SUID bit changes the security context of an executable An executable is normally run with the security context of the user ‘who invoked it ‘An executable with the SUID bit set runs with the security context of ‘the user who owns it, regardless of the executing user (perhaps changing permissions and ownership on certain files and directories) such that it no longer needs the SUID bit set. If this is possible, do it. If not, evaluate whether or not the program in question is needed. SUID and SGID files can be discovered using the find command. The following finds all files owned by root which have the SUID permission bit set # find / -type £ -user root -perm +4988 ++ « output omitted . . The following finds all files which have she SGID permission bit set: + find / -type £ -perm +2000 ++ + Output omitted . ‘Special Permissions on Directories: SGID If the SGID permission is set on a directory, then files or sub-directories created within that directory inherit the group ‘ownership of the SGID directory. Sub-directories created within the directory will also inherit the SGID special permission propagating this behavior further. Note that although the group ownership and special SGID bit are inherited, all other permissions for newly created directories are determined in the usual fashion using the value of the umask Special Permissions on Directories: Sticky Bit Based on standard Unix filesystem permissions behavior, a user that has write access to a directory will be able to delete files in that directory (even if the file's permissions do not grant them access). With the sticky bit set on a directory, this behavior is overridden and only users who have at least write access to a file will be able to delete it. The /tmp directory is an example of a directory with the sticky bit set itis very important for all users to be able to write to the /tmp directory, but it could cause major problems if any user could delete any other user’ files. SGID and Sticky Bit on Directories sGID * Files or sub-directories created within that directory inherit the group ownership of the SGID directory ‘ Often used to facilitate collaboration among users who need to share files. Sticky bit ‘© Normally in a directory that is world writable, users can delete each others files. Setting the sticky bit overrides this behavior 1-17 User Private Group Scheme Traditionally Unix systems have placed all users into the same default group. Files are created with the default group, so all users have access to each others files via common group membership. To protect users from each other, a default umask of 6822 is used so that only the owner has write access. The problem with this approach is that there is no easy way to shate files with a group. Users have used a file-creation mask of 022 as a result. This practice works well in most cases, but it poses a few difficulties when users of the system need to work on shared projects. To make shared projects possible, project members are normally put into a supplemental project group and given a shared directory owned by that group where they can save shared files. However, because they all have a 022 file-creation mask, they must sometimes use chmod and similar utilities on files after they edit them. To overcome this shortcoming, system administrators could use the. User Private Group scheme (UPG)}. In this configuration every user on the system is placed in a private primary group. Having a private group allows users to have a default file-creation mask of 002 rather ‘than 022. If all users have a 002 file-creation mask, then users working on shared projects no longer need to change file ownership ‘or permissions for new files. [RHELS.4 U804] The folowing applies to AMELS.4 and L804 ony On Red Hat Enterprise Linux and Ubuntu the User Private Group 118 User Private Group Scheme UPG provides a convenient way to share files when workin, group project directory UPG scheme implemented by: 1. placing each user in their own private group. 2. satting the umask to 4862 3. setting the group ownership of the project directory to a ‘commonly shared GID 4, setting the project directory SGID Enabling UPG on SUSE systems set file-creation mask to 002 ‘¢ create a wrapper shell script that creates/uses private groups: Scheme (UPG) is used by default. If you want to disable it and use the traditional Unix approach then ensure that the useradd command is invoked with the -n option. This is a specific option that suppresses the creation and use of the private group. The /ete/bashre script tests if the user is using a User Private Group scheme. If not the /ete/bashre script will set the file-creation mask to 022 [U804] The fofowing applies to UBO4 ony: The default Ubuntu file-creation mask is 422. To change this default for use with the existing User Private Group Scheme, the user should edit their sholl profile. The system administrator may make this change in the /etc/skel/ profile: File: /ete/skel/.profite + {umask 082 Configuring UPG on SUSE Linux Enterprise Server Novell has chosen to follow the traditional Unix approach and place all users in the same default group. Setting up the system to use the UPG scheme requires diligence of the system administrator. For instance, the first user added to the system (UID 1000) will be assigned to the users group (GID 100) by the YaST installer. The useradd command will stil follow the default behavior after the changes below are made, which means all members of the users

You might also like