Linux Lpic Guide 2ed
Linux Lpic Guide 2ed
This guide is an independent publication and is not affiliated with, authorized by, sponsored by, or otherwise approved by the
Linux Professional Institute. You can use and share this guide both in its electronic or in its printed form, provided that you
distribute intact the whole guide (or the single pages) and you do it not-for-profit. For any other use please email me. Feel
free also to contact me for any error, inaccuracy, or unclear point so I can correct it in future editions.
Daniele Raffo
Suggested readings
● Adam Haeder et al., LPI Linux Certification in a Nutshell, O'Reilly
● Evi Nemeth et al., UNIX and Linux System Administration Handbook, O'Reilly
● Heinrich W. Klöpping et al., The LPIC-2 Exam Prep, http://lpic2.unix.nl/
● Mendel Cooper, Advanced Bash-Scripting Guide, http://tldp.org/LDP/abs/html/
● http://www.gnu.org/manual/
● http://www.commandlinefu.com/
● Linux man pages
Index
LVM................................................1 SQL..............................................35 NAT routing...................................69
System boot....................................2 X Window System..........................36 SSH..............................................70
SysV startup sequence.....................3 User accounts................................37 SSH configuration...........................71
Runlevels........................................4 User management..........................38 GnuPG..........................................72
Init scripts......................................5 User privileges...............................39 OpenVPN.......................................73
/etc/inittab......................................6 User messaging.............................40 Key bindings..................................74
Filesystem hierarchy.........................7 Job scheduling...............................41 udev.............................................75
Partitions........................................8 Localization...................................42 Kernel...........................................76
Swap..............................................9 System time..................................43 Kernel management.......................77
/etc/fstab......................................10 Syslog..........................................44 Kernel compile and patching............78
Filesystem operations.....................11 E-mail...........................................45 Kernel modules..............................79
Filesystem maintenance..................12 SMTP............................................46 /proc filesystem.............................80
XFS, ReiserFS and CD-ROM fs..........13 Sendmail & Exim............................47 System recovery............................81
AutoFS..........................................14 Postfix..........................................48 DNS.............................................82
RAID............................................15 Postfix configuration.......................49 DNS configuration..........................83
Bootloader....................................16 Procmail........................................50 DNS zone file.................................84
GRUB configuration........................17 Courier POP configuration................51 Apache.........................................85
GRUB commands...........................18 Courier IMAP configuration..............52 Apache configuration......................86
Package management.....................19 Dovecot login.................................53 Apache virtual hosts.......................87
Backup.........................................20 Dovecot mailboxes.........................54 Apache directory protection.............88
Command line...............................21 Dovecot IMAP & POP.......................55 HTTPS..........................................89
Text filters.....................................22 Dovecot authentication...................56 Apache SSL/TLS configuration..........90
File management...........................23 FTP..............................................57 OpenSSL.......................................91
I/O streams...................................24 CUPS............................................58 CA.pl............................................92
Processes......................................25 Network addressing........................59 Samba..........................................93
Signals.........................................26 Subnetting....................................60 Samba configuration.......................94
Resource monitoring.......................27 Network services............................61 Samba shares................................95
Regexs.........................................28 Network commands........................62 Samba macros...............................96
File permissions.............................29 Network tools................................63 NFS..............................................97
Links............................................30 Network monitoring........................64 /etc/exports..................................98
Find system files............................31 Network configuration.....................65 DHCP............................................99
Shell environment..........................32 TCP Wrapper..................................66 PAM............................................100
Scripting.......................................33 Routing.........................................67 LDAP..........................................101
Flow control...................................34 iptables.........................................68 OpenLDAP...................................102
1/102 LVM
LVM
Logical Volume Management (LVM) introduces an abstraction between physical and logical storage that permits a more
versatile use of filesystems.
LVM makes use of the Linux device mapper feature (/dev/mapper).
Disks, partitions, and RAID devices are made of Physical Volumes, which are grouped into a Volume Group.
A Volume Group is divided into small fixed-size chunks called Physical Extents.
Physical Extents are mapped one-to-one to Logical Extents.
Logical Extents are grouped into Logical Volumes, on which filesystems are created.
pvs Report information about Physical Volumes lvs Report information about Logical Volumes
pvck Check Physical Volume metadata lvchange Change Logical Volume attributes
pvdisplay Display Physical Volume attributes lvscan Scan all disks for Logical Volumes
pvscan Scan all disks for Physical Volumes
pvremove Remove a Physical Volume
pvmove Move the Logical Extents on a Physical
Volume to wherever there are available
Physical Extents (within the Volume Group)
and then put the Physical Volume offline
vgs Report information about Volume Groups
vgck Check Volume Group metadata
vgmerge Merge two Volume Groups
vgimport Import a Volume Group into a system
vgexport Export a Volume Group from a system
vgchange Change Volume Group attributes
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
2/102 System boot
System boot
Boot sequence
POST
Low-level check of PC hardware.
(Power-On Self Test)
BIOS
Detection of disks and hardware.
(Basic I/O System)
GRUB stage 1 is loaded from the MBR and executes GRUB stage 2 from filesystem.
GRUB chooses which OS to boot on.
The chain loader hands over to the boot sector of the partition on which resides the OS.
Chain loader The chain loader also mounts initrd, an initial ramdisk (typically a compressed ext2
GRUB
filesystem) to be used as the initial root device during kernel boot; this make possible to
(GRand Unified
load kernel modules that recognize hard drives hardware and that are hence needed to
Bootloader)
mount the real root filesystem. Afterwards, the system runs /linuxrc with PID 1.
(From Linux 2.6.13 onwards, the system instead loads into memory initramfs, a cpio-
compressed image, and unpacks it into an instance of tmpfs in RAM. The kernel then
executes /init from within the image.)
Kernel decompression into memory.
Kernel execution.
Linux kernel
Detection of devices.
Some newer systems use UEFI (Unified Extensible Firmware Interface). UEFI does not use the MBR boot code; it has
knowledge of partition table and filesystems, and stores its application files required for launch in a EFI System Partition,
mostly formatted as FAT32.
After the POST, the system loads the UEFI firmware which initializes the hardware required for booting, then reads its Boot
Manager data to determine which UEFI application to launch. The launched UEFI application may then launch another
application, e.g. the kernel and initramfs in case of a boot loader like the GRUB.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
3/102 SysV startup sequence
SysV startup sequence
The last script to be run is S99local -> ../init.d/rc.local ; therefore, an easy way to run a specific program on
boot is to add it to this script file.
/etc/init.d/boot.local runs only at boot time, not when switching runlevel.
/etc/init.d/before.local (SUSE) runs only at boot time, before the scripts in the startup directories.
/etc/init.d/after.local (SUSE) runs only at boot time, after the scripts in the startup directories.
To add or remove services at boot sequence: update-rc.d service defaults chkconfig --add service
update-rc.d -f service remove chkconfig --del service
/etc/init.d/service start
service service start (Red Hat) Start a service
rcservice start (SUSE)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
4/102 Runlevels
Runlevels
runlevel
who -r Display the previous and the current runlevel
init runlevel
telinit runlevel Change runlevel
init 0
telinit 0
shutdown -h now Halt the system
halt
poweroff
init 6
telinit 6
shutdown -r now Reboot the system
reboot
shutdown Shut down the system in a secure way: all logged in users are notified via a
message to their terminal, and login is disabled.
This command can be run only by the root user and by those users (if any) listed in
/etc/shutdown.allow
shutdown -h 16:00 message Schedule a shutdown for 4 PM and send a warning message to all logged in users
shutdown -a Non-root users that are listed in /etc/shutdown.allow can use this command to
shut down the system
shutdown -f Skip fsck on reboot
shutdown -F Force fsck on reboot
shutdown -c Cancel an already running shutdown
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
5/102 Init scripts
Init scripts
update-rc.d -f service \ Add a service on the default runlevels; create S30 symlinks for starting
start 30 2 3 4 5 . stop 70 0 1 6 . the service and K70 symlinks for stopping it
chkconfig service on Start the service on default runlevels (via the xinetd super server)
chkconfig service reset Reset the on/off state of the service for all runlevels to whatever is
specified in the init script *
chkconfig service resetpriorities Reset the start/stop priorities of the service for all runlevels to
whatever is specified in the init script *
chkconfig --list service Display current configuration of service (its status and the runlevels in
which it is active)
chkconfig --list List all active services and their current configuration
*
The Linux Standard Base (LSB) defines a format to specify the default values on an init script /etc/init.d/foo :
Default runlevels and S/K symlinks values can be also specified as such:
# chkconfig: 2345 85 15
# description: Foo service
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
6/102 /etc/inittab
/etc/inittab
/etc/inittab
# The default runlevel.
id:2:initdefault:
/etc/inittab describes which processes are started at bootup and during normal operation; it is read and executed by
init at bootup.
All its entries have the form id:runlevels:action:process
1-4 characters, uniquely identifies an entry.
id
For gettys and other login processes it should be equal to the suffix of the corresponding tty
Runlevels for which the specified action must be performed.
runlevels
If empty, action is performed on all runlevels
respawn Process will be restarted when it terminates
Process is started at the specified runlevel and init will wait for its termination
wait
(i.e. execution of further lines of /etc/inittab stops until the process exits)
once Process is executed once at the specified runlevel
boot Process is executed at system boot. Runlevels field is ignored
Process is executed at system boot and init will wait for its termination.
bootwait
Runlevels field is ignored
off Does nothing
ondemand Process is executed when an on-demand runlevel (A, B, C) is called
initdefault Specifies the default runlevel to boot on. Process field is ignored
action
Process is executed at system boot, before any boot or bootwait entries.
sysinit
Runlevels field is ignored
Process is executed when power goes down and an UPS kicks in.
powerfail
init will not wait for its termination
Process is executed when power goes down and an UPS kicks in.
powerwait
init will wait for its termination
powerfailnow Process is executed when power is down and the UPS battery is almost empty
powerokwait Process is executed when power has been restored from UPS
ctrlaltdel Process is executed when init receives a SIGINT via CTRL ALT DEL
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
7/102 Filesystem hierarchy
Filesystem hierarchy
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
8/102 Partitions
Partitions
/dev/hda, /dev/hdb, /dev/hdc first, second, third IDE hard drive
/dev/sda, /dev/sdb, /dev/sdc first, second, third SATA hard drive
/dev/sda1, /dev/sda2, /dev/sda3 first, second, third partition of the first SATA drive
The superblock contains information relative to the filesystem: e.g. filesystem type, size, status, metadata structures.
The Master Boot Record (MBR) is a 512-byte program located in the first sector of the hard disk; it contains information
about hard disk partitions and has the duty of loading the OS.
Most modern filesystems use journaling; in a journaling filesystem, the journal logs changes before committing them to the
filesystem, which ensures faster recovery and less corruption in case of a crash.
mkfs -t fstype device Create a filesystem of the specified type on a partition (i.e. format the partition).
mkfs is a wrapper utility for the actual filesystem-specific maker commands:
mkfs.ext2 mke2fs
mkfs.ext3 mke3fs
mkfs.ext4
mkfs.msdos mkdosfs
mkfs.reiserfs mkreiserfs
mkfs.jfs
mkfs.xfs
mkfs -t ext2 /dev/sda Create a ext2 filesystem on /dev/sda
mkfs.ext2 /dev/sda
mke2fs /dev/sda
mke2fs -j /dev/sda Create a ext3 filesystem (ext2 with journaling) on /dev/sda
mkfs.ext3 /dev/sda
mke3fs /dev/sda
mkfs -t msdos /dev/sda Create a MS-DOS filesystem on /dev/sda
mkfs.msdos /dev/sda
mkdosfs /dev/sda
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
9/102 Swap
Swap
In Linux, the swap space is a virtual memory area (a file or a partition) used as RAM extension. Usually a partition is
preferred because of better performances concerning fragmentation and disk speed. Although listed as filesystem type
0x82, the swap partition is not a filesystem but a raw addressable memory with no structure.
swapon /swapfile Enable a swap file or partition, thus telling the kernel that it can use it now
swapoff /swapfile Disable a swap file or partition
swapon -s Any of these commands can be used to show the sizes of total and used swap areas
cat /proc/swaps
cat /proc/meminfo
free
top
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
10/102 /etc/fstab
/etc/fstab
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
11/102 Filesystem operations
Filesystem operations
df Report filesystem disk space usage
df -h Report filesystem disk space usage in human-readable output
blkid -U 652b786e-b87f-49d2-af23-8087ced0c667 Print the name of the specified partition, given its UUID
blkid -L /boot Print the UUID of the specified partition, given its label
findfs UUID=652b786e-b87f-49d2-af23-8087ced0c667 Print the name of the specified partition, given its UUID
findfs LABEL=/boot Print the name of the specified partition, given its label
e2label /dev/sda1 Print the label of the specified partition, given its name
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
12/102 Filesystem maintenance
Filesystem maintenance
fsck device Check and repair a Linux filesystem (which must be unmounted).
Corrupted files will be placed into the /lost+found of the partition.
The exit code returned is the sum of the following conditions:
0 No errors 8 Operational error
1 File system errors corrected 16 Usage or syntax error
2 System should be rebooted 32 Fsck canceled by user
4 File system errors left uncorrected 128 Shared library error
fsck is a wrapper utility for actual filesystem-specific checker commands:
fsck.ext2 e2fsck
fsck.ext3
fsck.ext4
fsck.msdos
fsck.vfat
fsck.cramfs
fsck Check and repair serially all filesystems listed in /etc/fstab
fsck -As
fsck -f /dev/sda1 Force a filesystem check on /dev/sda1 even if it thinks is not necessary
fsck -y /dev/sda1 During filesystem repair, do not ask questions and assume that the
answer is always yes
fsck.ext2 -c /dev/sda1 Check a ext2 filesystem, running the badblocks command to mark all
e2fsck -c /dev/sda1 bad blocks and add them to the bad block inode to prevent them from
being allocated to files or directories
Most hard drives feature the Self-Monitoring, Analysis and Reporting Technology (SMART) whose purpose is to monitor the
reliability of the drive, predict drive failures, and carry out different types of drive self-tests.
The smartd daemon attempts to poll this information from all drives every 30 minutes, logging all data to syslog.
smartctl -a /dev/sda Print SMART information for drive /dev/sda
smartctl -s off /dev/sda Disable SMART monitoring and log collection for drive /dev/sda
smartctl -t long /dev/sda Begin an extended SMART self-test on drive /dev/sda
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
13/102 XFS, ReiserFS and CD-ROM fs
XFS, ReiserFS and CD-ROM fs
xfs_growfs [options] mountpoint Expand an XFS filesystem (there must be at least one spare new disk
partition available)
xfsdump -v silent -f /dev/tape / Dump the root of a XFS filesystem to tape, with lowest level of verbosity.
Incremental and resumed dumps are stored in the inventory database
/var/lib/xfsdump/inventory
xfsrestore -f /dev/tape / Restore a XFS filesystem from tape
xfsdump -J - / | xfsrestore -J - /new Copy the contents of a XFS filesystem to another directory (without
updating the inventory database)
mkisofs -r -o cdrom.img data/ Create a CD-ROM image from the contents of the target directory.
Enable Rock Ridge extension and set all content on CD to be public
readable (instead of inheriting the permissions from the original files)
CD-ROM filesystems
Filesystem Commands
ISO9660 mkisofs Create a ISO9660 filesystem
UDF (Universal Disk Format) mkudffs Create a UDF filesystem
udffsck Check a UDF filesystem
wrudf Maintain a UDF filesystem
cdrwtool Manage CD-RW drives (disk format, read/write speed, ...)
HFS (Hierarchical File System)
CD-ROM filesystem extensions
Rock Ridge Contains the original file information (e.g. permissions, filename) for MS Windows 8.3 filenames
MS Joliet Used to create more MS Windows friendly CD-ROMs
El Torito Used to create bootable CD-ROMs
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
14/102 AutoFS
AutoFS
AutoFS permits automounting of filesystems, even for nonprivileged users.
AutoFS is composed of the autofs kernel module that monitors specific directories for attempts to access them, and in this
case signals the automount userspace daemon which mounts the directory when it needs to be accessed and unmounts it
when no longer accessed.
The /net/nfsserver/ tree allows nonprivileged users to automatically access any nfsserver.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
15/102 RAID
RAID
RAID levels
Level Description Storage capacity
RAID 0 Striping (data is written across all member disks). Sum of the capacity of member disks
High I/O but no redundancy
RAID 1 Mirroring (data is mirrored on all disks). Capacity of the smaller member disk
High redundancy but high cost
RAID 4 Parity on a single disk. Sum of the capacity of member disks,
I/O bottleneck unless coupled to write-back caching minus one
RAID 5 Parity distributed across all disks. Sum of the capacity of member disks,
Can sustain one disk crash minus one
RAID 6 Double parity distributed across all disks. Sum of the capacity of member disks,
Can sustain two disk crashes minus two
Linear RAID Data written sequentially across all disks. Sum of the capacity of member disks
No redundancy
mdadm -C /dev/md0 -l 5 \ Create a RAID 5 array from three partitions and a spare.
-n 3 /dev/sdb1 /dev/sdc1 /dev/sdd1 \ Partitions type must be set to 0xFD.
-x 1 /dev/sde1 Once the RAID device has been created, it must be formatted e.g. via
mke2fs -j /dev/md0
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
16/102 Bootloader
Bootloader
Non-GRUB bootloaders
LILO Obsolete. Small bootloader that can be placed in the MBR or the boot sector of a partition.
(Linux Loader) The configuration file is /etc/lilo.conf (run /sbin/lilo afterwards to validate changes).
SYSLINUX Able to boot from FAT and NTFS filesystems e.g. floppy disks and USB drives.
Used for boot floppy disks, rescue floppy disks, and Live USBs.
ISOLINUX Able to boot from CD-ROM ISO 9660 filesystems.
Used for Live CDs and bootable install CDs.
EXTLINUX General-purpose bootloader like LILO or GRUB. Now merged with SYSLINUX.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
17/102 GRUB configuration
GRUB configuration
GRUB (Grand Unified Bootloader) is the standard boot manager on modern Linux distros, which may use either version:
GRUB Legacy or GRUB 2.
GRUB Stage 1 (446 bytes), as well as the partition table (64 bytes) and the boot signature (2 bytes), is stored in the 512-
byte MBR. It then accesses the GRUB configuration and commands available on the filesystem, usually on /boot/grub .
# Linux Debian
menuentry "Debian 2.6.36-experimental" {
set root=(hd0,1)
linux (hd0,1)/bzImage-2.6.36-experimental ro root=/dev/hda6
}
# Windows
menuentry "Windows" {
set root=(hd0,2)
chainloader +1
}
This file must not be edited manually. Instead, edit the files in /etc/grub.d/ (they are scripts that will be run in
order) and the file /etc/default/grub (the configuration file for menu display settings), then run update-grub .
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
18/102 GRUB commands
GRUB commands
The GRUB menu, presented at startup, permits to choose the OS or kernel to boot:
ENTER Boot the selected GRUB entry
C Get a GRUB command line
E Edit the selected GRUB entry (e.g. to edit kernel parameters in order to boot in single-user emergency mode,
or to change IRQ or I/O port of a device driver compiled in the kernel)
B Boot the GRUB entry once it has been modified
P Bring up the GRUB password prompt (necessary if a GRUB password has been set)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
19/102 Package management
Package management
Package management Debian Red Hat
Text-based UI or
aptitude
Manage packages and dependencies
graphical tools dselect
Convert a RPM package to DEB and installs it. alien -i package.rpm
Other tools Might break the package system!
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
20/102 Backup
Backup
dd if=/dev/sda of=/dev/sdb Copy the content of one hard disk over another, byte by byte
dd if=/dev/sda1 of=sda1.img Create the image of a partition
dd if=/dev/cdrom of=cdrom.iso bs=2048 Create an ISO file from a CD-ROM, using a block size of 2 Kb
rsync -rzv /home /tmp/bak Synchronize the content of the home directory with the temporary
rsync -rzv /home/ /tmp/bak/home backup directory. Use compression, verbosity, and recursion.
For all transfers subsequent to the first, rsync only copies the blocks
that have changed, making it a very efficient backup solution in terms
of speed and bandwidth
rsync -avz /home [email protected]:/backup/ Synchronize the content of the home directory with the backup
directory on the remote server, using SSH. Use archive mode (operates
recursively and preserves owner, group, permissions, timestamps, and
symlinks)
ls | cpio -o > myarchive.cpio Create an archive of all files that are on the current directory
ls | cpio -oF myarchive.cpio
find /home/ | cpio -o > homedirs.cpio Create an archive of all users' home directories
cpio -id < myarchive.cpio Extract all files from the archive, recreating the structure of directories
cpio -i -t < myarchive.cpio List the contents of an archive file without extracting it
Tape libraries
/dev/st0 First SCSI tape device
Devices
/dev/nst0 First SCSI tape device (no-rewind device file)
Utility for magnetic tapes mt -f /dev/nst0 asf 3 Position the tape at the start of 3rd file
mtx -f /dev/sg1 status Display status of tape library
mtx -f /dev/sg1 load 3 Load tape from slot 3 to drive 0
mtx -f /dev/sg1 unload Unload tape from drive 0 to original slot
Utility for tape libraries mtx -f /dev/sg1 transfer 3 4 Transfer tape from slot 3 to slot 4
mtx -f /dev/sg1 inventory Force robot to rescan all slots and drives
mtx -f /dev/sg1 inquiry Inquiry about SCSI media device
(Medium Changer = tape library)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
21/102 Command line
Command line
man 7 command Show man page 7 for a command
vlock
away Lock the virtual console (terminal)
Almost all Linux commands accept the option -v (verbose), and many commands also accept the option -vv (very verbose).
Bash shortcuts
. Current directory
.. Parent directory
~ Home directory of current user
~jdoe Home directory of user jdoe
~- Previously used directory
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
22/102 Text filters
Text filters
cat myfile Print a text file
cat myfile1 myfile2 > myfile3 Concatenate text files
head myfile Print the first 10 lines of a text file
head -n 10 myfile
tail myfile Print the last 10 lines of a text file
tail -n 10 myfile
tail -f myfile Output appended data as the text file grows; useful to read logs in realtime
tac myfile Print a text file in reverse, from last line to first line
fmt -w 75 myfile Format a text file so that each line has a max width of 75 chars
pr myfile Format a text file for a printer
join myfile1 myfile2 Join lines of two text files on a common field
paste myfile1 myfile2 Merge lines of text files
split -l 1 myfile Split a text file into 1-line files (named xaa, xab, xac, ...)
uniq myfile Print the unique lines of a text file, omitting consecutive identical lines
sort myfile Sort alphabetically the lines of a text file
expand myfile Convert tabs into spaces
unexpand myfile Convert spaces into tabs
cut -d: -f3 myfile Cut the lines of a file, considering : as the delimiter and printing only the 3rd field
cut -d: -f1 /etc/passwd Print the list of user accounts in the system
sed s/foo/bar/ myfile Stream Editor: Replace the first occurrence of foo with bar
sed s/foo/bar/g myfile Replace all occurrences of foo with bar
tr a-z A-Z <myfile Translate characters: Convert all lowercase into uppercase in a text file
tr [:lower:] [:upper:] <myfile
tr -d 0-9 <myfile Delete all digits from a text file
tr -d [:digit:] <myfile
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
23/102 File management
File management
cp myfile myfile2 Copy a file
cp myfile mydir/ Copy a file to a directory
Common options:
mv myfile myfile2 Rename a file -i Prompt before overwriting/deleting files (interactive)
-f Don't ask before overwriting/deleting files (force)
mv myfile mydir/ Move a file to a directory
rm myfile Delete a file
Brace expansion
cp myfile.{txt,bak} Copy myfile.txt to myfile.bak
touch myfile_{a,b,c} Create myfile_a, myfile_b, myfile_c
touch {a..h} Create 8 files named a b c d e f g h
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
24/102 I/O streams
I/O streams
In Linux, everything is a file. File descriptors are automatically associated to any process launched.
File descriptors
# Name Type Default device
0 Standard input (stdin) Input text stream Keyboard
1 Standard output (stdout) Output text stream Terminal
2 Standard error (stderr) Output text stream Terminal
mail [email protected] < myfile Redirect a file to the stdin of command mail
(i.e. mail a file to the specified email address)
ls > myfile 2>&1 Redirect both stdout and stderr of command ls to a file
ls &> myfile
ls | tee myfile tee reads from stdin and writes both to stdout and a file
(i.e. write content of current directory to screen and to a file at the same time)
ls | tee -a myfile tee reads from stdin and appends both to stdout and a file
ls foo* | xargs cat xargs calls the cat command multiple times for each argument found on stdin
(i.e. print the content of every file whose filename starts by foo)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
25/102 Processes
Processes
Any application/program/script that runs on the system is a process. Signals are used for inter-process communication.
Each process has an unique PID (Process ID) and a PPID (Parent Process ID); when a process spawns a child, the process
PID is assigned to the child's PPID.
The /sbin/init process, run at bootup, has PID 1. It is the ancestor of all processes and becomes the parent of any
orphaned process. It is also unkillable; should it die, the kernel will panic.
When a child process dies, its status becomes EXIT_ZOMBIE and a SIGCHLD is sent to the parent. The parent should then
call the wait() system call to read the dead process' exit status and other info; until that moment, the child process
remains a zombie.
jobs List all jobs (i.e. processes whose parent is a Bash shell)
CTRL Z Suspend a job, putting it in the stopped state (send a SIGTSTP)
bg %1 Put job #1 in the background (send a SIGCONT)
fg %1 Resume job #1 in the foreground and make it the current job (send a SIGCONT)
kill %1 Kill job #1
When a Bash shell is terminated cleanly via exit, its jobs will became child of the Bash's parent and will continue running.
When a Bash is killed instead, it issues a SIGHUP to his children which will terminate.
nohup myscript.sh Prevent a process from receiving a SIGHUP (hence terminating) when its parent Bash dies
To each process is associated a niceness value: the lower the niceness, the higher the priority.
The niceness value ranges from -20 to 19, and a newly created process has a default niceness of 0.
Unprivileged users can modify a process' niceness only within the range from 1 to 19.
nice -n -5 command Start a command with a niceness of -5 (if niceness is omitted, a default value of 10 is used)
renice -5 command Change the niceness of a running command to -5
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
26/102 Signals
Signals
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
27/102 Resource monitoring
Resource monitoring
iostat Print a report about CPU utilization, device utilization, and network filesystem.
The first report shows statistics since the system boot; subsequent reports will show
statistics since the previous report
vmstat Print a report about process usage, virtual memory, blocks I/O, interrupts, and CPU time
vmstat 1 5 Print a report every second, for 5 times
free Show the amount of free and used memory in the system
uptime Show how long the system has been up, how many users are connected, and the system
load averages for the past 1, 5, and 15 minutes
Monitoring tools
collectd System statistics collector
Nagios System monitor and alert
MRTG Network load monitor
Cacti Network monitor
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
28/102 Regexs
Regexs
Regular expressions
^ Beginning of a line
$ End of a line
\< \> Word boundaries (beginning of line, end of line, space, or punctuation mark)
. Any character, except newline
[abc] Any of the characters specified
[a-z] Any of the characters in the specified range
[^abc] Any character except those specified
* Zero or more times the preceding regex
+ One or more times the preceding regex
? Zero or one time the preceding regex
{5} Exactly 5 times the preceding regex
{3,6} Between 3 and 6 times the preceding regex
| The regex either before or after the vertical bar
( ) Grouping, to be used for back-references.
\1 expands to the first match, \2 for the second, and so on until \9
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
29/102 File permissions
File permissions
- r w x r w x r w x
--==regular
regularfile
file user
user(owner)
(owner) group
group others
others
dd==directory
directory
ll==symbolic
symboliclink
link rr==read
read rr==read
read rr==read
read
ss==Unix
Unixdomain
domainsocket
socket ww==write
write ww==write
write ww==write
write
pp==named
namedpipe
pipe xx==execute
execute xx==execute
execute xx==execute
execute
cc==character
characterdevice
devicefile
file ss==setUID
setUIDand
andexecute
execute ss==setGID
setGIDand
andexecute
execute tt==sticky
stickyand
andexecute
execute
bb==block
blockdevice
devicefilefile SS==setUID
setUID andnot
and notexecute
execute SS==setGID
setGID andnot
and notexecute
execute TT==sticky
sticky andnot
and notexecute
execute
Read group: 40 chmod g+r Can open and read the file Can list directory content
others: 4 chmod o+r
chmod +wx file Add write and execute permission to everybody (user, group, and others)
chmod -R o+r file Add recursively read permission to others
chmod o-x file Remove execute permission from others
The chmod, chown, and chgrp commands accept the option -R to recursively change properties of files and directories.
Set the permission mask to 022, hence masking write permission for group and others.
umask 022 Linux default permissions are 0666 for files and 0777 for directories. These base permissions are
ANDed with the inverted umask value to calculate the final permissions of a new file or directory.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
30/102 Links
Links
A Linux directory contains a list of structures which are associations between a filename and an inode.
An inode contains all file metadata: file type, permissions, owner, group, size, access/change/modification/deletion times,
number of links, attributes, ACLs, and address where the actual file content (data) is stored.
An inode does not contain the name of the file; this information is stored in the directory the file is in.
Yes No
Is the link still valid if the original
(because the link references the inode (the path now references a non-
file is moved or deleted
the original file pointed to) existent file)
No
Can link to a file in another
(because inode numbers make sense Yes
filesystem
only within a determinate filesystem)
Can link to a directory No Yes
Reflect the original file's permissions,
Link permissions rwxrwxrwx
even when these are changed
Link attributes - (regular file) l (symbolic link)
Inode number The same as the original file A new inode number
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
31/102 Find system files
Find system files
find / -name "foo*" Find all files, starting from the root dir, whose name start with foo
find / -name "foo*" -print Find all files whose name start with foo and print their path
find / -name "foo*" -exec chmod 700 {} \; Find all files whose name start with foo and apply permission 700 to
all of them
find / -name "foo*" -ok chmod 700 {} \; Find all files whose name start with foo and apply permission 700 to
all of them, asking for confirmation before each file
find / -perm -4000 -type f Find all files with SUID set
(a possible security risk, because a shell with SUID root is a backdoor)
find / -perm -2000 -type f Find all files with SGID set
whereis command Locate the binary, source, and manpage files for command
whereis -b command Locate the binary files for command
whereis -s command Locate the source files for command
whereis -m command Locate the manpage files for command
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
32/102 Shell environment
Shell environment
MYVAR=myvalue
((MYVAR=myvalue)) Set a variable
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
33/102 Scripting
Scripting
Scripts must start with the shebang line #! /bin/bash indicating the location of the script interpreter.
Script execution
source myscript.sh Script execution takes place in the same shell. Variables defined and
. myscript.sh exported in the script are seen by the shell when the script exits
bash myscript.sh
Script execution spawns a new shell
./myscript.sh (file must be executable)
MYVAR=`date`
MYVAR=$(date) Assign to a variable the output resulting from a command
zenity Display GTK+ graphical dialogs for user messages and input
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
34/102 Flow control
Flow control
test $MYVAR = "myvalue" && mycommand
[ $MYVAR = "myvalue" ] && mycommand Perform a test; if it holds true, the command is executed
if [ $MYVAR = "myvalue" ]; then mycommand; fi
Test operators
Integer operators File operators Expression operators
-eq Equal to -e or -a Exists -a Logical AND
-ne Not equal to -d Is a directory -o Logical OR
-lt Less than -b Is a block special file ! Logical NOT
-le Less than or equal to -c Is a character special file \( \) Priority
-gt Greater than -f Is a regular file
-ge Greater than or equal to -r Is readable
String operators -w Is writable
-z Is zero length -x Is executable
-n or nothing Is non-zero length -s Is non-zero length
= or == Is equal to -u Is SUID
!= Is not equal to -g Is SGID
< Is alphabetically before -k Is sticky
> Is alphabetically after -h Is a symbolic link
expr $MYVAR = "39 + 3" Evaluate an expression; the variable will hold the value 42
expr string : regex Return the length of the substring matching the regex
expr string : \(regex\) Return the substring matching the regex
Evaluation operators
= Equal to + Plus string : regex
match string regex String matches regex
!= Not equal to - Minus
< Less than \* Multiplied by substr string pos length Substring
<= Less than or equal to / Divided by index string chars Index of any chars in string
> Greater than % Remainder length string String length
>= Greater than or equal to
Tests
if [test 1] case $VAR in
then [pattern 1]) [command 1] ;;
[command block 1] [pattern 2]) [command 2] ;;
elif [test 2] *) [command 3]
then esac
[command block 2]
else
[command block 3]
fi
Loops
while [test] for $I in [list] break Terminate a loop
do do
[command block] [command operating on $I] continue Jump to the next iteration
done done
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
35/102 SQL
SQL
SQL syntax
USE MyDatabase; Choose which database to use
SHOW DATABASES; Show all existing databases
SHOW TABLES; Show all tables from the selected database
DESC tableCustomers; Describe the columns of a table
SELECT * FROM tableCustomers; Select all columns from the table
SELECT * FROM tableCustomers ORDER BY columnLastname LIMIT 5; Select only the first 5 records of customers
as ordered by last name
SELECT columnFirstname, columnLastname FROM tableCustomers WHERE Select only first and last name of customers
columnZipcode = 00123; whose zip code is 00123
SELECT columnCustomerID, SUM(columnSalary) FROM tablePayments Select all salary payments grouped by
GROUP BY columnCustomerID; customer ID, summed up
SELECT tableCustomers.columnLastname, tablePayments.columnAmount Perform a join by selecting data from two
FROM tableCustomers, tablePayments WHERE tables that are linked
tableCustomers.columnCustomerID = tablePayments.columnCustomerID;
INSERT INTO tableCustomers Insert new data
(columnFirstname,columnLastname,columnDOB)
VALUES (Arthur,Dent,1959-08-01);
UPDATE tableCustomers SET columnCity = 'London' WHERE Modify data
columnZipcode = 00789;
SHOW GRANTS FOR 'user'@'localhost'; Show permissions for a user
GRANT ALL PRIVILEGES ON MyDatabase.* TO 'user'@'localhost'; Grant permissions to a user
REVOKE ALL PRIVILEGES FROM 'user'@'localhost'; Revoke permissions from a user
SELECT Host,User FROM mysql.user; List MySQL users
CREATE USER 'user'@'localhost' IDENTIFIED BY 'p4ssw0rd'; Create a MySQL user
SET PASSWORD FOR 'user'@'localhost' = PASSWORD('p4ssw0rd'); Set a password for a MySQL user
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
36/102 X Window System
X Window System
Display Managers
Display Manager Configuration files Display Manager greeting screen
/etc/init.d/xdm start
/etc/init.d/gdm start Start the X Display Manager
/etc/init.d/kdm start
xorgconfig Configure X (text mode) (Debian)
Xorg -configure Configure X (text mode) (Red Hat)
xorgcfg Configure X (graphical mode) (Debian)
system-config-display Configure X (graphical mode) (Red Hat)
X -version Show which version of X is running
xdpyinfo Display information about the X server
xwininfo Display information about windows
xhost + 10.3.3.3 Add 10.3.3.3 to the list of hosts allowed to make X connections to the local machine
xhost - 10.3.3.3 Remove 10.3.3.3 from the list of hosts allowed to make X connections to the local machine
mkfontdir Catalog the newly installed fonts in the new directory
xset fp+ /usr/local/fonts Dynamically add the newly installed fonts in /usr/local/fonts to the X server
xfs Start the X font server
fc-cache Install fonts and build font information cache
switchdesk gde Switch to the GDE Display Manager at runtime
$DISPLAY Environment variable defining the display name of the X server, in the form
hostname:displaynumber.screennumber
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
37/102 User accounts
User accounts
root:x:0:0:/root:/bin/bash
bin:x:1:1:/bin:/bin/bash
jdoe:x:500:100:John Doe,,555-1234,,:/home/jdoe:/bin/bash
1 2 3 4 5 6 7
1 Login name
2 Encrypted password (obsolete), or x if password is in /etc/shadow
3 UID – User ID (UID 0 is superuser; by convention UIDs 1-99 are system accounts, UIDs above are regular users)
5 GECOS field – Information about the user: Full name, Room number, Work phone, Home phone, Other
7 Login shell (can be set to /bin/false to prevent a user from logging in)
root:fZPe54/Kldu6D32pl0X/A:15537:0:99999:7:::
bin:*:15637:0:99999:7:::
jdoe:!hsp\8e3jCUdw9Ru53:15580:0:99999:7::15766:
1 2 3 4 5 67 8 9
1 Login name
3 Date of last password change (in number of days since 1 January 1970)
4 Days before password may be changed; if 0, user can change the password at any time
9 Reserved field
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
38/102 User management
User management
useradd -m jdoe Create a user account, creating and populating his homedir from /etc/skel
useradd -mc "John Doe" jdoe Create a user account, specifying his full name
useradd -ms /bin/ksh jdoe Create a user account, specifying his login shell
useradd -D Show default values (specified in /etc/login.defs) for user account creation
usermod -c "Jonas Doe" jdoe Modify the GECOS field of a user account
(usermod accepts many
usermod -L jdoe Lock a user account
useradd options)
usermod -U jdoe Unlock a user account
chage -E 2013-02-14 jdoe Change the password expiration date, locking the account at that date
chage -d 13111 jdoe Change the date (in number of days since 1 January 1970) of last password change
chage -d 0 jdoe Force the user to change password at his next login
chage -M 30 jdoe Change the max number of days during which a password is valid
chage -m 7 jdoe Change the min number of days between password changes
chage -W 15 jdoe Change the number of days before password expiration that the user will be warned
chage -I 3 jdoe Change the number of days after password expiration before the account is locked
chage -l jdoe List password aging information for a user
adduser
deluser
addgroup User-friendly front-ends for user and group management (Debian)
delgroup
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
39/102 User privileges
User privileges
User control
who am i
whoami Print your effective user ID
fail2ban Scan authentication logs and temporarily ban IP addresses (via firewall rules) that have
too many failed password logins
su and sudo
su jdoe Run a shell as the specified user. If user is not specified, assume root
su -c "fdisk -l" Pass a single command to the shell
su - Ensure that the spawned shell is a login shell, hence running login scripts and setting
su -l the correct environment variables. Recommended option
sudo fdisk -l Run a command as root. Sudo commands are logged via syslog
sudo -ujdoe fdisk -l Run a command as another user
sudoedit /etc/passwd Edit a protected file. It is recommended to use this instead of allowing users to sudo
sudo -e /etc/passwd text editors as root, which will arise security problems if the editor spawns a shell
visudo Edit /etc/sudoers, the configuration file that specifies access rights to sudo
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
40/102 User messaging
User messaging
echo "Message" | write jdoe Write a message to the terminal of user jdoe
echo "Message" | wall Write a message to the terminal of all logged in users
talk jdoe Open an interactive chat session with user jdoe
mesg y Allow the other users to message you via write, wall, and talk
chmod g+w $(tty)
mesg n Disallow the other users to message you via write, wall, and talk
chmod g-w $(tty)
mesg Display your current message permission status
mesg works by enabling/disabling the group write permission of your terminal device, which is owned by system group tty.
The superuser is always able to message users.
/etc/issue Message to be printed before the login prompt. Can contain these escape codes:
\b Baudrate of line \o Domain name
\d Date \r OS release number
\s System name and OS \t Time
\l Terminal device line \u Number of users logged in
\m Architecture identifier of machine \U "n users" logged in
\n Nodename a.k.a. hostname \v OS version and build date
/etc/motd Message to be printed after a successful login, before execution of the login shell
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
41/102 Job scheduling
Job scheduling
cron – repeated scheduled execution
/etc/crontab
/etc/anacrontab
Anacron jobs are run by crond, and permit the execution of periodic jobs on a machine that is not always running, such as a
laptop.
If the job has not been executed in the last period, the system waits for delay and then executes command.
If /etc/cron.allow exists, only users listed therein can access the service.
If /etc/cron.deny exists, all users except those listed therein can access the service.
If none of these files exist, all users can access the service.
If /etc/at.allow exists, only users listed therein can access the service.
If /etc/at.deny exists, all users except those listed therein can access the service.
If none of these files exist, no user except root can access the service.
at -d 3
atrm 3 Remove job number 3 from the list
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
42/102 Localization
Localization
LC_MESSAGES Language and encoding of system messages and user The list of supported locales is stored in
input /usr/share/i18n/SUPPORTED
LC_PAPER Paper size
LC_NAME Personal name formats
LC_ADDRESS Geographic address formats
LC_TELEPHONE Telephone number formats
LC_MEASUREMENT Measurement units (metric or others)
LC_IDENTIFICATION Metadata about locale
LC_ALL Special variable overriding all others
apt-get install manpages-it language-pack-it Install a different locale (system messages and manpages)
iconv -f IS6937 -t IS8859 filein > fileout Convert a text file from a codeset to another
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
43/102 System time
System time
tzselect
tzconfig Set the timezone, stored in /etc/timezone
dpkg-reconfigure tzdata (Debian)
Timezone is also set as a symbolic link from /etc/localtime to the correct timezone file in /usr/share/zoneinfo/
ntpd NTP daemon, keeps the clock in sync with Internet time servers
ntpd -q Synchronize the time once and quit
ntpd -g Force NTP to start even if clock is off by more than the panic threshold (1000 secs)
ntpd -n -g -q Start NTP as a non-daemon, force set the clock, and quit
ntpdate timeserver Synchronizes the clock with the specified time server
ntpdate -b timeserver Brutally set the clock, without waiting for a slow adjusting
ntpdate -q timeserver Query the time server without setting the clock
hwclock --show
hwclock -r Show the hardware clock
hwclock --hctosys
hwclock -s Set the system time from the hardware clock
hwclock --systohc
hwclock -w Set the hardware clock from system time
hwclock --utc Indicate that the hardware clock is kept in Coordinated Universal Time
hwclock --localtime Indicate that the hardware clock is kept in local time
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
44/102 Syslog
Syslog
syslogd Daemon logging events from user processes
Syslog logging facility:
klogd Daemon logging events from kernel processes
/etc/syslog.conf
# facility.level action
*.info;mail.none;authpriv.none /var/log/messages
authpriv.* /var/log/secure
mail.* /var/log/maillog
*.alert root
*.emerg *
local5.* @10.7.7.7
local7.* /var/log/boot.log
† deprecated
logger -p auth.info "Message" Send a message to syslogd with the specified facility and priority
logrotate Rotate logs (by gzipping, renaming, and eventually deleting old logfiles) according to
/etc/logrotate.conf
tail -f /var/log/messages Print the last lines of the message log file, moving forward as the file grows (i.e. read
logs in real-time)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
45/102 E-mail
E-mail
e.g. Alpine, Mutt e.g. Sendmail, Exim, Postfix, qmail e.g. Procmail, SpamAssassin
~/.forward Mail address(es) to forward the user's mail to, or mail commands
/etc/aliases
/etc/mail/aliases Aliases database for users on the local machine. Each line has syntax alias: user
newaliases
sendmail -bi Update the aliases database; must be run after any change to /etc/aliases
mailq
exim4 -bp Examine the mail queue
Mailbox formats
Each mail folder is a single file, storing multiple email messages.
mbox $HOME/Mail/myfolder
Advantages: universally supported, fast search inside a mail folder.
Disadvantages: issues with file locking, possible mailbox corruption.
Each mail folder is a directory, and contains the subdirectories /cur, /new, and /tmp.
Each email message is stored in its own file with an unique filename ID.
The process that delivers an email message writes it to a file in the tmp/ directory,
and then moves it to new/. The moving is commonly done by hard linking the file to
new/ and then unlinking the file from tmp/, which guarantees that a MUA will not see
Maildir a partially written message as it never looks in tmp/. $HOME/Mail/myfolder/
When the MUA finds mail messages in new/ it moves them to cur/.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
46/102 SMTP
SMTP
SMTP commands
220 smtp.example.com ESMTP Postfix Initiate the conversation and
HELO abc.example.org HELO abc.example.org
identify client host to server
250 Hello abc.example.org, glad to meet you
MAIL FROM: [email protected] EHLO abc.example.org Like HELO, but tell server to
250 Ok use Extended SMTP
RCPT TO [email protected]
250 Ok MAIL FROM: [email protected] Specify mail sender
RCPT TO [email protected] RCPT TO: [email protected] Specify mail recipient
250 Ok
DATA Specify data to send. Ended
354 End data with <CR><LF>.<CR><LF> DATA
with a dot on a single line
From: Alice <[email protected]>
To: Bob <[email protected]> QUIT
RSET Disconnect
Cc: Eve <[email protected]>
Date: Wed, 13 August 2014 18:02:43 -0500
Subject: Test message
HELP List all available commands
NOOP Empty command
This is a test message.
. Verify the existence of an e-
250 OK id=1OjReS-0005kT-Jj
VRFY [email protected] mail address (this command
QUIT should not be implemented,
221 Bye for security reasons)
EXPN mailinglist Check mailing list membership
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
47/102 Sendmail & Exim
Sendmail & Exim
/etc/exim.conf
Exim4 configuration file
/usr/local/etc/exim/configure (FreeBSD)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
48/102 Postfix
Postfix
Postfix is a fast, secure, easy to configure, open source MTA intended as a replacement for Sendmail. It is implemented as
a set of small helper daemons, most of which run in a chroot jail with low privileges. The main ones are:
master Postfix master daemon, always running; starts the other daemons when necessary
nqmgr Queue manager for incoming and outgoing mail, always running
smtpd SMTP daemon for incoming mail
smtp SMTP daemon for outgoing mail
bounce Manager of bounce messages
cleanup Daemon that verifies the syntax of outgoing messages before they are handed to the queue manager
local Daemon that handles local mail delivery
virtual Daemon that handles mail delivery to virtual users
postmap dbtype:textfile Create a hashed map file of database type dbtype from textfile
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
49/102 Postfix configuration
Postfix configuration
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
50/102 Procmail
Procmail
Procmail is a regex-based MDA whose main purpose is to preprocess and sort incoming email messages.
It is able to work both with the standard mbox format and the Maildir format.
To have all email processed by Procmail, the ~/.forward file may be edited to contain:
"|exec /usr/local/bin/procmail || exit 75"
# Blacklisted by SpamAssassin
Flag: file locking not necessary because blackholing to /dev/null
:0
* ^X-Spam-Status: Yes Condition: match SpamAssassin's specific header
/dev/null Destination: delete the message
:0B:
* hacking Flag: match body of message instead of headers
$MAILDIR/Geekstuff
:0HB:
* hacking Flag: match either headers or body of message
$MAILDIR/Geekstuff
:0:
* > 256000 Condition: match messages larger than 256 Kb
| /root/myprogram Destination: pipe message through the specified program
:0fw
* ^From: .*@foobar\.org Flags: use the pipe as a filter (modifying the message), and tell
| /root/myprogram Procmail to wait that the filter finished processing the message
:0c
* ^Subject:.*administration
Flag: copy the message and proceed with next recipe
! [email protected]
Destination: forward to specified email address, and (as ordered
:0: by the next recipe) save in the specified mailfolder
$MAILDIR/Forwarded
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
51/102 Courier POP configuration
Courier POP configuration
The Courier MTA provides modules for ESMTP, IMAP, POP3, webmail, and mailing list services in a single framework.
The courier-authlib service must be launched first, then the desired mail service e.g. courier-imap for the IMAP service.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
52/102 Courier IMAP configuration
Courier IMAP configuration
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
53/102 Dovecot login
Dovecot login
Dovecot is an open source, security-hardened, fast and efficient IMAP and POP3 server.
By default it uses PAM authentication. The script mkcert.sh can be used to create self-signed SSL certificates.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
54/102 Dovecot mailboxes
Dovecot mailboxes
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
55/102 Dovecot IMAP & POP
Dovecot IMAP & POP
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
56/102 Dovecot authentication
Dovecot authentication
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
57/102 FTP
FTP
Passive mode (more protocol-compliant, because it is the client that initiates the connection)
1. Client connects to FTP server on port 21 and requests passive mode via the PASV command
2. Server acknowledges and sends unprivileged port number via the PORT command
3. Client connects to server's unprivileged port number
4. Server acknowledges
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
58/102 CUPS
CUPS
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
59/102 Network addressing
Network addressing
IPv4 IPv6
32-bit 2130:0000:0000:0000:0007:0040:15bc:235f 128-bit
divised in 4 octects divised in 8 16-bit sections
193.22.33.44 (dotted-quad) 2130:0:0:0:7:40:15bc:235f
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
60/102 Subnetting
Subnetting
Each block of a column identifies a subnet, whose range of valid hosts addresses is [network address +1 — broadcast address -1] inclusive.
The network address of the subnet is the number shown inside a block.
The broadcast address of the subnet is the network address of the block underneath -1 or, for the bottom block, .255.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
61/102 Network services
Network services
ISO/OSI TCP/IP
7 Application
6 Presentation Application e.g. HTTP, SMTP, POP, SSH
5 Session
4 Transport Transport e.g. TCP, UDP
3 Network Internet e.g. IPv4, IPv6, ICMP
2 Data Link
Network Access e.g. Ethernet, Wi-Fi, PPP
1 Physical
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
62/102 Network commands
Network commands
ip addr show Display configuration of all network
ifconfig -a interfaces
ip link show eth0 Display configuration of eth0
ifconfig eth0
ip addr add dev eth0 10.1.1.1/8 Configure IP address of eth0
ifconfig eth0 10.1.1.1 netmask 255.0.0.0 broadcast 10.255.255.255
ifconfig eth0 hw ether 45:67:89:ab:cd:ef Configure MAC address of eth0
ip link set eth0 up Activate eth0
ifconfig eth0 up
ifup eth0
ip link set eth0 down Shut down eth0
ifconfig eth0 down
ifdown eth0
dhclient eth0 Request an IP address via DHCP
pump
dhcpcd eth0 (SUSE)
iwlist wlan0 scan List all wireless devices in range, with their quality of signal and other information
iwlist wlan0 freq Display transmission frequency settings
iwlist wlan0 rate Display transmission speed settings
iwlist wlan0 txpower Display transmission power settings
iwlist wlan0 key Display encryption settings
iwgetid wlan0 option Print NWID, ESSID, AP/Cell address or other information about the wireless network
that is currently in use
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
63/102 Network tools
Network tools
dig example.org Perform a DNS lookup for the specified domain or hostname.
Returns information in BIND zone file syntax; uses an internal
resolver and hence does not honor /etc/resolv.conf
dig @10.7.7.7 -t MX example.org Perform a DNS lookup for the MX record of the domain
example.org, querying nameserver 10.7.7.7
dig -x 203.0.113.1 Perform a reverse DNS lookup for the IP address 203.0.113.1
host example.org Perform a DNS lookup for the specified domain or hostname.
Does honor /etc/resolv.conf
host example.org 10.7.7.7 Perform a DNS lookup for the domain example.org, querying
nameserver 10.7.7.7
host 192.168.13.13 Perform a reverse DNS lookup for the IP address 192.168.13.13
nslookup example.org (deprecated) Perform a DNS lookup for the specified domain or hostname
whois example.org Query the WHOIS service for an Internet resource, usually a
domain name
ping 10.0.0.2 Test if a remote host can be reached and measure the round-trip
time to it (by sending an ICMP ECHO_REQUEST datagram and
expecting an ICMP ECHO_RESPONSE)
fping -a 10.0.0.2 10.0.0.7 10.0.0.8 Ping multiple hosts in parallel and report which ones are alive
traceroute 10.0.0.3 Print the route, hop by hop, packets trace to a remote host
(by sending a sequence of ICMP ECHO_REQUEST datagrams with
increasing TTL values, starting with TTL=1)
tracepath 10.0.0.3 Simpler traceroute
mtr 10.0.0.3 traceroute and ping combined
telnet 10.0.0.4 23 Establish a telnet connection to the specified host and port
(if port is omitted, use default port 23)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
64/102 Network monitoring
Network monitoring
netstat Display network connections
netstat –-tcp Display active TCP connections
netstat -l Display only listening sockets
netstat -a Display all listening and non-listening sockets
netstat -n Display network connections, without resolving hostnames or portnames
netstat -p Display network connections, with PID and name of program to which
each socket belongs
netstat -i Display network interfaces
netstat -s Display protocol statistics
netstat -r Display kernel routing tables (equivalent to route -e)
netstat -c Display network connections continuously
nmap 10.0.0.1 Scan for open ports (TCP SYN scan) on remote host 10.0.0.1
nmap -sS 10.0.0.1
nmap -sP 10.0.0.1 Do a ping sweep (ICMP ECHO probes) on remote host
nmap -sU 10.0.0.1 Scan UDP ports on remote host
nmap -sV 10.0.0.1 Do a service and version scan on open ports
nmap -p 1-65535 10.0.0.1 Scan all ports (1-65535) on remote host, not only the common ports
nmap -O 10.0.0.1 Find which operating system is running on remote host (OS fingerprinting)
tcpdump -ni eth0 Sniff all network traffic on interface eth0, suppressing DNS resolution
tcpdump ip host 10.0.0.2 tcp port 25 Sniff network packets on TCP port 25 from and to 10.0.0.2
tcpdump ether host '45:67:89:ab:cd:ef' Sniff traffic from and to the network interface with that MAC address
tcpdump 'src host 10.0.0.2 and \ Sniff HTTP and HTTPS traffic having as source host 10.0.0.2
(tcp port 80 or tcp port 443)'
tcpdump -ni eth0 not port 22 Sniff all traffic on eth0 except that belonging to the SSH connection
tcpdump -vvnn -i eth0 arp Sniff ARP traffic on eth0, on maximum verbosity level, without converting
host IP addresses and port numbers to names
tcpdump ip host 10.0.0.2 and \ Sniff IP traffic between 10.0.0.2 and any other host except 10.0.0.9
not 10.0.0.9
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
65/102 Network configuration
Network configuration
/sys/class/net List of all network interfaces in the system
/etc/hosts Mappings between IP addresses and hostnames, for simple name resolution
/etc/nsswitch.conf Sources that must be used by various system library lookup functions
order hosts,bind
multi on
/etc/resolv.conf Specification of the domain names that must be appended to bare hostnames and of the
DNS servers that will be used for name resolution
loopback 127.0.0.0
mylan 10.2.3.0
DEVICE=eth0
BOOTPROTO=none
ONBOOT=yes
NETMASK=255.255.255.0
IPADDR=10.2.3.4
USERCTL=no
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
66/102 TCP Wrapper
TCP Wrapper
/etc/hosts.allow Host access control files used by the TCP Wrapper system.
/etc/hosts.deny
Each file contains zero or more daemon:client lines. The first matching line is considered.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
67/102 Routing
Routing
ip route Display IP routing table Gateway: Flags:
route -en host gateway name U route is up
route -F * no gateway G use gateway
netstat -rn
- rejected route H target is host
! rejected route
D dynamically installed by daemon
M modified from routing daemon
R reinstate route for dynamic routing
ADDRESS=10.2.0.0
NETMASK=255.255.0.0
GATEWAY=10.2.0.254
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
68/102 iptables
iptables
The Netfilter framework provides firewalling capabilities in Linux. It is implemented by iptables (which replaced ipchains,
which itself replaced ipfwadm). The IPv6 equivalent of iptables is ip6tables.
When a packet enters the system, it is handed to the INPUT chain. If the destination is local, it is processed; if the
destination is not local and IP forwarding is enabled, the packet is handed to the FORWARD chain, otherwise it is dropped.
An outgoing packet generated by the system will go through the OUTPUT chain.
If NAT is in use, an incoming packet will pass at first through the PREROUTING chain, and an outgoing packet will pass last
through the POSTROUTING chain.
iptables -A INPUT -s 10.0.0.6 -j ACCEPT Add a rule to accept all packets from 10.0.0.6
iptables -A INPUT -s 10.0.0.7 -j REJECT Add a rule to reject all packets from 10.0.0.7 and send
back a ICMP response to the sender
iptables -A INPUT -s 10.0.0.8 -j DROP Add a rule to silently drop all packets from 10.0.0.8
iptables -A INPUT -s 10.0.0.9 -j LOG Add a rule to log via Syslog all packets from 10.0.0.9, and
take no further action
iptables -D INPUT -s 10.0.0.9 -j LOG Delete a rule
iptables -D INPUT 42 Delete rule 42 of the INPUT chain
iptables -F INPUT Flush all rules of the INPUT chain
iptables -t mangle -F Flush all rules of the mangle table
iptables -t mangle -X Delete all user-defined (not built-in) rules in the mangle
table
iptables -L INPUT List the rules of the INPUT chain
iptables -P INPUT -j DROP Define the chain policy, which takes effect when no rule
matches and the end of the rules list is reached
iptables -A OUTPUT -d 10.7.7.0/24 -j DROP Add a rule to drop all packets with destination 10.7.7.0/24
iptables -A FORWARD -i eth0 -o eth1 -j LOG Add a rule to log all packets entering the system via eth0
and exiting via eth1
iptables -A INPUT -p 17 -j DROP Add a rule to drop all incoming UDP traffic (protocol
iptables -A INPUT -p udp -j DROP numbers are defined in /etc/protocols)
iptables -A INPUT --sport 1024:65535 --dport 53 \ Add a rule to accept all packets coming from any
-j ACCEPT unprivileged port and with destination port 53
iptables -A INPUT -p icmp --icmp-type echo-request \ Add a rule to accept incoming pings through eth0 at a
-m limit --limit 1/s -i eth0 -j ACCEPT maximum rate of 1 ping/second
iptables -A INPUT -m state --state ESTABLISHED \ Load the module for stateful packet filtering, and add a
-j ACCEPT rule to accept all packets that are part of a
communication already tracked by the state module
iptables -A INPUT -m state --state NEW -j ACCEPT Add a rule to accept all packets that are not part of a
communication already tracked by the state module
iptables -A INPUT -m state --state RELATED -j ACCEPT Add a rule to accept all packets that are related (e.g.
ICMP responses to TCP or UDP traffic) to a communication
already tracked by the state module
iptables -A INPUT -m state --state INVALID -j ACCEPT Add a rule to accept all packets that do not match any of
the states above
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
69/102 NAT routing
NAT routing
iptables -t nat -A PREROUTING -i eth0 -d ! 10.0.0.0/24 \ Redirect all outbound HTTP traffic originating from
-p tcp --dport 80 -j REDIRECT --to-ports 3128 the LAN to a proxy running on port 3128 on the
Linux box
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
70/102 SSH
SSH
ssh root@remotehost Connect to a remote host via SSH (Secure Shell) and login
as the superuser
ssh -p 2222 root@remotehost Login as the superuser to a remote host via SSH using
port 2222 instead of standard port 22
ssh root@remotehost /root/myscript.sh Execute a command on a remote host
sftp [email protected] FTP-like tool for secure file transfer
scp myfile [email protected]:/tmp/myfile2 Non-interactive secure file copy.
scp [email protected]:/tmp/myfile2 myfile Able of transferring files from local to remote, from remote
scp jdoe@host1:/tmp/myfile root@host2:/root/myfile2 to local, or between two remote systems
ssh-keygen -t rsa -b 2048 Generate interactively a 2048-bit RSA key pair, prompting
for a passphrase
ssh-keygen -t dsa Generate a DSA key pair
ssh-keygen -p -t rsa Change passphrase of the private key
ssh-keygen -q -t rsa -f /etc/ssh/ssh_host_key \ Generate a RSA key with no passphrase (to be used by a
-N '' -C '' server host, not a user) and no comment
ssh-keygen -l -f /etc/ssh/ssh_host_key View fingerprint of a public key
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
71/102 SSH configuration
SSH configuration
SSH files
/etc/ssh/sshd_config SSH server daemon configuration file
/etc/ssh/ssh_config SSH client global configuration file
/etc/ssh/ssh_host_key Host's private key (should be mode 0600)
/etc/ssh/ssh_host_key.pub Host's public key
/etc/ssh/shosts.equiv Names of trusted hosts for host-based authentication
/etc/ssh/ssh_known_hosts Database of host public keys that were previously accepted as legitimate
~/.ssh/ User's SSH directory (must be mode 0700)
~/.ssh/config SSH client user configuration file
~/.ssh/id_rsa User's RSA or DSA private key, as generated by ssh-keygen
~/.ssh/id_dsa
~/.ssh/id_rsa.pub User's RSA or DSA public key, as generated by ssh-keygen
~/.ssh/id_dsa.pub
~/.ssh/known_hosts Host public keys that were previously accepted as legitimate by the user
~/.ssh/authorized_keys Trusted public keys; the corresponding private keys allow the user to
~/.ssh/authorized_keys2 (obsolete) authenticate on this host
/etc/ssh/sshd_config
PermitRootLogin yes Control superuser login via SSH. Possible values are:
yes Superuser can login
no Superuser cannot login
without-password Superuser cannot login with password
forced-commands-only Superuser can only run commands in SSH command line
AllowUsers jdoe ksmith
DenyUsers jhacker List of users that can/cannot login via SSH, or * for everybody
AllowGroups geeks
DenyGroups * List of groups whose members can/cannot login via SSH, or * for all groups
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
72/102 GnuPG
GnuPG
gpg --gen-key Generate a key pair
gpg --import alice.asc Import Alice's public key into your keyring
gpg --list-keys List the keys contained into your keyring
gpg --list-secret-keys List your private keys contained into your keyring
gpg --list-public-keys List the public keys contained into your keyring
gpg --export -o keyring_backup.gpg Export your whole keyring to a file
gpg --export-secret-key -a "You" -o private.key Export your private key (username You) to a file
gpg --export-public-key -a "Alice" -o alice.pub Export Alice's public key to a file
gpg --edit-key "Alice" Sign Alice's public key
gpg -e -u "You" -r "Alice" file.txt Encrypt a file (to Alice i.e. with Alice's public key),
signing it with your private key
gpg -d file.txt.gpg Decrypt a file (with your own public key)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
73/102 OpenVPN
OpenVPN
openvpn --genkey --secret keyfile Generate a shared secret keyfile for OpenVPN authentication.
The keyfile must be copied on both server and client
openvpn server.conf Start the VPN on the server side. The encrypted VPN tunnel uses UDP port 1194
openvpn client.conf Start the VPN on the client side
dev tun
ifconfig [server IP] [client IP]
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
secret keyfile
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
74/102 Key bindings
Key bindings
Key Alternate key Function
CTRL ALT DEL Send a SIGINT to reboot the machine (same as shutdown -r now)*
*
as specified in /etc/inittab and /etc/init/control-alt-delete
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
75/102 udev
udev
The Hardware Abstraction Layer (HAL) manages device files and provides plug-and-play facilities. The HAL daemon hald
maintains a persistent database of devices.
udev dynamically generates the device nodes in /dev/ for devices present on the system. udev also provides persistent
naming for storage devices in /dev/disk .
When a device is added, removed, or changes state, the kernel sends an uevent received by the udevd daemon which will
pass the uevent through a set of rules stored in /etc/udev/rules.d/*.rules and /lib/udev/rules.d/*.rules .
KERNEL=="hdb", DRIVER=="ide-disk", SYMLINK+="mydisk myhd" Match a device with kernel name and driver
as specified; name the device node with the
default name and create two symbolic links
/dev/mydisk and /dev/myhd pointing to
/dev/hdb
KERNEL=="fd[0-9]*", NAME="floppy/%n", SYMLINK+="%k" Match all floppy disk drives (i.e. fdn); place
device node in /dev/floppy/n and create a
symlink /dev/fdn to it
KERNEL=="sda", PROGRAM="/bin/mydevicenamer %k", SYMLINK+="%c" Match a device named by the kernel as sda;
to name the device, use the defined
program which takes on stdin the kernel
name and output on stdout e.g. name1
name2. Create symlinks /dev/name1 and
/dev/name2 pointing to /dev/sda
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
76/102 Kernel
Kernel
A kernel version number has the form major.minor.patchlevel.
Kernel images are usually gzip-compressed and can be of two types: zImage (max 520 Kb) and bzImage (no size limit).
Kernel modules can be loaded dynamically into the kernel to provide additional functionalities on demand, instead of being
included when the kernel is compiled; this reduces memory footprint.
kerneld (daemon) and kmod (kernel thread) facilitate the dynamic loading of kernel modules.
freeramdisk Free the memory used for the initrd image. This command must be
run directly after unmounting /initrd
mkinitrd [initrd image] [kernel version] Create a initrd image file (Red Hat)
mkinitramfs Create a initrd image file according to the configuration file
/etc/initramfs-tools/initramfs.conf (Debian)
dracut Create initial ramdisk images for preloading modules
The runtime loader ld.so loads the required shared libraries of the program into RAM, searching in this order:
1. LD_LIBRARY_PATH Environment variable specifying the list of dirs where libraries should be searched for first
2. /etc/ld.so.cache Cache file
3. /lib and /usr/lib Default locations for shared libraries
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
77/102 Kernel management
Kernel management
lsdev List information about the system's hardware
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
78/102 Kernel compile and patching
Kernel compile and patching
Kernel compile
Download kernel source code linux-X.Y.Z.tar.bz2 from http://www.kernel.org
Download
to the base of the kernel source tree /usr/src/linux
make clean Delete most generated files
Clean make mrproper Delete all generated files and kernel configuration
make distclean Delete temporary files, patch leftover files, and similar
make config Terminal-based (options must be set in sequence)
make menuconfig ncurses UI
make xconfig
make gconfig GUI
make oldconfig Create a new config file, based on the options in the old config
file and in the source code
Configure
Components (e.g. device drivers) can be either:
- not compiled
- compiled into the kernel binary, for support of devices always used on the system or necessary
for the system to boot
- compiled as a kernel module, for optional devices
Copy the new compiled kernel and other files into the boot partition
Kernel install cp /usr/src/linux/arch/boot/bzImage /boot/vmlinuz-X.Y.Z (kernel)
cp /usr/src/linux/arch/boot/System.map-X.Y.Z /boot
cp /usr/src/linux/arch/boot/config-X.Y.Z /boot (config options used for this compile)
Kernel patching
Download Download and decompress the patch to /usr/src
patch -p1 < file.patch Apply the patch
Patch To remove a patch, you can either apply the patch again or
patch -Rp1 < file.patch
use this command (reverse patch)
Build Build the patched kernel as explained previously
Install Install the patched kernel as explained previously
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
79/102 Kernel modules
Kernel modules
Kernel modules allow the kernel to access functions (symbols) for kernel services e.g. hardware drivers, network stack, or
filesystem abstraction.
lsmod List the modules that are currently loaded into the kernel
insmod module Insert a module into the kernel. If the module requires another module or if it
does not detect compatible hardware, insertion will fail
rmmod module Remove a module from the kernel. If the module is in use by another module, it
is necessary to remove the latter first
modinfo module Display the list of parameters accepted by the module
depmod -a Probe all modules in the kernel modules directory and generate the file that lists
their dependencies
It is recommended to use modprobe instead of insmod/rmmod, because it automatically handles prerequisites when inserting
modules, is more specific about errors, and accepts just the module name instead of requiring the full pathname.
modprobe module option=value Insert a module into the running kernel, with the specified parameters.
Prerequisite modules will be inserted automatically
modprobe -a Insert all modules
modprobe -t directory Attempt to load all modules contained in the directory until a module succeeds.
This action probes the hardware by successive module-insertion attempts for a
single type of hardware, e.g. a network adapter
modprobe -r module Remove a module
modprobe -c module Display module configuration
modprobe -l List loaded modules
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
80/102 /proc filesystem
/proc filesystem
/proc/sys is the only writable branch of /proc and can be used to tune kernel parameters on-the-fly.
All changes will be lost after system shutdown.
sysctl fs.file-max
cat /proc/sys/fs/file-max Get the maximum allowed number of open files
sysctl -w "fs.file-max=100000"
echo "100000" > /proc/sys/fs/file-max Set the maximum allowed number of open files to 100000
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
81/102 System recovery
System recovery
If the kernel has been booted in emergency mode and init has not been run, some initial configuration is necessary e.g.
mount /proc
mount -o remount,rw /
mount -a
mknod /dev/sda
mknod /dev/sda1
fdisk -l /dev/sda
fsck -y /dev/sda1
mount -t ext3 /dev/sda1 /mnt/sysimage
chroot /mnt/sysimage
To install a package using an alternative root directory (useful if the system has been booted from a removable media):
An alternative metod is to chroot /mnt/sysimage before installing GRUB via grub-install /dev/sda .
Run sync and unmount filesystems before exiting the shell, to ensure that all changes have been written on disk.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
82/102 DNS
DNS
DNS implementations
BIND Berkeley Internet Name Domain system, is the standard DNS server for UNIX
dnsmasq Lightweight DNS, DHCP and TFTP server for a small network
djbdns Security-hardened DNS server that also includes DNS debugging tools
PowerDNS Alternative open-source DNS server
DNSSEC was designed to secure the DNS tree and hence prevent cache poisoning.
The TSIG (Transaction SIGnature) standard, that authenticates communications between two trusted systems, is used to
sign zone transfers and DDNS (Dynamic DNS) updates.
dnssec-keygen -a dsa -b 1024 \ Generate a TSIG key with DNSSEC algorithm nnn and key fingerprint fffff.
-n HOST dns1.example.org This will create two key files
Kdns1.example.org.+nnn+fffff.key
Kdns1.example.org.+nnn+fffff.private
which contain a key number that has to be inserted both in /etc/named.conf and
/etc/rndc.conf
key "rndc-key" {
algorithm hmac-md5;
secret "vyZqL3tPHsqnA57e4LT0Ek==";
};
options {
default-key "rndc-key";
default-server 127.0.0.1;
default-port 953;
};
named -u named -g named Run BIND as user/group named (both must be created if needed) instead of root
named -t /var/cache/bind Run BIND in a chroot jail /var/cache/bind
(actually is the chroot command that starts the named server)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
83/102 DNS configuration
DNS configuration
options {
directory "/var/named"; // Working directory
version "0.0"; // Hide version number by replacing it with 0.0
listen-on port 53 {10.7.0.1; 127.0.0.1;}; // Port and own IP addresses to listen on
blackhole {172.17.17.0/24;}; // IPs whose packets are to be ignored
allow-query {mynetwork;}; // IPs allowed to do iterative queries
allow-query-on {any;}; // Local IPs that can accept iterative queries
allow-query-cache {any;}; // IPs that can get an answer from cache
allow-recursion {mynetwork;}; // IPs to accept recursive queries from (typically
// own network's IPs). The DNS server does the full
// resolution process on behalf of these client IPs,
// and returns a referral for the other IPs
allow-recursion-on {mynetwork;}; // Local IPs that can accept recursive queries
allow-transfer {10.7.0.254;}; // Zone transfer is restricted to these IPs (slaves);
// on slave servers, this option should be disabled
allow-update {any;}; // IPs to accept DDNS updates from
recursive-clients 1000; // Max number of simultaneous recursive lookups
dnssec-enable yes; // Enable DNSSEC
dialup no; // Not a dialup connection: external zone maintenance
// (e.g. sending heartbeat packets, external zone transfers)
// is then permitted
forward first; // Site-wide cache: bypass the normal resolution
forwarders {10.7.0.252; 10.7.0.253;}; // method by querying first these central DNS
// servers if they are available
};
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
84/102 DNS zone file
DNS zone file
IN NS dns1.example.org.
IN NS dns2.example.org.
IN MX 10 mail1.example.org.
IN MX 20 mail2.example.org.
dns1 IN A 224.123.240.3
dns2 IN A 224.123.240.4
mail1 IN A 224.123.240.73
mail2 IN A 224.123.240.77
foo IN A 224.123.240.12
bar IN A 224.123.240.13
www IN A 224.123.240.19
baz IN CNAME bar
Resource Records
$TTL How long to cache a positive response
$ORIGIN Suffix appended to all names not ending with a dot.
Useful when defining multiple subdomains inside the same zone
SOA Start Of Authority for the example.org zone
serial Serial number. Must be increased after each edit of the zone file
refresh How frequently a slave server refreshes its copy of zone data from the master
retry How frequently a slave server retries connecting to the master
expire How long a slave server relies on its copy of zone data. After this time period expires,
the slave server is not authoritative anymore for the zone unless it can contact a master
negative TTL How long to cache a non-existent answer
A Address: maps names to IP addresses. Used for DNS lookups.
PTR Pointer: maps IP addresses to names. Used for reverse DNS lookups.
Each A record must have a matching PTR record
CNAME Canonical Name: specifies an alias for a host with an A record (even in a different zone).
Discouraged as it causes multiple lookups; it is better to use multiple A records instead
NS Name Service: specifies the authoritative name servers for the zone
MX Mailserver: specifies address and priority of the servers able to handle mail for the zone
Glue Records are not really part of the zone; they delegate authority for other zones, usually subdomains
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
85/102 Apache
Apache
Methods of MPM (Multi-Processing Modules) operation of the Apache webserver:
prefork MPM A number of child processes is spawned in advance, with each child serving exclusively one connection.
Highly reliable due to Linux memory protection that isolates each child process
worker MPM Multiple child processes spawn multiple threads, with each thread serving one connection.
More scalable but prone to deadlocks if third-party non-threadsafe modules are loaded
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
86/102 Apache configuration
Apache configuration
httpd.conf
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
87/102 Apache virtual hosts
Apache virtual hosts
httpd.conf
<VirtualHost *:80> The first listed virtual host is also the default virtual host.
ServerName www.mysite.org It inherits those main settings that does not override.
ServerAlias mysite.org *.mysite.org This virtual host answers to http://www.mysite.org , and also
DocumentRoot /var/www/vhosts/mysite
redirects there all HTTP requests on the domain mysite.org
</VirtualHost>
LogFormat "%h %l %u %t \"%r\" %>s %b" common Specify a nickname (here, "common") for a log format.
This one is the CLF (Common Log Format) defined as such:
%h IP address of the client host
%l Identity of client as determined by identd
%u User ID of client making the request
%t Timestamp the server completed the request
%r Request as done by the user
%s Status code sent by the server to the client
%b Size of the object returned, in bytes
CustomLog /var/log/httpd/access_log common Set up a log filename, with the format or (as in this case)
the nickname specified
TransferLog /var/log/httpd/access_log Set up a log filename, with format determined by the most
recent LogFormat directive which did not define a nickname
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
88/102 Apache directory protection
Apache directory protection
httpd.conf
AuthGroupFile "/var/www/.htgroup" Group database file. Each line contains a groupname followed
by all member usernames:
mygroup: jdoe ksmith mgreen
Allow from 10.13.13.0/24 Control which host can access the protected resource
Satisfy Any Set the access policy concerning user and host control.
All both Require and Allow criteria must be satisfied
Any any of Require or Allow criteria must be satisfied
Order Allow,Deny Control the evaluation order of Allow and Deny directives.
Allow,Deny First, all Allow directives are evaluated; at
least one must match, or the request is
rejected. Next, all Deny directives are
evaluated; if any matches, the request is
rejected. Last, any requests which do not
match an Allow or a Deny directive are
denied
Deny,Allow First, all Deny directives are evaluated; if
any match, the request is denied unless it
also matches an Allow directive. Any
requests which do not match any Allow or
Deny directives are permitted
</Directory>
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
89/102 HTTPS
HTTPS
A secure web server (using HTTP over SSL i.e. HTTPS) hands over its public key to the client when the latter connects to it
via port 443. The server's public key is signed by a CA (Certification Authority), whose validity is ensured by the root
certificates stored into the client's browser.
The openssl command and its user-friendly CA.pl script are the tools of the OpenSSL crypto library that can be used to
accomplish all public key crypto operations e.g. generate key pairs, Certificate Signing Requests, self-signed certificates.
Virtual hosting with HTTPS requires assigning an unique IP address for each virtual host; this because the SSL handshake
(during which the server sends its certificate to the client's browser) takes place before the client sends the Host: header
(which tells which virtual host the client wants to talk to).
A workaround for this is SNI (Server Name Indication) that makes the browser send the hostname in the first message of
the SSL handshake. Another workaround is to have all multiple name-based virtual hosts use the same SSL certificate e.g.
for a wildcard domain *.example.org.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
90/102 Apache SSL/TLS configuration
Apache SSL/TLS configuration
httpd.conf
SSL/TLS directives (module mod_ssl)
SSLCertificateFile \ SSL server certificate
/etc/httpd/conf/ssl.crt/server.crt
SSLCertificateKeyFile \ SSL server private key (for security reasons, this file
/etc/httpd/conf/ssl.key/server.key should be readable only by root)
SSLCACertificatePath \ Directory containing the certificates of CAs. Files in this
/usr/local/apache2/conf/ssl.crt/ directory are PEM-encoded and accessed via symlinks to
hash filenames
SSLCACertificateFile \ Certificates of CAs. Certificates are PEM-encoded and
/usr/local/apache2/conf/ssl.crt/ca-bundle.crt concatenated in a single bundle file in order of preference
SSLCertificateChainFile \ Certificate chain of the CAs. Certificates are PEM-encoded
/usr/local/apache2/conf/ssl.crt/ca.crt and concatenated from the issuing CA certificate of the
server certificate to the root CA certificate. Optional
SSLEngine on Enable the SSL/TLS Protocol Engine
SSLProtocol +SSLv3 +TLSv1.2 SSL protocol flavors that the client can use to connect to
server. Possible values are:
SSLv2 (deprecated)
SSLv3
TLSv1
TLSv1.1
TLSv1.2
All (all the above protocols)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
91/102 OpenSSL
OpenSSL
openssl x509 -text -in certif.crt -noout Read a certificate
openssl req -text -in request.csr -noout Read a Certificate Signing Request
openssl req -new -key private.key -out request.csr Generate a Certificate Signing Request (in PEM
format) for the public key of a key pair
openssl req -new -nodes -keyout private.key \ Create a 2048-bit RSA key pair and generate a
-out request.csr -newkey rsa:2048 Certificate Signing Request for it
openssl ca -config ca.conf -in request.csr \ Sign a CSR (to generate a self-signed certificate,
-out certif.cer -days validity -verbose the steps are creating a CSR and signing it)
openssl ca -config ca.conf -gencrl -revoke certif.cer \ Revoke a certificate
-crl_reason why
openssl ca -config ca.conf -gencrl -out crlist.crl Generate a Certificate Revocation List containing
all revoked certificates so far
openssl x509 -in certif.pem -outform DER \ Convert a certificate from PEM to DER
-out certif.der
openssl pkcs12 -export -in certif.pem \ Convert a certificate from PEM to PKCS#12
-inkey private.key -out certif.pfx -name friendlyname including the private key
openssl dgst -hashfunction -out file.hash file Generate the digest of a file
openssl dgst -hashfunction file | cmp -b file.hash Verify the digest of a file (if there is no output,
then digest verification is successful)
openssl dgst -hashfunction -sign private.key \ Generate the signature of a file
-out file.sig file
openssl dgst -hashfunction -verify public.key \ Verify the signature of a file
-signature file.sig file
openssl enc -e -cipher -in file -out file.enc -salt Encrypt a file
openssl enc -d -cipher -in file.enc -out file Decrypt a file
openssl genpkey -algorithm RSA -cipher 3des \ Generate a 2048-bit RSA key pair protected by
-pkeyopt rsa_keygen_bits:2048 -out key.pem TripleDES passphrase
openssl genrsa -des3 -out key.pem 2048 Generate a 2048-bit RSA key pair protected by
TripleDES passphrase (older versions of OpenSSL)
openssl pkey -text -in private.key -noout Examine a private key
openssl rsa -text -in private.key -noout Examine a private key
(older versions of OpenSSL)
openssl pkey -in old.key -out new.key -cipher Change a private key's passphrase
openssl rsa -in old.key -out new.key -cipher Change a private key's passphrase
(older versions of OpenSSL)
openssl s_client -connect www.website.com:443 > tmpfile Retrieve and inspect a SSL certificate from a
CTRL C website
openssl x509 -in tmpfile -text
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
92/102 CA.pl
CA.pl
CA.pl -newca Create a Certification Authority hierarchy
CA.pl -newreq Generate a Certificate Signing Request
CA.pl -signreq Sign a Certificate Signing Request
CA.pl -pkcs12 "My certificate" Generate a PKCS#12 certificate from a Certificate Signing Request
CA.pl -newreq-nodes Generate a Certificate Signing Request, with an unencrypted private key
(necessary for servers as the private key must be accessed)
CA.pl -verify Verify a certificate against the Certification Authority certificate for "demoCA"
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
93/102 Samba
Samba
Samba is a cross-platform implementation of Microsoft's SMB (Server Message Block) protocol for file and printer sharing.
SMB is sometimes also referred to as CIFS (Common Internet File System).
WINS (Windows Internet Name Service) is a name service used to translate NetBIOS names to IP addresses.
Ports used: TCP 137 name service requests and responses
TCP 138 datagram services e.g. server announcements
TCP 139 file and printer sharing
UDP registration and translation of NetBIOS names, network browsing
smbd Server Message Block daemon. Provides SMB file and printer sharing, browser services, user authentication,
and resource lock. An extra copy of this daemon runs for each client connected to the server
nmbd NetBIOS Name Service daemon. Handles NetBIOS name lookups, WINS requests, list browsing and elections.
An extra copy of this daemon runs if Samba functions as a WINS server.
Another extra copy of this daemon runs if DNS is used to translate NetBIOS names
mount.cifs //smbserver/share1 /mnt/shares/sh1 \ Mount a Samba share on a Linux filesystem, using the CIFS
-o auto,credentials=/etc/smbcreds filesystem interface.
Access is checked upon a credentials file /etc/smbcreds
(should be readable only by root) formatted as follows:
username = jdoe
password = jd03s3cr3t
smbmount //smbserver/share1 /mnt/shares/sh1 \ Mount a Samba share as user jdoe
-o username=jdoe
nmblookup -U winsserver -R WORKGROUP#1B Query recursively a WINS server for the Domain Master
Browser for the specified workgroup
nmblookup -U winsserver -R WORKGROUP#1D Query recursively a WINS server for the Domain Controller
for the specified workgroup
testparm Check for errors in the Samba configuration file
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
94/102 Samba configuration
Samba configuration
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
95/102 Samba shares
Samba shares
Server-level authentication
[global]
security = server Set up server-level authentication
password server = srv1 srv2 Authenticate to server srv1, or to server srv2 if srv1 is unavailable
Domain-level authentication
[global]
security = ADS Set up domain-level authentication as an Active Directory member server
realm = KRB_REALM Join the specified realm.
Kerberos must be installed and an administrator account must be created:
net ads join -U Administrator%password
Share-level authentication
[global]
security = share Set up share-level authentication
[foobar] Define a share accessible to any user which can supply foobaruser's password.
path = /foobar The user foobaruser must be created on the system:
username = foobaruser useradd -c "Foobar account" -d /tmp -m -s /sbin/nologin foobaruser
only user = yes and added to the Samba password file:
smbpasswd -a foobaruser
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
96/102 Samba macros
Samba macros
Samba macros
%S Username The substitutes below apply only to the
configuration options that are used when a
%U Session username (the username that the client requested,
connection has been established:
not necessarily the same as the one he got)
%G Primary group of session username %S Name of the current service, if any
%h Samba server hostname %P Root directory of the current service, if any
%M Client hostname %u Username of the current service, if any
%L NetBIOS name of the server %g Primary group name of username
%m NetBIOS name of the client %H Home directory of username
%d Process ID of the current server process %N Name of the NIS home directory server as
obtained from the NIS auto.map entry.
%a Architecture of remote machine
Same as %L if Samba was not compiled with
%I IP address of client machine the --with-automount option
%i Local IP address to which a client connected %p Path of service's home directory as obtained
from the NIS auto.map entry. The NIS
%T Current date and time
auto.map entry is split up as %N:%p
%D Domain or workgroup of the current user
%w Winbind separator
%$(var) Value of the environment variable var
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
97/102 NFS
NFS
A Network File System (NFS) server makes filesystems available to clients for mounting.
The portmapper is needed by NFS to map incoming TCP/IP connections to the appropriate NFS RPC calls. Some Linux
distributions use rpcbind instead of the portmapper.
For security, the TCP Wrapper should be configured to limit access to the portmapper to NFS clients only:
file /etc/hosts.deny should contain portmap: ALL
file /etc/hosts.allow should contain portmap: IP_addresses_of_clients
NFS handles user permissions across systems by considering users with same UID and username as the same user.
Group permission is evaluated similarly, by GID and groupname.
showmount Show the remote client hosts currently having active mounts
showmount --directories Show the directories currently mounted by a remote client host
showmount --exports Show the filesystems currently exported i.e. the active export list
showmount --all Show both remote client hosts and directories
showmount -e nfsserver Show the shares a NFS server has available for mounting
mount -t nfs nfsserver:/share /usr Command to be run on a client to mount locally a remote NFS share.
NFS shares accessed frequently should be added to /etc/fstab :
nfsserver:/share /usr nfs intr 0 0
rpcinfo -p nfsserver Probe the portmapper on a NFS server and display the list of all registered
RPC services there
rpcinfo -t nfsserver nfs Test a NFS connection by sending a null pseudo request (using TCP)
rpcinfo -u nfsserver nfs Test a NFS connection by sending a null pseudo request (using UDP)
both -n -r -nr
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
98/102 /etc/exports
/etc/exports
/etc/exports
/export/ 10.3.3.3(rw)
/export/ *(ro,sync)
/home/ftp/pub client1(rw) *.example.org(ro)
/home/crew @FOOBARWORKGROUP(rw) (ro)
filesystem Filesystem on the NFS server to be exported to clients
Client systems allowed to access the exported directory.
client
Can be identified by hostname, IP address, wildcard, subnet, or @NIS workgroup.
identity
Multiple client systems can be listed, and each one can have different options
ro Read-only access (default)
rw Read and write access. The client may choose to mount read-only anyway
sync Reply to requests only after the changes made by these requests have been committed to
stable storage
async Reply to requests without waiting that changes are committed to stable storage.
client
options Improves performances but might cause loss or corruption of data if server crashes
root_squash Requests by user root on client will be done as user nobody on server (default)
no_root_squash Requests by user root on client will be done as same user root on server
all_squash Requests by a non-root user on client will be done as user nobody on server
no_all_squash Requests by a non-root user on client will be attempted as same user on server (default)
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
99/102 DHCP
DHCP
A DHCP (Dynamic Host Configuration Protocol) server listens for requests on UDP port 67 and answers to UDP port 68.
The assignment of an IP address to a host is done through a sequence of DHCP messages initiated by the client host:
DHCP Discover, DHCP Offer, DHCP Request, DHCP Acknowledgment.
Because DHCP Discover messages are broadcast and therefore not routed outside a LAN, a DHCP relay agent is necessary
for those clients situated outside the DHCP server's LAN. The DHCP relay agent listens to DHCP Discover messages and
relays them in unicast to the DHCP server.
/etc/dhcpd.conf
option domain-name-servers 10.2.2.2;
option smtp-servers 10.3.3.3;
option pop-servers 10.4.4.4; Global parameters for DNS, mail, NTP, and news servers
option time-servers 10.5.5.5; specification
option nntp-servers 10.6.6.6;
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
100/102 PAM
PAM
PAM (Pluggable Authentication Modules) is an abstraction layer that allows applications to use authentication methods while
being implementation-agnostic.
/etc/pam.d/service
auth requisite pam_securetty.so
auth required pam_nologin.so
auth required pam_env.so
auth required pam_unix.so nullok
account required pam_unix.so
session required pam_unix.so
session optional pam_lastlog.so
password required pam_unix.so nullok obscure min=4 max=8
auth Authentication module to verify user identity and group membership
account Authorization module to determine user's right to access a resource (other than his identity)
type
password Module to update an user's authentication credentials
session Module (run at end and beginning of an user session) to set up the user environment
optional Module is not critical to the success or failure of service
sufficient If this module successes, and no previous module has failed, module stack processing ends
successfully. If this module fails, it is non-fatal and processing of the stack continues
control required If this module fails, processing of the stack continues until the end, and service fails
requisite If this module fails, service fails and control returns to the application that invoked service
include Include modules from another PAM service file
PAM module and its options, e.g.:
pam_unix.so Standard UNIX authentication module via /etc/passwd and /etc/shadow
pam_nis.so Module for authentication via NIS
pam_ldap.so Module for authentication via LDAP
module
pam_fshadow.so Module for authentication against an alternative shadow passwords file
pam_cracklib.so Module for password strength policies (e.g. length, case, max n of retries)
pam_limits.so Module for system policies and system resource usage limits
pam_listfile.so Module to deny or allow the service based on an arbitrary text file
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
101/102 LDAP
LDAP
LDAP (Lightweight Directory Access Protocol) is a simplified version of the X.500 standard and uses TCP port 389.
LDAP permits to organize hierarchically a database of entries, each one of which is identified by an unique DN (Distinguished
Name). Each DN has a set of attributes, each one of which has a value. An attribute may appear multiple times.
ldapsearch -H ldap://ldapserver.example.org \ Query the specified LDAP server for entries where
-s base -b "ou=people,dc=example,dc=com" \ surname=Doe, and print common name, surname, and
"(sn=Doe)" cn sn telephoneNumber telephone number of the resulting entries.
Output is shown in LDIF
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo
102/102 OpenLDAP
OpenLDAP
slapd Standalone OpenLDAP daemon
SSSD (the System Security Services Daemon) can be used to provide access to OpenLDAP as an authentication and identity
provider.
Linux & LPIC Quick Reference Guide 2nd ed. 2014-09 © Daniele Raffo www.crans.org/~raffo