0% found this document useful (0 votes)
422 views

Linux Basic Sysadmin PDF

Uploaded by

Kaushal Shakya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
422 views

Linux Basic Sysadmin PDF

Uploaded by

Kaushal Shakya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 283

COURSE

Linux System and


Networking
Administration
2 Linux System and Networking Administration
Linux System and Networking Administration 3

Table of Contents
Chapter 1: Overview of Linux ............................................................................... 17
Introduction to Linux ........................................................................................... 17
Recapitulating Basic Concept of Operating System ........................................................17
Linux Architecture .......................................................................................................... 17
What is Kernel?............................................................................................................................. 17
What is Shell? ............................................................................................................................... 18
History of Unix ...............................................................................................................18
Multics Project .............................................................................................................................. 18
Unix History .................................................................................................................................. 18
Flavours of Unix.............................................................................................................. 18
Evolution of Linux........................................................................................................... 18
Features of the Linux Operating System......................................................................... 19
Advantages of Linux ....................................................................................................... 20
Explaining How Linux Architecture Works...................................................................... 21
Identifying Distributors of Linux .....................................................................................22
Introducing Red Hat Enterprise Linux ............................................................................. 23
Installing/Upgrading Red Hat Enterprise Linux 5 .................................................. 24
Performing Pre-Installation Tasks ..................................................................................24
An Overview of Installation Methods............................................................................. 24
Performing the Installation from the CD/DVD................................................................25
Performing an Upgrade .................................................................................................. 35

Chapter 2: Linux Filesystem and Commands ......................................................... 37


Understanding Filesystem Structure..................................................................... 37
Introduction ...................................................................................................................37
Overview of the FHS ....................................................................................................... 37
The /dev Directory ........................................................................................................................ 37
The /etc Directory......................................................................................................................... 37
The /lib Directory .......................................................................................................................... 38
The /proc Directory ...................................................................................................................... 38
The /sbin Directory ....................................................................................................................... 38
The /usr Directory......................................................................................................................... 38
The /usr/local Directory ............................................................................................................... 39
The /var Directory ........................................................................................................................ 39
usr/local in Red Hat Linux ............................................................................................................. 40
4 Linux System and Networking Administration

Working with Basic Commands............................................................................ 40


Printing Working Directory.............................................................................................40
Listing Files and Directories ............................................................................................41
Creating Files ..................................................................................................................41
Working with cat Command ......................................................................................................... 41
Working with touch Command .................................................................................................... 42
Creating Directories........................................................................................................ 42
Navigating through Directories ......................................................................................42
Removing a File or Directory ..........................................................................................43
Copying a File or Directory .............................................................................................43
Moving / Renaming a File or Directory ........................................................................... 43
Looking for Files ............................................................................................................. 43
The find Command ....................................................................................................................... 43
The locate Command .................................................................................................................... 44
Getting into the Files ...................................................................................................... 44
The cat Command......................................................................................................................... 44
The less and more Command ....................................................................................................... 44
The head and tail Command ........................................................................................................ 44

Search Text Files Using Regular Expressions ......................................................... 45


Introduction ...................................................................................................................45
Regular Expression Syntax..............................................................................................45
Using grep ......................................................................................................................47
Using egrep ....................................................................................................................49
Using sed ........................................................................................................................50
Examples of Simple Regular Expression ......................................................................... 53
Anchors ......................................................................................................................................... 53
Groups and Ranges ....................................................................................................................... 53
Modifiers ...................................................................................................................................... 54
Basic Regular Expression Patterns ................................................................................................ 56
Using Regular Expressions as Addresses in sed ............................................................................ 56

Working with File Permissions ............................................................................. 58


Basic File Permission ...................................................................................................... 58
Access Permission .......................................................................................................... 58
Permission – Access Mode ........................................................................................................... 58
File Permission Modes .................................................................................................................. 59
Default File Permission................................................................................................... 59
Viewing Umask Value ................................................................................................................... 60
Default Directory Permission .........................................................................................60
The chmod Command .................................................................................................... 60
Linux System and Networking Administration 5

Understanding Advanced File Permissions ........................................................... 61


Using SUID Commands ................................................................................................... 61
Understanding SGID ....................................................................................................... 62
Understanding Sticky Bit ................................................................................................62
Working with vi-Editor......................................................................................... 62
What are Editors?........................................................................................................... 62
vi Editor Modes .............................................................................................................. 62
Getting into Insert Mode .............................................................................................................. 62
Working in Command Mode ........................................................................................................ 62
Working at Execute Mode ............................................................................................................ 63

Chapter 3: Managing Services.............................................................................. 65


Explaining Linux Boot Process .............................................................................. 65
Introduction ...................................................................................................................65
The Boot Process ............................................................................................................ 65
A Detailed Look at the Boot Process...............................................................................65
The BIOS ....................................................................................................................................... 65
The Boot Loader ........................................................................................................................... 66
The Kernel..................................................................................................................................... 67
The /sbin/init Program ................................................................................................................. 67
Running Additional Programs at Boot Time ................................................................... 70
SysV Init Runlevels ............................................................................................... 71
Introduction ...................................................................................................................71
Different Runlevels......................................................................................................... 71
Runlevel Utilities ............................................................................................................ 72
Shutting Down................................................................................................................72
Changing Runlevels with init and telinit ......................................................................... 72
Managing Services .............................................................................................. 73

Chapter 4: X Window System ............................................................................... 75


Basic X Concepts .................................................................................................. 75
Introduction ...................................................................................................................75
The X11R7.1 Release ...................................................................................................... 75
Desktop Environments and Window Managers .................................................... 76
Introduction ...................................................................................................................76
Desktop Environments ................................................................................................... 76
Window Managers ......................................................................................................... 76
6 Linux System and Networking Administration

X Server Configuration Files ................................................................................. 77


The GNOME and KDE Desktops ............................................................................ 78
Overview ........................................................................................................................78
GNOME Features ............................................................................................................ 79
Sawfish Window Manager ............................................................................................................ 79
Using GNOME ............................................................................................................................... 79
KDE Features ..................................................................................................................80
Default Desktop .................................................................................................. 80
X Window System Configuration .......................................................................... 81
Introduction ...................................................................................................................81
Display Settings .............................................................................................................. 81
Display Hardware Settings .............................................................................................82
Dual Head Display Settings .............................................................................................83

Chapter 5: Performing Administrative Tasks ........................................................ 85


Working with Links .............................................................................................. 85
Introducing Links ............................................................................................................ 85
Using Links Commands ................................................................................................... 85
Changing Owner / Group................................................................................................85
Access Control List ............................................................................................... 86
Introducing Access Control List.......................................................................................86
Steps for Implementing ACL ...........................................................................................86
Managing ACL Lists......................................................................................................... 87
Performing Backup .............................................................................................. 87
What is Backup? ............................................................................................................. 87
Types of Data .................................................................................................................88
Types of Backup ............................................................................................................. 88
Commands for Backup ................................................................................................... 88
tar command ................................................................................................................................ 88
cpio - copy input output Command .............................................................................................. 89
dump and restore Command ....................................................................................................... 89
Taking Remote Backup ................................................................................................... 89
Automation Jobs ............................................................................................................ 89
Working with Partitions....................................................................................... 89
What is Partitioning? ...................................................................................................... 89
Identifying Partitioning Tools .........................................................................................90
Linux System and Networking Administration 7

Naming Conventions ...................................................................................................... 90


Commands for Partitioning ............................................................................................90
Options with fdisk Command ....................................................................................................... 91
Updating Partition Table .............................................................................................................. 91
Formatting of Partition................................................................................................... 91
Mounting File System ..................................................................................................... 92
Converting from Ext2 to Ext3 .........................................................................................93
Converting from Ext3 to Ext2 .........................................................................................93
Using Labels ...................................................................................................................93
Working with Swap Partition .........................................................................................94
Using Quotas ....................................................................................................... 95
Introducing Quotas ........................................................................................................ 95
Advantages of Quotas .................................................................................................... 95
Types of Quotas ............................................................................................................. 95
Applying Quota .............................................................................................................. 95
Quotas Creation ............................................................................................................. 95
Understanding RAID ............................................................................................ 96
Introducing RAID in Linux ...............................................................................................96
RAID 0 ............................................................................................................................96
RAID 1 ............................................................................................................................96
RAID 4 ............................................................................................................................97
RAID 5 ............................................................................................................................97
Data Recovery Using RAID..............................................................................................98
RAID Commands............................................................................................................. 98
Working with RPM .............................................................................................. 99
What is RPM? .................................................................................................................99
RPM Pattern ...................................................................................................................99
RPM – Install ................................................................................................................ 100
How to Install Source RPMs ........................................................................................................ 100
RPM – Upgrade ............................................................................................................ 100
RPM – Remove ............................................................................................................. 100
RPM – Query ................................................................................................................ 100
Automatic Updates with yum ............................................................................ 101
Introducing yum ........................................................................................................... 101
Configuring yum ........................................................................................................... 101
Automating yum .......................................................................................................... 102
8 Linux System and Networking Administration

Yum Commands ........................................................................................................... 102


Configuring Yum server with FTP ................................................................................. 102
Troubleshooting ................................................................................................ 103
Recovering Root Password ...........................................................................................103
Assigning Grub Password .............................................................................................103
Recovering Grub Password...........................................................................................103
Other Troubleshooting Techniques .............................................................................. 104
User and Group Administration ......................................................................... 104
Introduction to User and Groups in Linux..................................................................... 104
Types of Users .............................................................................................................. 105
User and Group Administration Database Files ............................................................105
etc/passwd - Database file of Users ........................................................................................... 105
etc/shadow ................................................................................................................................. 105
etc/group .................................................................................................................................... 106
Managing Users............................................................................................................ 106
User Creation .............................................................................................................................. 106
User Modification ....................................................................................................................... 107
User Deletion .............................................................................................................................. 107
Managing Groups ......................................................................................................... 107
Group Creation ........................................................................................................................... 107
Group Modification .................................................................................................................... 107
Group Deletion ........................................................................................................................... 107
Changing User Setting ................................................................................................................ 108
Changing Group Setting .............................................................................................................. 108

Working with Logical Volume Manager (LVM) ................................................... 108


Steps for Configuring LVM............................................................................................108
A. Creating Physical Volume ....................................................................................................... 108
B. Creating Logical Volume Group .............................................................................................. 108
C. Creating a New Volume in a Volume Group ........................................................................... 109
D. Formatting and Mounting The Logical Volume ...................................................................... 109
E. Increasing the Volume Size ..................................................................................................... 109
F. Decreasing the Volume Size.................................................................................................... 110
G. Removing Logical Volume ...................................................................................................... 110
LVM Snapshot .............................................................................................................. 111

Chapter 6: Configuring Networks ....................................................................... 113


Setting Up a Domain Name System Server ......................................................... 113
Introduction ................................................................................................................. 113
Understanding DNS ...................................................................................................... 113
Understanding Authoritative Zones ............................................................................. 114
Understanding BIND..................................................................................................... 114
Linux System and Networking Administration 9

DNS Name Server Example...........................................................................................115


Quick-Starting A DNS Server.........................................................................................116
Identifying Your DNS Servers ...................................................................................................... 116
Creating DNS Configuration Files (named.conf and /var/names/*) ........................................... 117
Starting The Named (DNS) Daemon ........................................................................................... 122
Checking That DNS Is Working ................................................................................................... 122

Configuring Samba ............................................................................................ 124


What is Samba?............................................................................................................ 124
Getting And Installing Samba .......................................................................................125
Configuring A Simple Samba Server ............................................................................. 125
Configuring Samba with SWAT .....................................................................................128
Turning On The SWAT Service .................................................................................................... 128
Starting With SWAT .................................................................................................................... 129
Creating Global Samba Settings In SWAT ................................................................................... 129
Configuring Shared Directories With SWAT ............................................................................... 133
Checking Your Samba Setup With SWAT .................................................................................... 134
Working With Samba Files And Commands ................................................................. 134
Editing the smb.conf File ............................................................................................................ 135
Adding Samba Users ................................................................................................................... 136
Starting The Samba Service ........................................................................................................ 137
Testing Your Samba Permissions ................................................................................................ 137
Checking The Status Of Shared Directories ................................................................................ 137
Setting Up Samba Clients .............................................................................................137
Using Samba Shared Directories From Linux .............................................................................. 138
Using Samba From Nautilus........................................................................................................ 138
Mounting Samba Directories In Linux ........................................................................................ 138
Accessing Samba Shares from Windows Clients ........................................................................ 138

Sharing with Network File System (NFS)............................................................. 139


NFS – A Brief Overview................................................................................................. 139
NFS Server Configuration and Operation...................................................................... 139
Required Packages...................................................................................................................... 139
Starting and Stopping NFS .......................................................................................................... 140
The /etc/exports File .................................................................................................................. 140
Wildcards and Globbing ............................................................................................................. 140
Activating the List of Exports ...................................................................................................... 141
NFS Client Configuration and Operation ...................................................................... 141
NFS and /etc/fstab ...................................................................................................................... 141
Client-Side Helper Processes ...................................................................................................... 141
Diskless Clients ........................................................................................................................... 142

Configuring NIS Clients ...................................................................................... 142


Introduction to NIS ....................................................................................................... 142
NIS Components on Red Hat Linux ............................................................................... 143
The Name Service Switch File .......................................................................................144
10 Linux System and Networking Administration

Configuring the Apache Web Server ................................................................... 145


Introduction to Apache Web Server ............................................................................. 145
Apache 2.2....................................................................................................................145
Installation ...................................................................................................................146
Starting on Reboot ....................................................................................................... 146
The Apache Configuration Files ....................................................................................147
Analyzing the Default Apache Configuration................................................................148
Analyzing httpd.conf .................................................................................................... 148
Basic Apache Configuration for a Simple Web Server...................................................152
Configuring Dynamic Host Configuration Protocol (DHCP) .................................. 152
Introduction ................................................................................................................. 152
Installing DHCP Packages..............................................................................................153
DHCP Server Configuration...........................................................................................153
DHCP and Microsoft Windows .....................................................................................156
Client Configuration ..................................................................................................... 156
DHCP Client Troubleshooting .......................................................................................157
Configuring File Transfer Protocol (FTP) ............................................................. 158
Introduction to FTP ...................................................................................................... 158
FTP Client .....................................................................................................................158
FTP Installation............................................................................................................. 160
anonftp ....................................................................................................................................... 160
WU-FTP ....................................................................................................................................... 160
Configuring a Simple Anonymous FTP Server ...............................................................161
Configuring Telnet ............................................................................................. 161
What is Telnet? ............................................................................................................ 161
Telnet Installation and Configuration........................................................................... 161
Telnet Usage................................................................................................................. 162
Configuring Squid .............................................................................................. 162
What is Squid?.............................................................................................................. 162
Required Packages for Squid ........................................................................................163
Initializing Squid ........................................................................................................... 163
Configuration Options .................................................................................................. 163
Configuring Squid to Act as a Proxy for Web and FTP Service ...................................... 164
Linux System and Networking Administration 11

Chapter 7: Shell Scripting ................................................................................... 165


Shells................................................................................................................. 165
Shell Scripts ....................................................................................................... 165
The echo Command ........................................................................................... 165
Shell Script Example .......................................................................................... 166
Shell Variables ................................................................................................... 166
Creating Variables ............................................................................................. 166
Referencing Variables ........................................................................................ 167
Reading a Value into a Variable......................................................................... 167
Local and Global Shell Variables ........................................................................ 168
Environment Variables ...................................................................................... 168
Special Characters to Use with PS1 .................................................................... 169
Printing $ .......................................................................................................... 169
Command Substitution ...................................................................................... 170
Introduction ................................................................................................................. 170
The test and [] Command .............................................................................................170
expr ..............................................................................................................................170
Backquote ......................................................................................................... 171
Control Flow ...................................................................................................... 172
Introduction ................................................................................................................. 172
The if Construct ............................................................................................................ 172
The if…elif Construct .................................................................................................... 172
The case…esac Construct..............................................................................................173
The while Construct...................................................................................................... 174
The for Construct.......................................................................................................... 174
The exit Command ....................................................................................................... 175
The break and continue Command .............................................................................. 175
File Tests ........................................................................................................... 176
Arithmetic Tests ................................................................................................ 177
String Tests ....................................................................................................... 178
Parameter Handling In Shell Scripts ................................................................... 178
The shift Command............................................................................................ 178
Functions........................................................................................................... 179
12 Linux System and Networking Administration

Chapter 8: Handling Electronic Mail ................................................................... 181


Introduction ...................................................................................................... 181
The Basics of Linux E-Mail .................................................................................. 181
E-Mail in Linux .............................................................................................................. 181
The Mail Transfer Agent ...............................................................................................182
The Mail Delivery Agent ...............................................................................................183
The Mail User Agent ..................................................................................................... 184
Mailx ............................................................................................................................185
Mutt .............................................................................................................................186
Graphical e-mail clients ................................................................................................186
Setting Up Your Server ....................................................................................... 187
sendmail.......................................................................................................................187
Parts of the sendmail program .....................................................................................188
The sendmail.cf file ...................................................................................................... 188
Postfix ..........................................................................................................................190
Parts of the Postfix system ...........................................................................................190
Postfix configuration files .............................................................................................193
Sending a Message with Mailx .......................................................................... 194
The Mutt Program ........................................................................................................ 197
Installing Mutt.............................................................................................................. 197
The Mutt command line ...............................................................................................198

Chapter 9: Implementing Network Using Linux OS ............................................. 201


Getting Introduced to LAN Setup in Linux OS ...................................................... 201
Installing the Hardware ................................................................................................201
Configuring the LAN ..................................................................................................... 201
Using LinuxConf to Configure Ethernet Card ................................................................202
Configuring Nameserver Specification ......................................................................... 202
Configuring Hostname Search Path .............................................................................. 203
Setting up /etc/hosts File .............................................................................................203
Repeating for Every Host..............................................................................................204
Testing the LAN ............................................................................................................ 204
Troubleshooting the LAN..............................................................................................205
Linux System and Networking Administration 13

Summarizing Network Setup in Linux........................................................................... 206


Illustrating Linux Networking Setup ................................................................... 206
Identifying Required Information ................................................................................. 206
Identifying Configuration tools.....................................................................................207
Identifying Analysis Tools .............................................................................................207
Configuring Manually ................................................................................................... 207
Configuring an Interface for Multiple IP Addresses ......................................................208
Configuring IP Address Dynamically ............................................................................. 209
Delving Deep into Networking Files ............................................................................. 209
Understanding Older X Windows Configuration...........................................................211
Overview of Routing..................................................................................................... 212

Chapter 10: Securing Linux Implementation ....................................................... 213


Introduction to Linux Security ............................................................................ 213
Hacker versus Cracker........................................................................................ 213
Understanding Attack Techniques...................................................................... 213
Protecting Against Denial-of-Service Attacks ...............................................................214
Mailbombing ................................................................................................................ 214
Blocking mail with Procmail .........................................................................................214
Blocking mail with sendmail .........................................................................................215
Spam relaying............................................................................................................... 216
Smurf amplification attack ...........................................................................................216
Protecting Against Distributed DOS Attacks ................................................................. 217
Disabling network services ...........................................................................................222
Using TCP wrappers...................................................................................................... 223
Protecting Your Network with Firewalls ............................................................. 225
Introduction ................................................................................................................. 225
Configuring a Simple Firewall .......................................................................................226
Configuring an ipchains firewall ...................................................................................227
Understanding ipchains firewall rules .......................................................................... 228
Changing ipchains firewall rules ...................................................................................231
Saving ipchains Firewall Rules ......................................................................................232
Configuring an iptables Firewall ...................................................................................232
Turning on iptables ...................................................................................................... 233
14 Linux System and Networking Administration

Creating iptables Firewall Rules ...................................................................................234


Understanding iptables ................................................................................................238
Using iptables to do Port Forwarding ........................................................................... 240
Using Logging with iptables ..........................................................................................240
Enhancing your iptables firewall .................................................................................. 240
Detecting Intrusions from Log Files .................................................................... 241
The Role of syslogd....................................................................................................... 243
Redirecting Logs to a loghost with syslogd ................................................................... 244
Understanding the Messages logfile ............................................................................ 245
Monitoring Log Files with LogSentry ............................................................................ 246
Downloading and Installing LogSentry ......................................................................... 246
Setting up LogSentry .................................................................................................... 247
Running LogSentry ....................................................................................................... 247
Using LogSentry............................................................................................................ 247
Configuring LogSentry to Suit Your Needs .......................................................... 249
Changing LogSentry Filter Files .....................................................................................250
logcheck.hacking .......................................................................................................... 251
logcheck.ignore ............................................................................................................ 251
logcheck.violations ....................................................................................................... 252
Using Password Protection ................................................................................ 254
Using a Shadow Password File .....................................................................................255
Using Encryption Techniques ............................................................................. 257
Symmetric Cryptography..............................................................................................257
Public-key Cryptography ..............................................................................................257
Secure Socket Layer...................................................................................................... 258
Creating SSL Certificates ...............................................................................................258
Using third-party certificate signers ............................................................................. 260
Creating a Certificate Service Request.......................................................................... 261
Getting the CSR Signed ................................................................................................. 262
Creating Self-Signed Certificates .................................................................................. 264
Restarting your Web server..........................................................................................265
Troubleshooting your certificates ................................................................................ 265
Exporting Encryption Technology ................................................................................. 266
Using The Secure Shell Package....................................................................................266
Using the ssh, sftp, and scp commands ........................................................................ 266
Linux System and Networking Administration 15

Using ssh, scp and sftp without Passwords .................................................................. 267


Guarding Your Computer with PortSentry .......................................................... 268
Introduction ................................................................................................................. 268
Downloading and installing PortSentry ........................................................................ 269
Using PortSentry as is ................................................................................................... 269
Configuring PortSentry ................................................................................................. 269
Changing the portsentry.conf file ................................................................................. 270
Selecting ports.............................................................................................................. 270
Identifying configuration files ......................................................................................271
Choosing responses ...................................................................................................... 271
Changing the portsentry.modes file ............................................................................. 273
Testing PortSentry........................................................................................................ 273
Tracking PortSentry intrusions .....................................................................................274
Restoring Access........................................................................................................... 275

Chapter 11: Virtualization with Xen ................................................................... 277


What is Virtualization? ...................................................................................... 277
Xen Architecture ................................................................................................ 277
Virtualization Support And Requirements In Red Hat Enterprise Linux 5 ............. 278
Packages for Xen Virtualization ......................................................................... 279
Virtual Machine Creation In Red Hat Enterprise Linux 5 ...................................... 280
Introduction ................................................................................................................. 280
Creating A Virtual Machine with Virtual Machine Manager ......................................... 280
Creating A Virtual Machine With virt-install................................................................. 281
Red Hat Enterprise Linux 5 Xen Configuration And Log Files ............................... 281
Virtual Machine Management Commands ......................................................... 282
16 Linux System and Networking Administration
Linux System and Networking Administration 17

CHAPTER 1: OVERVIEW OF LINUX

Introduction to Linux

Recapitulating Basic Concept of Operating System

Operating System is a collection of programs that coordinates the operation of computer


hardware & software. The major functions of Operating System are:
 Process Management
 Memory Management
 Data Management
 I/O Management

Linux Architecture

The following figure illustrates the architecture of Linux Operating System:

Fig - Linux OS Architectural Components

What is Kernel?
 A set of functions that make up the heart of an OS
 It is used to provide an application interface between programs and physical
devices.
 Services provided by the kernel Controls execution of processes.
 Scheduling processes fairly for execution on the CPU.
 Allocating memory for an executing process.
18 Linux System and Networking Administration

What is Shell?
 Shell is the interface between the user and the kernel.
 Services provided by the shell
1. It interprets all the commands to the kernel
2. The kernel after processing the commands gives back to the shell.

History of Unix

Multics Project
 It was started in 1965 on Mainframe GE 645 by the joint effort of
o AT & T Bell Labs
o General Electricals
o Massachusetts Institute of Technology (MIT)
 Multics was written in Assembly Language
 In 1969 Multics project was dropped.

Unix History
 In 1969, Ken Thompson & Dennis Ritchie at Bell Labs - AT&T redesigned the
Multics and introduced New OS - UNICS (Uniplexed Information & computing
system)
 It is written in 80 percent of C language and 20 percent assembly language.
 Later on totally rewritten in C language and named as UNIX (1973).

Flavours of Unix

The following table lists the different flavors of Unix OS and the corresponding vendors:

Unix Flavor Vendor

SYS III – SYS V AT & T, Bell Labs

SunOS - Solaris Sun

AIX IBM

IRIX SG

SCO Unix SCO

Free BSD Linux Linux

HPUX HP

Evolution of Linux

Around 1991, Linus Torvalds, a student at the University of Helsinki, Finland, was working
on Minix, an operating system similar to Unix. Linus Torvalds was impressed with the
features of the Unix operating system. He wanted to create his own version of the Unix
operating system and give it free of charge for use to everybody. Torvalds worked on the
Linux System and Networking Administration 19

project, wrote the source code for the kernel, and named it Linux. The kernel was the core
program of the Linux operating system. Torvalds made the Linux kernel available on the
Internet.
The Linux kernel was combined with the GNU system resulting in a complete operating
system. This operating system was called GNU/Linux because it was a combination of the
GNU system and Linux as the kernel. The GNU/Linux operating system is referred to as the
Linux operating system.
The Internet has played a major role in the development of the Linux operating system.
Today, many companies provide support for Linux on the Internet. Many Linux forums on
the Internet allow free registration and subscription to the latest information.
Linux has an official mascot – the Linux penguin, called Tux, which was selected by Linus
Torvalds to represent the image he associates with the operating system he created. The
following figure shows the Linux official mascot:

Fig – Tux

Features of the Linux Operating System

The following features can be outlined in the Linux operating system:


 Multiprogramming: Linux allows many programs to be executed simultaneously by
different users. This feature is called multiprogramming.
 Time-sharing: Multiprogramming is made possible on the Linux system by the
concept of time-sharing. The operating system has to manage the various
programs to be executed. The programs are ‘queued’ and CPU time is shared
among them. Each program gets CPU time for a specific period and is then put
back in the queue to wait its turn again as the next program in the queue is
attended.
 Multitasking: A program in Linux is broken down into tasks, each task being,
reading from or writing to the disk, or waiting for input from a user. The ability of
any operating system to handle the execution of multiple tasks is known as
multitasking. When a task is waiting for the completion of an activity, the CPU,
instead of wasting time, starts executing the next task. Therefore, while one task
is waiting for input from the user, another program could be reading from the hard
disk. To explain the concept of multitasking, consider an example where you are
having a cup of coffee, reading a book, and talking to your friend over the phone.
You are performing more than one task simultaneously. However, at a given point
in time, you would be sipping coffee, reading the book, or speaking on the phone.
As you notice, you divide your time into smaller units and in each unit of time; you
would be doing only one of the tasks. Similarly, the CPU divides the time between
all the active tasks. The kernel is responsible for scheduling the tasks.
20 Linux System and Networking Administration

 Virtual memory: The amount of physical memory may not always be sufficient for
executing large applications or for having multiple applications active at a point in
time. In such situations, Linux makes a partition, which is a portion of the hard
disk, available for use as the virtual memory. The system places the programs and
data that are not frequently required on this portion of the hard disk and loads
them in the memory, whenever required. Therefore, it uses the resources of the
computer to the optimum.
 Shared libraries: These are sets of functions or sub-routines maintained as a set of
files. All the applications that use these functions access the functions from the
shared library files instead of individually maintaining code for the functions, thus
saving hard disk space and memory.
 POSIX-Compliance: Linux is POSIX-compliant and supports most of the standards
set for all Unix systems.
 Samba: The name, Samba, is derived from the Server Message Block protocol or
SMB. SMB is the protocol used by the Microsoft operating systems to share file and
print services. Samba is a suite of programs that implement the SMB protocol in
Linux. Using Samba, you can share a Linux file system with the Windows operating
system. You can also share a Windows file system with Linux. SMB also enables
the sharing of printers connected to either Linux or the Windows operating system.
 Network Information Service (NIS): It is possible to share passwords and group
files across a network in Linux using the Network Information Service (NIS). In
effect, NIS is a client and server database system. It is a central database of
account information that is used for account authentication. It was developed by
Sun Microsystems and was originally known as Yellow Pages (YP). Later, its name
was changed to NIS due to trademark issues.
 Cron scheduler: Linux has a scheduler program called cron. It is used to run
commands, scripts, or programs at scheduled times.
 Office suites: Linux supports OpenOffice.org, an application program that has
many in-built tools. OpenOffice.org enables you to create documents,
presentations, and illustrations and analyze data. Working on OpenOffice.org is
similar to working on Microsoft Office Application for Windows.
 Data archiving utilities: Linux provides utilities for basic data backup (archiving),
such as tar, cpio, and dd. Advanced Maryland Automatic Network Disk Archiver or
Amanda is a backup system supported by Linux. It enables the LAN administrator
in setting up a master backup server and makes back up for multiple hosts in a
large capacity tape drive.
 Licensing: Linux is a copyright under the GNU General Public License. The licensing
for Fedora states that a person can download, install, or use the software and any
updates to the software, regardless of the delivery mechanism.
 Web server: A Web server is the software that serves Web pages. Linux comes
with the Apache Web server, which is the most popular Web server in use today.
Apache also supports the Squid proxy server that helps in improving the
performance for accessing the Internet.
 Other Features: Linux comes with many other useful and free software such as
text editors, browsers, and scientific applications.

Advantages of Linux

The Linux operating system has the following advantages:


 Reliability: Linux is a stable operating system. Linux servers are not shut down for
years together. This means that users on the Linux operating system work
consistently with the Linux server without reporting any operating system failures.
 Backward compatibility: Linux is said to be backward compatible. This implies that
Linux has excellent support for earlier hardware. It can run on different types of
Linux System and Networking Administration 21

processors, including 386 and 486 Intel processors. It also runs well on DEC Alpha
processor, Sun SPARC machine, PowerPC and SGI MIPS.
 Simple upgrade and installation process: The installation procedure of most Linux
versions is menu-driven and easy. It includes the ability to upgrade from prior
versions. The upgrade process preserves the existing configuration files and
maintains a list of its actions during installation.
 Low total cost of ownership: Linux and most of the packages that come with it are
free. Therefore, the total cost of ownership in procuring Linux server software is
low. In addition, there are a lot of people and organizations providing free support
for Linux so the cost of support can also reduce. The system configuration
requirements for installing a Linux computer are less. For this reason, the
hardware cost goes down.
 Support for legacy devices: Linux can run on a computer with low configuration,
such as a 386 DX. Users who have low configuration computers prefer to use Linux
compared to any other operating systems, which require higher configuration.
 GUI interface: The graphical interface for Linux is the X Window system. It is
divided into two subsystems consisting of a server and a client. Linux has a
number of graphical user interfaces called Desktop Environments, such as K
Desktop Environment (KDE) and GNU Object Model Environment (GNOME), both of
which are versions of the X Window system. They run on the X server. When you
startup KDE, the desktop is organized into folders such as Trash and Start Here.
Icons represent these folders pictorially. When you click an icon, the K file
manager pops up a browser window. GNOME can be configured in the way you
want to use it. It supports the drag-and-drop mechanism. GNOME follows the
Common Object Request Broker Architecture (CORBA) standards to allow different
software to communicate easily.
 Multiple distributors: Linux is offered by many organizations, each with their own
added features. Therefore, the user has various options available. Some
distributions of Linux are Red Hat, SuSE, Mandrake, Debian, and Slackware.
 No known viruses: Linux is said to be free of any virus attack. So far, there are no
known viruses for Linux.
 Excellent security features: Linux offers high security. This is the reason why many
Internet Service Providers are replacing their current operating systems with
Linux.
 Support for high user load: Linux can support a large number of users working
simultaneously.
 Support for development libraries: Linux offers an excellent platform for many
development languages, such as C, C++, JAVA, Python, and Perl. It also supports
Integrated Development Environments such as KDevelop and Glade.

Explaining How Linux Architecture Works

The following figure illustrates how each component of Linux architecture interacts with
each other:
22 Linux System and Networking Administration

Fig - Intercommunication between Linux OS Components

Identifying Distributors of Linux

Many distributors provide Linux. All the distributors use the Linux kernel. These
distributors add their own utilities and applications and sell the utilities as a customized
package.
There are currently over three hundred Linux distribution projects in active development,
constantly revising and improving their respective distributions. One can distinguish
between commercially backed distributions, such as Fedora (Red Hat), SUSE Linux
(Novell), Ubuntu (Canonical Ltd.), and Mandriva Linux and community distributions such as
Debian and Gentoo. The procedures for assembling and testing a distribution prior to
release tend to become more elaborate the larger the user base.
Well-known Linux distributions include:
 CentOS, a distribution derived from the same sources used by Red Hat, maintained
by a dedicated volunteer community of developers with both 100% Red Hat -
compatible versions and an upgraded version that is not always 100% upstream
compatible
 Debian, a non-commercial distribution maintained by a volunteer developer
community with a strong commitment to free software principles
 Fedora which is a community distribution sponsored by Red Hat
 Gentoo, a distribution targeted at power users, known for its FreeBSD Ports-like
automated system for compiling applications from source code
 Knoppix, a LiveCD distribution that runs completely from removable media and
without installation to a hard disk
 Linspire, a commercial desktop distribution based on Ubuntu (and thus Debian),
and once the defendant in the Microsoft vs. Lindows lawsuit over its former name.
 Mandriva, a Red Hat derivative popular in France and Brazil, today maintained by
the French company of the same name
 openSUSE, originally derived from Slackware, sponsored by the company Novell
 PCLinuxOS which is the number 1 distribution on DistroWatch
 Red Hat Enterprise Linux, which is a derivative of Fedora maintained and
commercially supported by Red Hat
 Slackware, one of the first Linux distributions, founded in 1993, and since then
actively maintained by Patrick J. Volkerding
Linux System and Networking Administration 23

 Ubuntu, a newly popular desktop distribution maintained by Canonical that is


derived from Debian.
DistroWatch maintains a popularity ranking of distribution information on its web site, but
this is not considered to be a reliable measure of distribution popularity.

Introducing Red Hat Enterprise Linux

Red Hat Enterprise Linux (often abbreviated as RHEL) is a Linux distribution produced by
Red Hat and targeted toward the commercial market, including mainframes. Red Hat
commits to supporting each version of RHEL for 7 years after its release. All of Red Hat's
official support, all of Red Hat's training and the Red Hat Certification Program center on
the Red Hat Enterprise Linux platform.
New versions of RHEL are released every 18 to 24 months. When Red Hat releases a new
version of RHEL, customers may upgrade to the new version at no additional charge as
long as they are in possession of a current subscription (i.e. the subscription term has not
yet lapsed).
Red Hat's first Enterprise offering (Red Hat Linux 6.2E) essentially consisted of a version of
Red Hat Linux 6.2 with different support levels, and without separate engineering.
The first version of RHEL to bear the name originally came onto the market as "Red Hat
Linux Advanced Server". In 2003 Red Hat rebranded Red Hat Linux Advanced Server to
"Red Hat Enterprise Linux" (RHEL) AS, and added two more variants, RHEL ES and RHEL
WS.
Verbatim copying and redistribution of the entire RHEL distribution is not permitted due to
trademark restrictions. However, there are several redistributions of RHEL minus
trademarked features (such as logos and the name).
As of 2005 Red Hat distributed four variants of RHEL (AS/ES/WS expansions are
unofficial):
 RHEL AS (“Advanced Server”) – Used for large servers and supports up to 16
CPUs. This operating system supports databases, Enterprise Resource Planning
(ERP), and Customer Relationship Management (CRM) applications.
 RHEL ES (“Edge Server”, “Economy Server”, or “Entry -level Server”) – Used for
small and middle range servers and supports up to two CPUs. It is used for
business applications, such as printing, mailing, and networking applications.
 RHEL WS (“Workstation”) – Used as desktop operating system and supports up to
two CPUs. This operating system is compatible with Red Hat Enterprise Linux AS
and Red Hat Enterprise Linux ES. This operating system is suitable for client
applications, such as document processing and software development applications.
 Red Hat Desktop – used for small and medium business environments. It supports
a single CPU. It is compatible with Red Hat Enterprise Linux AS, Red Hat Enterprise
Linux ES, and Red Hat Enterprise Linux WS. This operating system is suitable for
document processing, browsing, software development, and instant messaging.
In RHEL 5 there are new editions that substitute former RHEL AS/ES/WS/Desktop:
 RHEL Advanced Platform (former AS)
 RHEL (former ES)
 RHEL Desktop with Workstation and Multi-OS option
 RHEL Desktop with Workstation option (former WS)
 RHEL Desktop with Multi-OS option
 RHEL Desktop (former Desktop)
24 Linux System and Networking Administration

Installing/Upgrading Red Hat Enterprise Linux 5

Performing Pre-Installation Tasks

Before you can even start installing RHEL, you first check the hardware compatibility of all
hardware devices connected to your computer. Hardware compatibility is particularly
important if you have an older system or a system that you built yourself. Red Hat
Enterprise Linux 5 should be compatible with most hardware in systems that were factory
built within the last two years. However, hardware specifications change almost daily, so it
is difficult to guarantee that your hardware is 100% compatible.
The most recent list of supported hardware can be found at:
http://hardware.redhat.com/hcl/
In addition, check whether your system has enough hard disk space. The disk space used
by Red Hat Enterprise Linux must be separate from the disk space used by other OSes you
may have installed on your system, such as Windows, OS/2, or even a different version of
Linux. This can be performed by partitioning the hard disk. Disk partitioning is the creation
of divisions of a hard disk.
For x86, AMD64, and Intel® 64 systems, at least two partitions (/ and swap) must be
dedicated to Red Hat Enterprise Linux. For Itanium systems, at least three partitions (/,
/boot/efi/, and swap) must be dedicated to Red Hat Enterprise Linux.
Before you start the installation process, you must
 have enough unpartitioned1 disk space for the installation of Red Hat Enterprise
Linux, or
 have one or more partitions that may be deleted, thereby freeing up enough disk
space to install Red Hat Enterprise Linux.
To gain a better sense of how much space you really need, refer to the following
recommended partitioning sizes:
 A swap partition (at least 256 MB): Swap partitions are used to support virtual
memory. In other words, data is written to a swap partition when there is not
enough RAM to store the data your system is processing.
If you are unsure about what size swap partition to create, make it twice the
amount of RAM on your machine. It must be of type swap.
 A /boot/ partition (100 MB): The partition mounted on /boot/ contains the
operating system kernel (which allows your system to boot Red Hat Enterprise
Linux), along with files used during the bootstrap process. Due to limitations,
creating a native ext3 partition to hold these files is required. For most users, a
100 MB boot partition is sufficient.
 A root partition (3.0 GB - 5.0 GB): This is where "/" (the root directory) is located.
In this setup, all files (except those stored in /boot) are on the root partition.
A 3.0 GB partition allows you to install a minimal installation; while a 5.0 GB root
partition lets you perform a full installation, choosing all package groups.

An Overview of Installation Methods

One of the many strengths of the Red Hat Enterprise Linux installation program is that the
installation files can be retrieved in a variety of ways. For example, if you are only
installing one or two systems, performing a traditional CD-ROM installation is probably
easiest because it requires minimal setup time. However, if you are installing tens or
hundreds of systems on the same network, the time it takes to set up a centralized
installation source with the necessary files will ultimately save the administrator time and
allow the administrator to scale his efforts. The installation CDs do not have to be swapped
out of each machine as they are needed. To perform simultaneous installs on all the
Linux System and Networking Administration 25

systems, all the systems can be booted using PXE instead of burning a set of CDs for each
system, and they can all be installed from one set of installation files shared over the
network.
Note that you do not have to standardize on just one installation method. A combination of
methods might work best for you.
The following installation methods are available:
 CD-ROM
Installing from a set of installation CDs is the most direct method. Insert the media
into the system, make sure the BIOS is configured to boot off the CD, and boot the
system. The administrator is stepped through the process from keyboard and
language selection to choosing which software sets to install.
 Hard Drive
Installing from the hard drive requires the ISO images of the installation CDs to be
on a hard drive partition accessible by the installation program (formatted as ext2,
ext3, or vfat). It also requires a boot CD created from the boot.iso image found on
the first installation CD.
 Network Install (via NFS, FTP, or HTTP)
This method also requires a boot CD created from the boot.iso image or PXE boot.
After booting, select the preferred network installation method (NFS, FTP, or
HTTP). The installation source must be available to the system using the selected
network protocol.
 Kickstart
Kickstart is the name of the Red Hat scripted installation method. A kickstart
formatted script is written; the installation program is started with a boot CD or via
PXE and then given the location of the kickstart file.
 PXE
PXE, or Pre-Execution Environment, is available on some Network Interface Cards
(NICs) and can be used to perform a network installation by connecting to a
network file server and booting from files retrieved over the network instead of
from local media such as a CD.
 Red Hat Network Provisioning
This method requires an additional subscription to the RHN Provisioning module
and an RHN Satellite Server. The web interface to the RHN Satellite Server
includes a Kickstart Profile creation wizard, which can be used to create and store
a customized kickstart file. Then the clients are installed from this kickstart file.
Here we will discuss only the CD-ROM installation method.

Performing the Installation from the CD/DVD

The required steps are listed below:


1. Insert the first installation CD, make sure the BIOS is configured to boot off the
CD-ROM device, and start the computer. Before the welcome screen appears, you
are prompted to run the mediacheck program to verify each installation CD.
After successful verification, the welcome screen appears. This is shown in the
following figure:
26 Linux System and Networking Administration

Fig – Displaying Red Hat Enterprise Linux 5 Welcome Screen


2. Click Next. You will be prompted to select the language to use for the installation.
Using your mouse, select a language to use for the installation. The language you
select here will become the default language for the operating system once it is
installed. Selecting the appropriate language also helps target your time zone
configuration later in the installation. The installation program tries to define the
appropriate time zone based on what you specify on this screen. The language
selection screen is shown below:
Linux System and Networking Administration 27

Fig – Selecting Language


3. Click Next. You will be prompted to select the keyboard layout. Using your mouse,
select the correct layout type (for example, U.S. English) for the keyboard you
would prefer to use for the installation and as the system default, refer to the
figure below:
28 Linux System and Networking Administration

Fig – Selecting the Keyboard Layout


4. Click Next. You will be prompted to enter your Installation Number. This number
will determine the package selection set that is available to the installer. If you
choose to skip entering the installation number you will be presented with a basic
selection of packages to install later on.
The installation program then searches for existing installations. If one is found,
the following two options are displayed:
o Install Red Hat Enterprise Linux
o Upgrade an existing installation
5. Select Install Red Hat Enterprise Linux option to perform a clean installation of
RHEL. You will be prompted to partition your hard disk. The different disk
partitioning options available are:
o Remove all partitions on selected drives and create default layout: Select
this option to remove all partitions on your hard drive(s) (this includes
partitions created by other operating systems such as Windows VFAT or
NTFS partitions).
o Remove Linux partitions on selected drives and create default layout:
Select this option to remove only Linux partitions (partitions created from a
previous Linux installation).This does not remove other partitions you may
have on your hard drive(s) (such as VFAT or FAT32 partitions).
o Use free space on selected drives and create default layout: Select this
option to retain your current data and partitions, assuming you have
enough free space available on your hard drive(s).
o Create custom layout: Select this option to manually partitioning the hard
disk using a utility called Disk Druid.
The first three options allow you to perform an automated installation without
having to partition your drive(s) yourself. If you do not feel comfortable with
partitioning your system, it is recommended that you do not choose to create a
custom layout and instead let the installation program partition for you.
The various disk partitioning methods are shown in the following figure:
Linux System and Networking Administration 29

Fig – Identifying Disk Partitioning Methods


6. Select a method for partitioning as shown below:

Fig – Selecting a Partitioning Scheme


Using your mouse, choose the storage drive(s) on which you want Red Hat
Enterprise Linux to be installed. If you have two or more drives, you can choose
30 Linux System and Networking Administration

which drive(s) should contain this installation. Unselected drives, and any data on
them, are not touched.
7. Click Next. You will be prompted to specify the boot loader. A boot loader must be
installed to boot into the operating system. The GRUB boot loader is installed by
default as shown below:

Fig – Configuring Boot Loader


In this screen, you can also select the option, enabling a boot loader password.
Enter a password and confirm it. If you are installing a boot loader, you should
create a password to protect your system. Without a boot loader password, users
with access to your system can pass options to the kernel which can compromise
your system security. With a boot loader password in place, the password must
first be entered before selecting any non-standard boot options.
If you do not want to install GRUB as your boot loader, click Change boot loader,
where you can choose not to install a boot loader at all.
If you already have a boot loader that can boot Red Hat Enterprise Linux and do
not want to overwrite your current boot loader, choose Do not install a boot loader
by clicking on the Change boot loader button.
8. Click Next. You will be prompted to configure network connections. The installation
program automatically detects any network devices you have and displays them in
the Network Devices list.
If you have a hostname (fully qualified domain name) for the network device, you
can choose to have DHCP (Dynamic Host Configuration Protocol) automatically
detect it or you can manually enter the hostname in the field provided.
Finally, if you entered the IP and Netmask information manually, you may also
enter the Gateway address and the Primary and Secondary DNS addresses.
The following figure shows the network configuration screen:
Linux System and Networking Administration 31

Fig – Configuring Network Devices


To configure a network device, select the network device and click Edit. From the
Edit Interface pop-up screen, you can choose to configure the IP address and
Netmask (for IPv4 - Prefix for IPv6) of the device via DHCP (or manually if DHCP is
not selected) and you can choose to activate the device at boot time. If you select
Activate on boot, your network interface is started when you boot. If you do not
have DHCP client access or you are unsure what to provide here, please contact
your network administrator.
9. After completing network configuration settings, click Next. You will be prompted
for time zone setting. Set your time zone by selecting the city closest to your
computer's physical location. Click on the map to zoom in to a particular
geographical region of the world. The Time Zone configuration screen is shown
below:
32 Linux System and Networking Administration

Fig - Configuring the Time Zone


10. Click Next. The installation program prompts you to set a root password for your
system. You cannot proceed to the next stage of the installation process without
entering a root password.
The root password must be at least six characters long; the password you type is
not echoed to the screen. You must enter the password twice; if the two
passwords do not match, the installation program asks you to enter them again.
The root password screen is shown below:
Linux System and Networking Administration 33

Fig – Specifying Root Password


11. Click Next. The Package Installation Defaults screen appears and details the
default package set for your Red Hat Enterprise Linux installation. This screen
varies depending on the version of Red Hat Enterprise Linux you are installing.
If you choose to accept the current package list, skip this step.
To customize your package set further, select the Customize now option on the
screen. Clicking Next takes you to the Package Group Selection screen.
You can select package groups, which group components together according to
function (for example, X Window System and Editors), individual packages, or a
combination of the two.
To select a component, click on the checkbox beside it.
The following figure shows a Package Group Selection screen:
34 Linux System and Networking Administration

Fig – Selecting a Package Group


12. Once a package group has been selected, if optional components are available you
can click on Optional packages to view which packages are installed by default,
and to add or remove optional packages from that group. If there are no optional
components this button will be disabled.
The following figure shows Package Details screen:
Linux System and Networking Administration 35

Fig – Selecting Optional Packages


13. Click Next. The installation will start. As the software is installed, the progress is
shown as a time estimate and a progress bar. As you are performing a CD
installation, a popup window is displayed when the next CD is needed.
When all the necessary files are installed and all post-installation actions such as
writing the bootloader are complete, the final screen will be displayed confirming
that installation is completed successfully.
The installation program prompts you to prepare your system for reboot. Remember to
remove any installation media if it is not ejected automatically upon reboot.
After your computer's normal power-up sequence has completed, the graphical boot loader
prompt appears at which you can do any of the following things:
 Press Enter: causes the default boot entry to be booted.
 Select a boot label, followed by Enter: causes the boot loader to boot the operating
system corresponding to the boot label.
 Do nothing: after the boot loader's timeout period, (by default, five seconds) the
boot loader automatically boots the default boot entry.
Do whatever is appropriate to boot Red Hat Enterprise Linux. One or more screens of
messages should scroll by. Eventually, a login: prompt or a GUI login screen (if you
installed the X Window System and chose to start X automatically) appears.

Performing an Upgrade

If the system already has an older version of Red Hat Enterprise Linux installed, it can be
upgraded, preserving the data on the system while upgrading the packages to the latest
versions.
To perform an upgrade, choose Upgrade an existing installation during the interactive
installation.

CAUTION:
Even if you are not reformatting partitions with data that needs to be preserved, it is
important that you back up all data before performing the upgrade in case an error occurs.

When performing an upgrade, the steps are similar to those described in the previous
section “Performing the Installation from the CD/DVD”. However, some screens are
omitted because their operations are not permitted for upgrades. For example, the system
cannot be repartitioned because it would cause data loss.
36 Linux System and Networking Administration
Linux System and Networking Administration 37

CHAPTER 2: LINUX FILESYSTEM AND COMMANDS

Understanding Filesystem Structure

Introduction

Red Hat is committed to the Filesystem Hierarchy Standard (FHS), a collaborative


document that defines the names and locations of many files and directories. We will
continue to track and follow the standard to keep Red Hat Linux compliant.
The current FHS document is the authoritative reference to any FHS compliant filesystem,
but the standard leaves many areas undefined or extensible. In this section we provide an
overview of the standard and a description of the parts of the filesystem not covered by
the standard.
The complete standard can be viewed at:

http://www.pathname.com/fhs/

Compliance with the standard means many things, but the two most important are
compatibility with other compliant systems, and the ability to mount the /usr partition as
read-only (because it contains common executables and is not meant to be changed by
users). Since /usr can be mounted read-only, /usr can be mounted from the CD-ROM or
from another machine via read-only NFS.

Overview of the FHS

The directories and files noted here are small subsets of those specified by the FHS
document. Check the latest FHS document for the most complete information.

The /dev Directory


The /dev directory contains filesystem entries which represent devices that are attached to
the system. These files are essential for the system to function properly.

The /etc Directory


The /etc directory is reserved for configuration files that are local to your machine. No
binaries are to be put in /etc. Any binaries that were formerly put in /etc should now go
into /sbin or possibly /bin.
The X11 and skel directories should be subdirectories of /etc:

/etc
|- X11
+- skel

The X11 directory is for X11 configuration files such as XF86Config. The skel directory is
for "skeleton" user files, which are used to populate a home directory when a user is first
created.
38 Linux System and Networking Administration

The /lib Directory


The /lib directory should contain only those libraries that are needed to execute the
binaries in /bin and /sbin.

The /proc Directory


The /proc directory contains special files that either extract information or send
information to the kernel. /proc provides an easy method of accessing information about
the operating system using the cat command.

The /sbin Directory


The /sbin directory is for executables used only by the root user. The executables in /sbin
are only used to boot and mount /usr and perform system recovery operations. The FHS
says:
"/sbin typically contains files essential for booting the system in addition to the binaries in
/bin. Anything executed after /usr is known to be mounted (when there are no problems)
should be placed in /usr/sbin. Local-only system administration binaries should be placed
into /usr/local/sbin."
At a minimum, the following programs should be in /sbin:

arp, clock, getty, halt, init, fdisk,


fsck.*, ifconfig, lilo, mkfs.*, mkswap, reboot,
route, shutdown, swapoff, swapon, update

The /usr Directory


The /usr directory is for files that can be shared across a whole site. The /usr directory
usually has its own partition, and it should be mountable read-only. The following
directories should be subdirectories of /usr:

/usr
|- X11R6
|- bin
|- doc
|- etc
|- games
|- include
|- lib
|- libexec
|- local
|- sbin
|- share
+- src

The X11R6 directory is for the X Window System (XFree86 on Red Hat Linux), bin contains
executables, doc contains non-manpage documentation, etc contains site-wide
configuration files, games is for (you guessed it!) games, include contains C header files,
lib contains libraries, libexec contains small helper programs called by other programs,
sbin is for system administration binaries (those that do not belong in /sbin), share
contains files that aren't architecture-specific, and src is for source code.
Linux System and Networking Administration 39

The /usr/local Directory


The FHS says:
"The /usr/local hierarchy is for use by the system administrator when installing software
locally. It needs to be safe from being overwritten when the system software is updated. It
may be used for programs and data that are shareable amongst a group of machines, but
not found in /usr."
The /usr/local directory is similar in structure to the /usr directory. It has the following
subdirectories, which are similar in purpose to those in the /usr directory:

/usr/local
|- bin
|- doc
|- etc
|- games
|- info
|- lib
|- man
|- sbin
+- src

The /var Directory


Since the FHS requires that you be able to mount /usr read-only, any programs that write
log files or need spool or lock directories probably should write them to the /var directory.
The FHS states /var is for:
"…variable data files. This includes spool directories and files, administrative and logging
data, and transient and temporary files."
The following directories should be subdirectories of /var:

/var
|- cache
|- db
|- ftp
|- gdm
|- lib
|- local
|- lock
|- log
|- named
|- nis
|- opt
|- preserve
|- run
+- spool
40 Linux System and Networking Administration

|- anacron
|- at
|- cron
|- fax
|- lpd
|- mail
|- mqueue
+- news
|- rwho
|- samba
|- slrnpull
|- squid
|- up2date
|- uucp
|- uucppublic
|- vbox
|- voice
|- tmp
|- yp

System log files such as wtmp and lastlog go in /var/log. The /var/lib directory also
contains the RPM system databases. Lock files go in /var/lock. The /var/spool directory has
subdirectories for various systems that need to store data files.

/usr/local in Red Hat Linux


In Red Hat Linux, the intended use for /usr/local is slightly different from that specified by
the FHS. The FHS says that /usr/local should be where you store software that is to remain
safe from system software upgrades. Since system upgrades from Red Hat are done safely
with the RPM system and Gnome-RPM, you don't need to protect files by putting them in
/usr/local. Instead, we recommend you use /usr/local for software that is local to your
machine.
For instance, let's say you have mounted /usr via read-only NFS from beavis. If there is a
package or program you would like to install, but you are not allowed to write to beavis,
you should install it under /usr/local. Later perhaps, if you've managed to convince the
system administrator of beavis to install the program on /usr, you can uninstall it from
/usr/local.

Working with Basic Commands

Printing Working Directory

You use the pwd command to print the name of the working directory. The usage is:

[root@comp1 ~]# pwd


Linux System and Networking Administration 41

Listing Files and Directories

You use ls command to list files and directories. The general syntax of ls command is given
below:

[root@comp1 ~]# ls <options> <arguments>

The various usages of ls command are illustrated below.

Shows list of files & directories

[root@comp1 ~]# ls

Listing of files and directories along with the attributes

[root@comp1 ~]# ls -l

[or]

[root@comp1 ~]#ll

Listing of all files and directories including the hidden

root@comp1 ~]# ls –a

Listing of all files and directories in reverse order

[root@comp1 ~]# ls –r

Listing of files and directories along with the ‘inode’ numbers

[root@comp1 ~]# ls -il

Listing of the attributes of a particular file or directory

[root@comp1 ~]# ls -ld <directory>

Shows the list of files in Tree structure

[root@comp1 ~]# ls -R <directory>

Creating Files

By using the commands like cat and touch you can create files.

Working with cat Command


The general syntax of cat command for displaying and creating text file is shown below:
42 Linux System and Networking Administration

[root@comp1 ~]# cat <options> <arguments>

The various usage of cat command is illustrated below:


 To create a file

[root@comp1 ~]# cat > <filename>

 To view the content of a file

[root@comp1 ~]# cat <filename>

 To append a file

[root@comp1 ~]# cat >> <filename>

 To transfer the contents of file1 & file2 to file3

[root@comp1 ~]# cat <file1> <file2> >> <file3>

Working with touch Command


The various usages of the touch command are shown below:
 To create a file with zero bytes as well as to change the time stamp of file or
directory.

[root@comp1 ~]# touch <filename>

 To create multiple files

[root@comp1 ~]# touch <file1> <file2> <file3>

Creating Directories

You use the mkdir command to create directories in Linux. The various usages of mkdir
command are illustrated below:
 To create a directory

[root@comp1 ~]# mkdir <directory name>

 To create multiple directories

[root@comp1 ~]# mkdir <dir1> <dir2> <dir3>

 To create nested directories

[root@comp1 ~]# mkdir -p <dir1>/<dir2>/<dir3>

Navigating through Directories

You use the cd command to traverse through a directory. The various usages of the cd
command are illustrated below:
 To change the directory

[root@comp1 ~]# cd <path of the directory>

 To change directory one level back

[root@comp1 ~]# cd ..

 To change directory two levels back

[root@comp1 ~]# cd ../..

 To change directory to last working directory


Linux System and Networking Administration 43

[root@comp1 ~]# cd -

 To change directory to home directory

[root@comp1 ~]# cd

[or]

[root@comp1 ~]# cd ~

Removing a File or Directory

You use the rm and rmdir commands to remove files and directories. The usages are
illustrated below:
 To remove a file

[root@comp1 ~]# rm <filename>

 To remove empty directory

[root@comp1 ~]# rmdir <directory name>

 To remove directory recursively and forcefully

[root@comp1 ~]# rm -rf <directory name>

Copying a File or Directory

You use the cp command for copying a file or a directory. The various usages are
illustrated below:
 To copy a file

[root@comp1 ~]# cp <source file path> <destination file path>

 To copy a directory

[root@comp1 ~]# cp -r <source dir path> <destination dir path>

Moving / Renaming a File or Directory

You use the mv command for moving or renaming a file or directory. The various usages
are:
 To rename file/dir move at same location

[root@comp1 ~]# mv <old name> <new name>

 To move a file/dir to a different location

[root@comp1 ~]# mv <source path> <destination path>

Looking for Files

You have two basic commands for file searches: find and locate.

The find Command


44 Linux System and Networking Administration

The find command searches through directories and subdirectories for a desired file. For
example, if you wanted to find the directory with the XF86Config GUI configuration file,
you could use the following command, which would start the search in the root directory:

[root@comp1 ~]# find / -name XF86Config

But this search on my older laptop computer with a 200 MHz CPU took several minutes.
Alternatively, if you know that this file is located in the /etc subdirectory tree, you could
start in that directory with the following command:

[root@comp1 ~]# find /etc -name XF86Config

The locate Command


Another command useful for finding files is locate. The locate command uses a database
that is updated only daily. So it can't find recently created files and it shows files that may
have been recently deleted. But it operates much more quickly than the find command. To
use the locate command, specify as the command's argument a string of characters, which
need not be enclosed in quotes. The command will list all filenames in its database that
contain the specified characters. For example, the command:

[root@comp1 ~]# locate pass

lists all files containing the characters pass.

Getting into the Files

Now that you see how to find and get around different files, it’s time to start reading the
content of the file. Most Linux configuration files are text files. Linux editors are text
editors. Linux commands are designed to read text files. If in doubt, you can check what
the file type is by using the file command, since Linux doesn’t require a file extension.

The cat Command


The most basic command for reading files is cat. To view the contents of a text file using
cat, simply type the cat command, specifying the name of the text file as an argument. For
example:

[root@comp1 ~]# cat /etc/passwd

displays the contents of the /etc/passwd file, which lists the accounts on the system.
The cat filename command scrolls the text within the filename file. It also works with
multiple filenames; it concatenates the file names that you might list - as one continuous
output to your screen.

The less and more Command


Larger files demand a command that can help you scroll though the file text at your
leisure. Linux has two of these commands: more and less. With the more filename
command, you can scroll through the text of a file, from start to finish, one screen at a
time. With the less filename command, you can scroll in both directions through the same
text with the PAGE UP and PAGE DOWN keys. Both commands support vi-style searches.
The following shows an example of less command:

[root@comp1 ~]# less /etc/passwd

The head and tail Command


The head and tail commands are separate commands that work in essentially the same
way. By default, the head filename command looks at the first 10 lines of a file; the tail
Linux System and Networking Administration 45

filename command looks at the last 10 lines of a file. You can specify the number of lines
shown with the -nxy switch. Just remember to avoid the space when specifying the
number of lines; the

[root@comp1 ~]# tail -n15 /etc/passwd

command lists the last 15 lines of the /etc/passwd file.

Search Text Files Using Regular Expressions

Introduction

Linux offers many tools for system administrators to use for processing text. Many, such
as sed, awk, and perl, are capable of automatically editing multiple files, providing you
with a wide range of text-processing capability. To harness that capability, you need to be
able to define and delineate specific text segments from within files, text streams, and
string variables. Once the text you're after is identified, you can use one of these tools or
languages to do useful things to it.
These tools and others understand a loosely defined pattern language. The language and
the patterns themselves are collectively called regular expressions (often abbreviated just
regexp or regex). While regular expressions are similar in concept to file globs, many more
special characters exist for regular expressions, extending the utility and capability of tools
that understand them.
Two tools that are widely used and that make use of regular expressions are grep and sed.
These tools are useful for text searches. There are many other tools that make use of
regular expressions, including the awk, Perl, and Python languages and other utilities, but
here we will discuss only the sed, grep, egrep, and awk.

Regular Expression Syntax

It would not be unreasonable to assume that some specification defines how regular
expressions are constructed. Unfortunately, there isn't one. Regular expressions have been
incorporated as a feature in a number of tools over the years, with varying degrees of
consistency and completeness. The result is a cart-before-the-horse scenario, in which
utilities and languages have defined their own flavor of regular expression syntax , each
with its own extensions and idiosyncrasies. Formally defining the regular expression syntax
came later, as did efforts to make it more consistent. Regular expressions are defined by
arranging strings of text, or patterns. Those patterns are composed of two types of
characters, literals (plain text or literal text) and metacharacters.
Like the special file globbing characters, regular expression metacharacters take on a
special meaning in the context of the tool in which they're used. There are a few
metacharacters that are generally thought of to be among the "extended set" of
metacharacters, specifically those introduced into egrep after grep was created.
The egrep command on Linux systems is simply a wrapper that runs grep -E. Examples of
metacharacters include the ^ symbol, which means "the beginning of a line," and the $
symbol, which means "the end of a line." A complete listing of metacharacters follows in
the following tables.

Tip:
The backslash character (\) turns off (escapes) the special meaning of the character that
follows, turning metacharacters into literals. For non-metacharacters, it often turns on
some special meaning.
46 Linux System and Networking Administration

Table: Regular expression position anchors

Regular
expression Description

^ Match at the beginning of a line. This interpretation makes sense only


when the ^ character is at the left-hand side of the regex.

$ Match at the end of a line. This interpretation makes sense only when the
$ character is at the right-hand side of the regex.

\<\> Match word boundaries. Word boundaries are defined as whitespace, the
start of line, the end of line, or punctuation marks. The backslashes are
required and enable this interpretation of < and >.

Table: Regular expression character sets

Regular
expression Description

[abc][a-z] Single-character groups and ranges. In the first form, match any single
character from among the enclosed characters a, b, or c. In the second
form, match any single character from among the range of characters
bounded by a and z (POSIX character classes can also be used, so [a-z]
can be replaced with [[:lower:]]). The brackets are for grouping only
and are not matched themselves.

[^abc][^a- Inverse match. Match any single character not among the enclosed
z] characters a, b, and c or in the range a-z. Be careful not to confuse this
inversion with the anchor character ^, described earlier.

. Match any single character except a newline.

Table: Regular expression modifiers

Extended
regular
Basic regular expression
expression (egrep) Description

* * Match an unknown number (zero or more) of the single


character (or single-character regex) that precedes it.

\? ? Match zero or one instance of the preceding regex.

\+ + Match one or more instances of the preceding regex.


Linux System and Networking Administration 47

Table: Regular expression modifiers

Extended
regular
Basic regular expression
expression (egrep) Description

\{n,m\} {n,m} Match a range of occurrences of the single character or


regex that precedes this construct. \{n\} matches n
occurrences, \{n,\} matches at least n occurrences,
and \{n,m\} matches any number of occurrences
from n to m, inclusively.

\| | Alternation. Match either the regex specified before or


after the vertical bar.

\(regex\) (regex) Grouping. Matches regex, but it can be modified as a


whole and used in back-references. (\1 expands to the
contents of the first \(\) and so on up to \9.)

It is often helpful to consider regular expressions as their own language, where literal text
acts as words and phrases. The "grammar" of the language is defined by the use of
metacharacters. The two are combined according to specific rules (which, as mentioned
earlier, may differ slightly among various tools) to communicate ideas and get real work
done. When you construct regular expressions, you use metacharacters and literals to
specify three basic ideas about your input text:
Position anchors
A position anchor is used to specify the position of one or more character sets in relation to
the entire line of text (such as the beginning of a line).

Character sets
A character set matches text. It could be a series of literals, metacharacters that match
individual or multiple characters, or combinations of these.

Quantity modifiers
Quantity modifiers follow a character set and indicate the number of times the set should
be repeated.

Using grep

A long time ago, as the idea of regular expressions was catching on, the line editor ed
contained a command to display lines of a file being edited that matched a given regular
expression. The command is:

g/regular expression /p
48 Linux System and Networking Administration

That is, "on a global basis, print the current line when a match for regular expression
is found," or more simply, "global regular expression print." This function was so useful
that it was made into a standalone utility named, appropriately, grep. Later, the regular
expression grammar of grep was expanded in a new command called egrep (for "extended
grep"). You'll find both commands on your Linux system today, and they differ slightly in
the way they handle regular expressions. For the purposes of Exam 101, we'll stick with
grep, which can also make use of the "extended" regular expr essions when used with the -
E option. You will find some form of grep on just about every Unix or Unix-like system
available.
Syntax

grep [options

] regex [files]

Description
Search files or standard input for lines containing a match to regular expression regex.
By default, matching lines will be displayed and nonmatching lines will not be displayed.
When multiple files are specified, grep displays the filename as a prefix to the output lines
(use the -h option to suppress filename prefixes).

Frequently used options


-c
Display only a count of matched lines, but not the lines themselves.

-h
Display matched lines, but do not include filenames for multiple file input.

-i
Ignore uppercase and lowercase distinctions, allowing abc to match both abc and ABC.

-n
Display matched lines prefixed with their line numbers. When used with multiple files, both
the filename and line number are prefixed.

-v
Print all lines that do not match regex. This is an important and useful option. You'll want
to use regular expressions, not only to select information but also to eliminate information.
Using -v inverts the output this way.

-E
Interpret regex as an extended regular expression. This makes grep behave as if it were
egrep.

Examples
Linux System and Networking Administration 49

Since regular expressions can contain both metacharacters and literals, grep can be used
with an entirely literal regex. For example, to find all lines in file1 that contain either
Linux or linux, you could use grep like this:

$ grep -i linux file1

In this example, the regex is simply linux. The uppercase L in Linux will match since
the command-line option -i was specified. This is fine for literal expressions that are
common. However, in situations in which regex includes regular expression
metacharacters that are also shell special characters (such as $ or *), the regex must be
quoted to prevent shell expansion and pass the metacharacters on to grep.
As a simplistic example of this, suppose you have files in your local directory named abc,
abc1, and abc2. When combined with bash's echo built-in command, the abc* wildcard
expression lists all files that begin with abc, as follows:

$ echo abc*
abc abc1 abc2

Now, suppose that these files contain lines with the strings abc, abcc, abccc , and so
on, and you wish to use grep to find them. You can use the shell wildcard expression abc*
to expand to all the files that start with abc as displayed with echo above, and you'd use
an identical regular expression abc* to find all occurrences of lines containing abc,
abcc, abccc, etc. Without using quotes to prevent shell expansion, the command would
be:

$ grep abc* abc*

After shell expansion, this yields:


grep abc abc1 abc2 abc abc1 abc2 no!

This is not what you intended! grep would search for the literal expression abc, because it
appears as the first command argument. Instead, quote the regular expression with single
or double quotes to protect it:

$ grep 'abc*' abc*

or:

$ grep "abc*" abc*

After expansion, both examples yield the same results:


grep abc* abc abc1 abc2

Now this is what you're after. The three files abc, abc1, and abc2 will be searched for the
regular expression abc*. It is good to stay in the habit of quoting regular expressions on
the command line to avoid these problemsthey won't be at all obvious because the shell
expansion is invisible to you unless you use the echo command.

Using egrep

Search one or more files for lines that match an extended regular expression regexp.
egrep doesn't support the regular expressions \(, \), \n, \<, \>, \{, or \}, but it does
support the other expressions, as well as the extended set +, ?, |, and ( ). Remember to
enclose these characters in quotes. Regular expressions are described earlier. Exit status is
0 if any lines match, 1 if none match, and 2 for errors.
50 Linux System and Networking Administration

The following are examples of use of egrep command:


Search for occurrences of Victor or Victoria in file:

$ egrep 'Victor(ia)*' file egrep '(Victor|Victoria)' file

Find and print strings such as old.doc1 or new.doc2 in files, and include their line
numbers:

$ egrep -n '(old|new)\.doc?' files

Using sed

sed, the stream editor, is a powerful filtering program found on nearly every Unix system.
The sed utility is usually used either to automate repetitive editing tasks or to process text
in pipes of Unix commands (see the section “Use Streams, Pipes, and Redirects," earlier in
this chapter). The scripts that sed executes can be single commands or more complex lists
of editing instructions.
Syntax

sed [options] 'command1' [files]

sed [options] -e 'command1' [-e 'command2'...] [files]

sed [options] -f script [files]

Description
The first form invokes sed with a one-line command1. The second form invokes sed with
two (or more) commands. Note that in this case the -e parameter is required for each
command specified. The commands are specified in quotes to prevent the shell from
interpreting and expanding them. The last form instructs sed to take editing commands
from file script (which does not need to be executable). In all cases, if files are not
specified, input is taken from standard input. If multiple files are specified, the edited
output of each successive file is concatenated.

Frequently used options


-ecmd

The -e option specifies that the next argument ( cmd) is a sed command (or a series of
commands). When specifying only one string of commands, the -e is optional.

-f file

file is a sed script.

-g
Treat all substitutions as global.

The sed utility operates on text through the use of addresses and editing commands. The
address is used to locate lines of text to be operated on, and editing commands modify
Linux System and Networking Administration 51

text. During operation, each line (that is, text separated by newline characters) of input to
sed is processed individually and without regard to adjacent lines. If multiple editing
commands are to be used (through the use of a script file or multiple -e options), they are
all applied in order to each line before moving on to the next line.

Addressing
Addresses in sed locate lines of text to which commands will be applied. The addresses can
be:
 A line number (note that sed counts lines continuously across multiple input files).
The symbol $ can be used to indicate the last line of input. A range of line numbers
can be given by separating the starting and ending lines with a comma
(start,end), so for example the address for all input would be 1,$.

 A regular expression delimited by forward slashes (/regex/).


 A line number with an interval. The form is n~s, where n is the starting line
number and s is the step, or interval, to apply. For example, to match every odd
line in the input, the address specification would be 1~2 (start at line 1 and match
every two lines thereafter). This feature is a GNU extension to sed.
If no address is given, commands are applied to all input lines by default. Any address may
be followed by the ! character, and commands are applied to lines that do not match the
address.

Commands
The sed command immediately follows the address specification if present. Commands
generally consist of a single letter or symbol, unless they have arguments. Following are
some basic sed editing commands to get you started.
d
Delete lines.

s
Make substitutions. This is a very popular sed command. The syntax is as follows:
s/pattern/replacement/[flags]
The following flags can be specified for the s command:

 g:Replace all instances of pattern, not just the first.


 n: Replace nth instance of pattern; the default is 1.
 p: Print the line if a successful substitution is done. Generally used with the -n
command-line option.
 w file: Print the line to file if a successful substitution is done.
 y:Translate characters. This command works in a fashion similar to the tr
command, described earlier.

Example 1
Delete lines 3 through 5 of file1:

$ sed '3,5d' file1

Example 2
52 Linux System and Networking Administration

Delete lines of file1 that contain a # at the beginning of the line:

$ sed '/^#/d' file1

Example 3
Translate characters:
y/abc/xyz/
Every instance of a is translated to x, b to y, and c to z.

Example 4
Write the @ symbol for all empty lines in file1 (that is, lines with only a newline character
but nothing more):

$ sed 's/^$/@/' file1

Example 5
Remove all double quotation marks from all lines in file1:

$ sed 's/"//g' file1

Example 6
Using sed commands from external file sedcmds, replace the third and fourth double
quotation marks with ( and ) on lines 1 through 10 in file1. Make no changes from line 11
to the end of the file. Script file sedcmds contains:
1,10{
s/"/(/3
s/"/)/4
}

The command is executed using the -f option:

$ sed -f sedcmds file1

This example employs the positional flag for the s (substitute) command. The first of the
two commands substitutes ( for the third double-quote character. The next command
substitutes ) for the fourth double-quote character. Note, however, that the position count
is interpreted independently for each subsequent command in the script. This is important
because each command operates on the results of the commands preceding it. In this
example, since the third double quote has been replaced with (, it is no longer counted as
a double quote by the second command. Thus, the second command will operate on the
fifth double quote character in the original file1. If the input line starts out with the
following:
""""""
after the first command, which operates on the third double quote, the result is this:
""("""
Linux System and Networking Administration 53

At this point, the numbering of the double-quote characters has changed, and the fourth
double quote in the line is now the fifth character. Thus, after the second command
executes, the output is as follows:
""(")"

As you can see, creating scripts with sed requires that the sequential nature of the
command execution be kept in mind.
If you find yourself making repetitive changes to many files on a regular basis, a sed script
is probably warranted. Many more commands are available in sed than are listed here.

Examples of Simple Regular Expression

Now that the gory details are out of the way, here are some examples of simple regular
expression usage that you may find useful.

Anchors
Anchors are used to describe position information.

Example 1
Display all lines from file1 where the string Linux appears at the start of the line:

$ grep '^Linux' file1

Example 2
Display lines in file1 where the last character is an x:

$ grep 'x$' file1

Example 3
Display the number of empty lines in file1 by finding lines with nothing between the
beginning and the end:

$ grep -c '^$' file1

Example 4
Display all lines from file1 containing only the word null by itself:

$ grep '^null$' file1

Example 5
Count the number of lines in lots_o_bits which either start with 1 or end with 01

$ egrep -c '^1|01$' lots_o_bits

Groups and Ranges


54 Linux System and Networking Administration

Characters can be placed into groups and ranges to make regular expressions more
efficient.

Example 1
Display all lines from file1 containing Linux, linux, TurboLinux , and so on:

$ grep '[Ll]inux' file1

Example 2
Display all lines from file1 which contain three adjacent digits:

$ grep '[0-9][0-9][0-9]' file1

Example 3
Display all lines from file1 beginning with any single character other than a digit:

$ grep '^[^0-9]' file1

Example 4
Display all lines from file1 that contain the whole word Linux or linux, but not LinuxOS
or TurboLinux:

$ grep '\<[Ll]inux\>' file1

Example 5
Display all lines from file1 with five or more characters on a line (excluding the newline
character):

$ grep '.....' file1

Example 6
Display all nonblank lines from file1 (i.e., that have at least one character):

$ grep '.' file1

Example 7
Display all lines from file1 that contain a period (normally a metacharacter) using an
escape:

$ grep '\.' file1

Example 8
Display all lines from myhello.c that contain a ) using an escape:

$ egrep ‘\)’ myhello.c

Modifiers
Linux System and Networking Administration 55

Modifiers change the meaning of other characters in a regular expression. Table 5-8 lists
these modifiers .

Example 1
Display all lines from file1 that contain ab, abc, abcc, abccc , and so on:

$ grep 'abc*' file1

Example 2
Display all lines from file1 that contain abc, abcc, abccc, and so on, but not ab:

$ grep 'abcc*' file1

Example 3
Display all lines from file1 that contain two or more adjacent digits:

$ grep '[0-9][0-9][0-9]*' file1

or:

$ grep '[0-9]\{2,\}' file1

Example 4
Display lines from file1 that contain file (because ? can match zero occurrences), file1,
or file2:

$ grep 'file[12]\?' file1

Example 5
Display all lines from file1 containing at least one digit:

$ grep '[0-9]\+' file1

Example 6
Display all lines from file1 that contain 111, 1111, or 11111 on a line by itself:

$ grep '^1\{3,5\}$' file1

Example 7
Display all lines from file1 that contain any three-, four-, or five-digit number:

$ grep '\<[0-9]\{3,5\}\>' file1

Example 8
Display all lines from file1 that contain Happy, happy, Sad, sad, Angry , or angry:

$ grep -E '[Hh]appy|[Ss]ad|[Aa]ngry' file1


56 Linux System and Networking Administration

Example 9
Display all lines of file that contain any repeated sequence of abc (abcabc, abcabcabc,
and so on):

$ grep '\(abc\)\{2,\}' file

Example 10
The following would match any character proceeded by "ay" except the combinations
"bay," "cay," and "day."

$ grep '[b-d]ay' *

Basic Regular Expression Patterns


Example 1
Match any letter:
[A-Za-z]

Example 2
Match any symbol (not a letter or digit):
[^0-9A-Za-z]

Example 3
Match an uppercase letter, followed by zero or more lowercase letters:
[A-Z][a-z]*

Example 4
Match a U.S. Social Security Number (123-45-6789) by specifying groups of three, two,
and four digits separated by dashes:
[0-9]\{3\}-[0-9]\{2\}-[0-9]\{4\}

Example 5
Match a dollar amount, using an escaped dollar sign, zero or more spaces or digits, an
escaped period, and two more digits:
\$[ 0-9]*\.[0-9]\{2\}

Example 6
Match the month of June and its abbreviation, Jun. The question mark matches zero or
one instance of the e:
June\?

Using Regular Expressions as Addresses in sed


These examples are commands you would issue to sed. For example, the commands could
take the place of command1 in this usage:

$ sed [options] 'command1 '


Linux System and Networking Administration 57

[files]

These commands could also appear in a standalone sed script.


Example 1
Delete blank lines:
/^$/d

Example 2
Delete any line that doesn't contain #keepme::
/#keepme/!d

Example 3
Delete lines containing only whitespace (spaces or tabs). In this example, Tab means the
single tab character and is preceded by a single space:
/^[ Tab]*$/d

Because GNU sed also supports character classes, this example could be written as
follows:
/^[[:blank:]]*$/d

Example 4
Delete lines beginning with periods or pound signs:
/^[\.#]/d

Example 5
Substitute a single space for any number of spaces wherever they occur on the line:
s/ */ /g

or
s/ \{2,\}/ /g

Example 6
Substitute def for abc from line 11 to 20, wherever it occurs on the line:
11,20s/abc/def/g

Example 7
Translate the characters a, b, and c to the @ character from line 11 to 20, wherever they
occur on the line:
11,20y/abc/@@@/
58 Linux System and Networking Administration

Working with File Permissions

Basic File Permission

The following figure illustrates the long listing of a file:

Fig - Long Listing of File Showing File Access Permission

Access Permission

The following figure illustrates the access permissions that can be given to a file:

Fig - File Access Permissions

Permission – Access Mode


The following table describes the different access modes for the files and the directories:

Access Mode File Directory

r To display contents of a file To list contents of a dir

w To create or append a file To create files and directories


Linux System and Networking Administration 59

Access Mode File Directory

x To execute a file To execute to a directory

File Permission Modes


The following figure illustrates the two different mechanisms for assigning file permission
modes. The symbolic mode and the absolute mode.

Fig - Symbolic and Absolute File Permission Modes


The following figure illustrates the various combinations of permissions that can be
assigned to a file or a directory and their corresponding absolute mode value, which are
actually the binary representation.

Fig - Symbolic Permission Modes and Their Absolute Mode Value

Default File Permission

When a file created with the help of cat, touch, vi will get the permissions as 644 i.e.
- rw- r-- r-- which means:
 read-write for the owner
 read-only for the owner’s group and
 read-only for the other’s
Actually in the basic UNIX system when a file is created it gets the permission as 666.
But this lapses in security, so when ever a file is created in UNIX system it masks some
bits, with a mask value of 022.
After masking we get the default value of a file as 644. [666 � 022 = 644]
022 is the UMASK value.
60 Linux System and Networking Administration

Viewing Umask Value


To view the Umask value:

[root@comp1 ~]#umask

To view Umask value from file:

[root@comp1 ~]#vi /etc/bashrc

Default Directory Permission

When a directory is created with the help of mkdir will get the permissions as 755, which
is:

d rwx r-x r-x

In the basic UNIX system when a directory is created it gets the permission as 777.
But this lapses in security, so when ever a directory is created in UNIX system it masks
some bits, with a mask value of 022.
After masking we get the default value of a file as 777. [777 � 022 = 755]
022 is as the UMASK value.

The chmod Command

The chmod command is used to change the permissions of a file/directory. It can be used
by the owner of the file or by root. With chmod command we can assign permission’s or
remove permissions as required.
The syntax of the chmod command is:

[root@comp1 ~]#chmod <permissions> <file/direccory>

The following are the permission parameters that can be used with the chmod command:
 Category: u g o
 Operators: + - =
 Permissions: r w x
 Weight: 4 2 1
The following figure illustrates applying permission to Owner (u), Group (g) & Others (o)
for File1:
Linux System and Networking Administration 61

Fig - Example of chmod Command (Absolute Mode)


The following figure shows an example of assigning permission in symbolic mode:

Fig - Example of chmod Command (Symbolic Mode)

Understanding Advanced File Permissions

Using SUID Commands

SUID stands for Set User ID. SUID allows applications to run by normal user with
privileges of root user. That means in case there is an application (eg. ping) whose owner
is 'root' and it has its SUID bit set, then when the application is executed as a normal user,
that application would still run as root.
By default the SUID will be applied on ping so that the normal users can also ping to other
systems.

The following examples illustrate the usage of SUID command:


 To remove SUID

[root@comp1 ~]#chmod 0755 /bin/ping

 To add SUID

[root@comp1 ~]#chmod 4755 /bin/ping


62 Linux System and Networking Administration

Understanding SGID

SGID is used for group inheritance, when SGID is applied to a directory, all sub directories
& files created by any user in that particular directory would be owned by the specified
group, regardless of user’s group.

Understanding Sticky Bit

Sticky bit is used to restrict ‘others’ from removing the files/directories. When applied, only
owner of that particular file/directory can delete them. However, a root / superuser can
also remove them, even if sticky bit is applied.

Working with vi-Editor

What are Editors?

Editors are used for inserting or deleting text. Some of the commonly used editors are:
 Windows : Notepad
 DOS : Edit
 Linux/Unix
o CLI based : ex , ed , vi
o GUI based : Emacs, Gedit, nedit, nano, pico

vi Editor Modes

There are three modes of operations in vi Editor:


 Insert Mode
 Command Mode
 Execute Mode

Getting into Insert Mode


The following key presses will enable you to get into Insert mode:
 i: Inserts the text at current cursor position
 I: Inserts the text at beginning of line
 a: Appends the text after current cursor position
 A: Appends the text at end of line
 o: Inserts a line below current cursor position
 O: Inserts a line above current cursor position
 r: Replaces a single char at current cursor position

Working in Command Mode


The following are the actions that you can perform in command mode:
 dd: Deletes a line
Linux System and Networking Administration 63

 2dd: Deletes 2 lines


 yy: Copies a line
 2yy: Copies 2 lines
 p: After deleting or copying, by pressing ‘p’ the deleted or copied contents will be
pasted below the position of cursor.
 u: Undo (can undo 1000 times)
 Ctrl+r: Redo
 G: Moves cursor to last line of file
 5G: Moves cursor to 5th line of file

Working at Execute Mode


The following are the commands that you can give at execute mode:
 :q: Quit without saving
 :q: Quit forcefully without saving
 :w: Save
 :wq: Save & quit
 :wq!: Save & quit forcefully
 :x: save & Quit
 Shift+ZZ: Save & quit
 :sh: Provides temporary shell
 :set number: Setting line numbers
 :se nu: Setting line numbers
 :set nonumber:- Removing line numbers
 :se nonu: Removing line numbers
 :84: Press enter goes to line 84
64 Linux System and Networking Administration
Linux System and Networking Administration 65

CHAPTER 3: MANAGING SERVICES

Explaining Linux Boot Process

Introduction

An important and powerful aspect of Red Hat Enterprise Linux is the open, user-
configurable method it uses for starting the operating system. Users are free to configure
many aspects of the boot process, including specifying the programs launched at boot-
time. Similarly, system shutdown gracefully terminates processes in an organized and
configurable way, although customization of this process is rarely required.
Understanding how the boot and shutdown processes work not only allows customization,
but also makes it easier to troubleshoot problems related to starting or shutting down the
system.

The Boot Process

Below are the basic stages of the boot process for an x86 system:
1. The system BIOS checks the system and launches the first stage boot loader on
the MBR of the primary hard disk.
2. The first stage boot loader loads itself into memory and launches the second stage
boot loader from the /boot/ partition.
3. The second stage boot loader loads the kernel into memory, which in turn loads
any necessary modules and mounts the root partition read-only.
4. The kernel transfers control of the boot process to the /sbin/init program.
5. The /sbin/init program loads all services and user-space tools, and mounts all
partitions listed in /etc/fstab.
6. The user is presented with a login screen for the freshly booted Linux system.
Next we will discuss in detail how the boot process works and how it can be customized to
suite specific needs.

A Detailed Look at the Boot Process

The beginning of the boot process varies depending on the hardware platform being used.
However, once the kernel is found and loaded by the boot loader, the default boot process
is identical across all architectures. This chapter focuses primarily on the x86 architecture.

The BIOS
When an x86 computer is booted, the processor looks at the end of system memory for
the Basic Input/Output System or BIOS program and runs it. The BIOS controls not only
the first step of the boot process, but also provides the lowest level interface to periphera l
devices. For this reason it is written into read-only, permanent memory and is always
available for use.
66 Linux System and Networking Administration

Other platforms use different programs to perform low-level tasks roughly equivalent to
those of the BIOS on an x86 system. For instance, Itanium-based computers use the
Extensible Firmware Interface (EFI) Shell.
Once loaded, the BIOS tests the system, looks for and checks peripherals, and then
locates a valid device with which to boot the system. Usually, it checks any diskette drives
and CD-ROM drives present for bootable media, then, failing that, looks to the system's
hard drives. In most cases, the order of the drives searched while booting is controlled
with a setting in the BIOS, and it looks on the master IDE device on the primary IDE bus.
The BIOS then loads into memory whatever program is residing in the first sector of this
device, called the Master Boot Record or MBR. The MBR is only 512 bytes in size and
contains machine code instructions for booting the machine, called a boot loader, along
with the partition table. Once the BIOS finds and loads the boot loader program into
memory, it yields control of the boot process to it.

The Boot Loader


This section looks at the default boot loader for the x86 platform, GRUB. Depending on the
system's architecture, the boot process may differ slightly.
A boot loader for the x86 platform is broken into at least two stages. The first stage is a
small machine code binary on the MBR. Its sole job is to locate the second stage boot
loader and load the first part of it into memory.
GRUB has the advantage of being able to read ext2 and ext3 [1] partitions and load its
configuration file — /boot/grub/grub.conf — at boot time.

Tip:
If upgrading the kernel using the Red Hat User Agent, the boot loader configuration file is
updated automatically. More information on Red Hat Network can be found online at the
following URL: https://rhn.redhat.com/.

Once the second stage boot loader is in memory, it presents the user with a graphical
screen showing the different operating systems or kernels it has been configured to boot.
On this screen a user can use the arrow keys to choose which operating system or kernel
they wish to boot and press Enter. If no key is pressed, the boot loader loads the default
selection after a configurable period of time has passed.

Note:
If Symmetric Multi-Processor (SMP) kernel support is installed, more than one option is
presented the first time the system is booted. In this situation GRUB displays Red Hat
Enterprise Linux (<kernel-version>-smp), which is the SMP kernel, and Red Hat Enterprise
Linux (<kernel-version>), which is for single processors.

If any problems occur using the SMP kernel, try selecting the a non-SMP kernel upon
rebooting.
Once the second stage boot loader has determined which kernel to boot, it locates the
corresponding kernel binary in the /boot/ directory. The kernel binary is named using the
following format — /boot/vmlinuz-<kernel-version> file (where <kernel-version>
corresponds to the kernel version specified in the boot loader's settings).
The boot loader then places one or more appropriate initramfs images into memory. Next,
the kernel decompresses these images from memory to /boot/, a RAM-based virtual file
system, via cpio. The initramfs is used by the kernel to load drivers and modules necessary
to boot the system. This is particularly important if SCSI hard drives are present or if the
systems use the ext3 file system.
Once the kernel and the initramfs image(s) are loaded into memory, the boot loader hands
control of the boot process to the kernel.
Linux System and Networking Administration 67

Boot Loaders for Other Architectures


Once the kernel loads and hands off the boot process to the init command, the same
sequence of events occurs on every architecture. So the main difference between each
architecture's boot process is in the application used to find and load the kernel.
For example, the Itanium architecture uses the ELILO boot loader, the IBM eServer pSeries
architecture uses YABOOT, and the IBM eServer zSeries and IBM S/390 systems use the
z/IPL boot loader.
Consult the Installation Guide specific to these platforms for information on configuring
their boot loaders.

The Kernel
When the kernel is loaded, it immediately initializes and configures the computer's
memory and configures the various hardware attached to the system, including all
processors, I/O subsystems, and storage devices. It then looks for the compressed
initramfs image(s) in a predetermined location in memory, decompresses it directly to
/sysroot/, and loads all necessary drivers. Next, it initializes virtual devices related to the
file system, such as LVM or software RAID, before completing the initramfs processes and
freeing up all the memory the disk image once occupied.
The kernel then creates a root device, mounts the root partition read-only, and frees any
unused memory.
At this point, the kernel is loaded into memory and operational. However, since there are
no user applications that allow meaningful input to the system, not much can be done with
the system.
To set up the user environment, the kernel executes the /sbin/init program.

The /sbin/init Program


The /sbin/init program (also called init) coordinates the rest of the boot process and
configures the environment for the user.
When the init command starts, it becomes the parent or grandparent of all of the
processes that start up automatically on the system. First, it runs the /etc/rc.d/rc.sysinit
script, which sets the environment path, starts swap, checks the file systems, and
executes all other steps required for system initialization. For example, most systems use
a clock, so rc.sysinit reads the /etc/sysconfig/clock configuration file to initialize the
hardware clock. Another example is if there are special serial port processes which must be
initialized, rc.sysinit executes the /etc/rc.serial file.
The init command then runs the /etc/inittab script, which describes how the system should
be set up in each SysV init runlevel. Runlevels are a state, or mode, defined by the
services listed in the SysV /etc/rc.d/rc<x>.d/ directory, where <x> is the number of the
runlevel. For more information on SysV init runlevels, refer to Section “SysV Init
Runlevels”.
Next, the init command sets the source function library, /etc/rc.d/init.d/functions, for the
system, which configures how to start, kill, and determine the PID of a program.
The init program starts all of the background processes by looking in the appropriate rc
directory for the runlevel specified as the default in /etc/inittab. The rc directories are
numbered to correspond to the runlevel they represent. For instance, /etc/rc.d/rc5.d/ is
the directory for runlevel 5.
When booting to runlevel 5, the init program looks in the /etc/rc.d/rc5.d/ directory to
determine which processes to start and stop.
Below is an example listing of the /etc/rc.d/rc5.d/ directory:

K05innd -> ../init.d/innd


K05saslauthd -> ../init.d/saslauthd
68 Linux System and Networking Administration

K10dc_server -> ../init.d/dc_server


K10psacct -> ../init.d/psacct
K10radiusd -> ../init.d/radiusd
K12dc_client -> ../init.d/dc_client
K12FreeWnn -> ../init.d/FreeWnn
K12mailman -> ../init.d/mailman
K12mysqld -> ../init.d/mysqld
K15httpd -> ../init.d/httpd
K20netdump-server -> ../init.d/netdump-server
K20rstatd -> ../init.d/rstatd
K20rusersd -> ../init.d/rusersd
K20rwhod -> ../init.d/rwhod
K24irda -> ../init.d/irda
K25squid -> ../init.d/squid
K28amd -> ../init.d/amd
K30spamassassin -> ../init.d/spamassassin
K34dhcrelay -> ../init.d/dhcrelay
K34yppasswdd -> ../init.d/yppasswdd
K35dhcpd -> ../init.d/dhcpd
K35smb -> ../init.d/smb
K35vncserver -> ../init.d/vncserver
K36lisa -> ../init.d/lisa
K45arpwatch -> ../init.d/arpwatch
K45named -> ../init.d/named
K46radvd -> ../init.d/radvd
K50netdump -> ../init.d/netdump
K50snmpd -> ../init.d/snmpd
K50snmptrapd -> ../init.d/snmptrapd
K50tux -> ../init.d/tux
K50vsftpd -> ../init.d/vsftpd
K54dovecot -> ../init.d/dovecot
K61ldap -> ../init.d/ldap
K65kadmin -> ../init.d/kadmin
K65kprop -> ../init.d/kprop
K65krb524 -> ../init.d/krb524
K65krb5kdc -> ../init.d/krb5kdc
K70aep1000 -> ../init.d/aep1000
K70bcm5820 -> ../init.d/bcm5820
K74ypserv -> ../init.d/ypserv
K74ypxfrd -> ../init.d/ypxfrd
Linux System and Networking Administration 69

K85mdmpd -> ../init.d/mdmpd


K89netplugd -> ../init.d/netplugd
K99microcode_ctl -> ../init.d/microcode_ctl
S04readahead_early -> ../init.d/readahead_early
S05kudzu -> ../init.d/kudzu
S06cpuspeed -> ../init.d/cpuspeed
S08ip6tables -> ../init.d/ip6tables
S08iptables -> ../init.d/iptables
S09isdn -> ../init.d/isdn
S10network -> ../init.d/network
S12syslog -> ../init.d/syslog
S13irqbalance -> ../init.d/irqbalance
S13portmap -> ../init.d/portmap
S15mdmonitor -> ../init.d/mdmonitor
S15zebra -> ../init.d/zebra
S16bgpd -> ../init.d/bgpd
S16ospf6d -> ../init.d/ospf6d
S16ospfd -> ../init.d/ospfd
S16ripd -> ../init.d/ripd
S16ripngd -> ../init.d/ripngd
S20random -> ../init.d/random
S24pcmcia -> ../init.d/pcmcia
S25netfs -> ../init.d/netfs
S26apmd -> ../init.d/apmd
S27ypbind -> ../init.d/ypbind
S28autofs -> ../init.d/autofs
S40smartd -> ../init.d/smartd
S44acpid -> ../init.d/acpid
S54hpoj -> ../init.d/hpoj
S55cups -> ../init.d/cups
S55sshd -> ../init.d/sshd
S56rawdevices -> ../init.d/rawdevices
S56xinetd -> ../init.d/xinetd
S58ntpd -> ../init.d/ntpd
S75postgresql -> ../init.d/postgresql
S80sendmail -> ../init.d/sendmail
S85gpm -> ../init.d/gpm
S87iiim -> ../init.d/iiim
S90canna -> ../init.d/canna
S90crond -> ../init.d/crond
70 Linux System and Networking Administration

S90xfs -> ../init.d/xfs


S95atd -> ../init.d/atd
S96readahead -> ../init.d/readahead
S97messagebus -> ../init.d/messagebus
S97rhnsd -> ../init.d/rhnsd
S99local -> ../rc.local

As illustrated in this listing, none of the scripts that actually start and stop the services are
located in the /etc/rc.d/rc5.d/ directory. Rather, all of the files in /etc/rc.d/rc5.d/ are
symbolic links pointing to scripts located in the /etc/rc.d/init.d/ directory. Symbolic links
are used in each of the rc directories so that the runlevels can be reconfigured by creating,
modifying, and deleting the symbolic links without affecting the actual scripts they
reference.
The name of each symbolic link begins with either a K or an S. The K links are processes
that are killed on that runlevel, while those beginning with an S are started.
The init command first stops all of the K symbolic links in the directory by issuing the
/etc/rc.d/init.d/<command> stop command, where <command> is the process to be
killed. It then starts all of the S symbolic links by issuing /etc/rc.d/init.d/<command>
start.
Each of the symbolic links are numbered to dictate start order. The order in which the
services are started or stopped can be altered by changing this number. The lower the
number, the earlier it is started. Symbolic links with the same number are started
alphabetically.

Note:
One of the last things the init program executes is the /etc/rc.d/rc.local file. This file is
useful for system customization.

After the init command has progressed through the ap propriate rc directory for the
runlevel, the /etc/inittab script forks an /sbin/mingetty process for each virtual console
(login prompt) allocated to the runlevel. Runlevels 2 through 5 have all six virtual
consoles, while runlevel 1 (single user mode) has one, and runlevels 0 and 6 have none.
The /sbin/mingetty process opens communication pathways to tty devices, sets their
modes, prints the login prompt, accepts the user's username and password, and initiates
the login process.

In runlevel 5, the /etc/inittab runs a script called /etc/X11/prefdm. The prefdm script
executes the preferred X display manager — gdm, kdm, or xdm, depending on the
contents of the /etc/sysconfig/desktop file.
Once finished, the system operates on runlevel 5 and displays a login screen.

Running Additional Programs at Boot Time

The /etc/rc.d/rc.local script is executed by the init command at boot time or when
changing runlevels. Adding commands to the bottom of this script is an easy way to
perform necessary tasks like starting special services or initialize devices without writing
complex initialization scripts in the /etc/rc.d/init.d/ directory and creating symbolic links.
The /etc/rc.serial script is used if serial ports must be setup at boot time. This script runs
setserial commands to configure the system's serial ports. Refer to the setserial man page
for more information.
Linux System and Networking Administration 71

SysV Init Runlevels

Introduction

The SysV init runlevel system provides a standard process for controlling which programs
init launches or halts when initializing a runlevel. SysV init was chosen because it is easier
to use and more flexible than the traditional BSD-style init process.
The configuration files for SysV init are located in the /etc/rc.d/ directory. Within this
directory, are the rc, rc.local, rc.sysinit, and, optionally, the rc.serial scripts as well as the
following directories:
init.d/
rc0.d/
rc1.d/
rc2.d/
rc3.d/
rc4.d/
rc5.d/
rc6.d/
The init.d/ directory contains the scripts used by the /sbin/init command when controlling
services. Each of the numbered directories represent the six runlevels configured by
default under Red Hat Enterprise Linux.

Different Runlevels

The idea behind SysV init runlevels revolves around the idea that different systems can be
used in different ways. For example, a server runs more efficiently without the drag on
system resources created by the X Window System. Or there may be times when a system
administrator may need to operate the system at a lower runlevel to perform diagnostic
tasks, like fixing disk corruption in runlevel 1.

The characteristics of a given runlevel determine which services are halted and started by
init. For instance, runlevel 1 (single user mode) halts any network services, while runlevel
3 starts these services. By assigning specific services to be halted or started on a given
runlevel, init can quickly change the mode of the machine without the user manually
stopping and starting services.
The following runlevels are defined by default under Red Hat Enterprise Linux:
 0 — Halt
 1 — Single-user text mode
 2 — Not used (user-definable)
 3 — Full multi-user text mode
 4 — Not used (user-definable)
 5 — Full multi-user graphical mode (with an X-based login screen)
 6 — Reboot
In general, users operate Red Hat Enterprise Linux at runlevel 3 or runlevel 5 — both full
multi-user modes. Users sometimes customize runlevels 2 and 4 to meet specific needs,
since they are not used.
72 Linux System and Networking Administration

The default runlevel for the system is listed in /etc/inittab. To find out the default runlevel
for a system, look for the line similar to the following near the top of /etc/inittab:

id:5:initdefault:

The default runlevel listed in this example is five, as the number after the first colon
indicates. To change it, edit /etc/inittab as root.
It is possible to change the default runlevel at boot time by modifying the arguments
passed by the boot loader to the kernel. For information on changing the runlevel at boot
time, refer to Section, “Changing Runlevels at Boot Time”.

Runlevel Utilities

One of the best ways to configure runlevels is to use an initscript utility. These tools are
designed to simplify the task of maintaining files in the SysV init directory hierarchy and
relieves system administrators from having to directly manipulate the numerous symbolic
links in the subdirectories of /etc/rc.d/.
Red Hat Enterprise Linux provides three such utilities:
 /sbin/chkconfig — The /sbin/chkconfig utility is a simple command line tool for
maintaining the /etc/rc.d/init.d/ directory hierarchy.
 /usr/sbin/ntsysv — The ncurses-based /sbin/ntsysv utility provides an interactive
text-based interface, which some find easier to use than chkconfig.
 Services Configuration Tool — The graphical Services Configuration Tool (system-
config-services) program is a flexible utility for configuring runlevels.

Shutting Down

To shut down Red Hat Enterprise Linux, the root user may issue the /sbin/shutdown
command. The shutdown man page has a complete list of options, but the two most
common uses are:

/sbin/shutdown -h now/sbin/shutdown -r now

After shutting everything down, the -h option halts the machine, and the -r option reboots.
If the computer does not power itself down, be careful not to turn off the computer until a
message appears indicating that the system is halted.
Failure to wait for this message can mean that not all the hard drive partitions are
unmounted, which can lead to file system corruption.

Changing Runlevels with init and telinit

The init process is the grandfather of all processes. If used as a command on a running
system, init sends signals to the executing init process, instructing it to change to a
specified runlevel. You must be logged in as the superuser to use the init command.
Syntax
init n

Description
The number of the runlevel, n, can be changed to an integer from 1 through 6.
Linux System and Networking Administration 73

The numeric arguments instruct init to switch to the specified runlevel. init also supports a
few alphabetical options such as S and s, which are equivalent to runlevel 1, and q, which
is used to tell init to reread its configuration file, /etc/inittab.

Examples
Shut down immediately:
# init 0

Reboot immediately:
# init 6

Go to single-user mode immediately:


# init 1

or:
# init s

The telinit command may be used in place of init. telinit is simply a link to init, and the two
may be used interchangeably.
Generally, you will use a runlevel change for the following reasons:
 To shut down the system using runlevel 0.
 To go to single-user mode using runlevel 1.
 To reboot the system using runlevel 6.
 To switch between text-based and X11 GUI login modes, usually runlevels 3 and 5,
respectively.

Managing Services
The following are the usages of various commands used for managing services:
 To display status of all services
[root@comp1 ~]#chkconfig --list
 To display status of particular service
[root@comp1 ~]#chkconfig --list network
 To change services at certain Runlevel
[root@comp1 ~]#chkconfig --level 2345 <service> <on/off>
 To start / stop any service temporarily
[root@comp1 ~]#service <service name> <start/stop/restart>
74 Linux System and Networking Administration
Linux System and Networking Administration 75

CHAPTER 4: X WINDOW SYSTEM

Basic X Concepts

Introduction

While the heart of Red Hat Enterprise Linux is the kernel, for many users, the face of the
operating system is the graphical environment provided by the X Window System, also
called X.
Other windowing environments have existed in the UNIX world, including some that
predate the release of the X Window System in June 1984. Nonetheless, X has been the
default graphical environment for most UNIX-like operating systems, including Red Hat
Enterprise Linux, for many years.
The graphical environment for Red Hat Enterprise Linux is supplied by the X.Org
Foundation, an open source organization created to manage development and strategy for
the X Window System and related technologies. X.Org is a large-scale, rapidly developing
project with hundreds of developers around the world. It features a wide degree of support
for a variety of hardware devices and architectures, and can run on a variety of different
operating systems and platforms. This release for Red Hat Enterprise Linux specifically
includes the X11R7.1 release of the X Window System.
The X Window System uses a client-server architecture. The X server (the Xorg binary)
listens for connections from X client applications via a network or local loopback interface.
The server communicates with the hardware, such as the video card, monitor, keyboard,
and mouse. X client applications exist in the user-space, creating a graphical user interface
(GUI) for the user and passing user requests to the X server.

The X11R7.1 Release

Red Hat Enterprise Linux 5 now uses the X11R7.1 release as the base X Window System,
which includes several video driver, EXA, and platform support enhancements over the
previous release, among others. In addition, this release also includes several automatic
configuration features for the X server.
X11R7.1 is the first release to take specific advantage of the modularization of the X
Window System. This modularization, which splits X into logically distinct modules, makes
it easier for open source developers to contribute code to the system.
Red Hat Enterprise Linux no longer provides the XFree86 server packages. Before
upgrading a system to the latest version of Red Hat Enterprise Linux, be sure that the
system's video card is compatible with the X11R7.1 release by checking the Red Hat
Hardware Compatibility List located online at http://hardware.redhat.com/.
In the X11R7.1 release, all libraries, headers, and binaries now live under /usr/ instead of
/usr/X11R6. The /etc/X11/ directory contains configuration files for X client and server
applications. This includes configuration files for the X server itself, the xfs font server, the
X display managers, and many other base components.
The configuration file for the newer Fontconfig-based font architecture is still
/etc/fonts/fonts.conf. For more on configuring and adding fonts, refer to Section 30.4,
“Fonts”.
76 Linux System and Networking Administration

Because the X server performs advanced tasks on a wide array of hardware, it requires
detailed information about the hardware it works on. The X server automatically detects
some of this information; other details must be configured.
The installation program installs and configures X automatically, unless the X11R7.1
release packages are not selected for installation. However, if there are any changes to the
monitor, video card or other devices managed by the X server, X must be reconfigured.
The best way to do this is to use the X Configuration Tool (system-config-display),
particularly for devices that are not detected manually.
In Red Hat Enterprise Linux's default graphical environment, the X Configuration Tool is
available at System (on the panel) => Administration => Display.
Changes made with the X Configuration Tool take effect after logging out and logging back
in.
In some situations, reconfiguring the X server may require manually editing its
configuration file, /etc/X11/xorg.conf.

Desktop Environments and Window Managers

Introduction

Once an X server is running, X client applications can connect to it and create a GUI for the
user. A range of GUIs are possible with Red Hat Enterprise Linux, from the rudimentary
Tab Window Manager to the highly developed and interactive GNOME desktop environment
that most Red Hat Enterprise Linux users are familiar with.
To create the latter, more comprehensive GUI, two main classes of X client application
must connect to the X server: a desktop environment and a window manager.

Desktop Environments

A desktop environment integrates various X clients to create a common graphical user


environment and development platform.
Desktop environments have advanced features allowing X clients and other running
processes to communicate with one another, while also allowing all applications written to
work in that environment to perform advanced tasks, such as drag and drop operations.
Red Hat Enterprise Linux provides two desktop environments:
 GNOME — The default desktop environment for Red Hat Enterprise Linux based on
the GTK+ 2 graphical toolkit.
 KDE — An alternative desktop environment based on the Qt 3 graphical toolkit.
Both GNOME and KDE have advanced productivity applications, such as word processors,
spreadsheets, and Web browsers; both also provide tools to customize the look and feel of
the GUI. Additionally, if both the GTK+ 2 and the Qt libraries are present, KDE applications
can run in GNOME and vice-versa.

Window Managers

Window managers are X client programs which are either part of a desktop environment
or, in some cases, stand-alone. Their primary purpose is to control the way graphical
windows are positioned, resized, or moved. Window managers also control title bars,
window focus behavior, and user-specified key and mouse button bindings.
Linux System and Networking Administration 77

Four window managers are included with Red Hat Enterprise Linux:
kwin
The KWin window manager is the default window manager for KDE. It is an efficient
window manager which supports custom themes.

metacity
The Metacity window manager is the default window manager for GNOME. It is a simple
and efficient window manager which also supports custom themes. To run this window
manager, you need to install the kdebase package.

mwm
The Motif Window Manager (mwm) is a basic, stand-alone window manager. Since it is
designed to be a stand-alone window manager, it should not be used in conjunction with
GNOME or KDE. To run this window manager, you need to install the openmotif package.

twm
The minimalist Tab Window Manager (twm, which provides the most basic tool set of any
of the window managers, can be used either as a stand-alone or with a desktop
environment. It is installed as part of the X11R7.1 release.
To run any of the aforementioned window managers, you will first need to boot into
Runlevel 3.
Once you are logged in to Runlevel 3, you will be presented with a terminal prompt, not a
graphical environment. To start a window manager, type

xinit -e <path-to-window-manager>

at the prompt.
<path-to-window-manager> is the location of the window manager binary file. The binary
file can be located by typing which window-manager-name, where window-manager-name
is the name of the window manager you want to run.
For example:

user@host# which twm


/usr/bin/twm

user@host# xinit -e /usr/bin/twm

The first command above returns the absolute path to the twm window manager, the
second command starts twm.
To exit a window manager, close the last window or press Ctrl-Alt-Backspace. Once you
have exited the window manager, you can log back into Runlevel 5 by typing startx at the
prompt.

X Server Configuration Files


The X server is a single binary executable (/usr/bin/Xorg). Associated configuration files
are stored in the /etc/X11/ directory (as is a symbolic link — X — which points to
/usr/bin/Xorg). The configuration file for the X server is /etc/X11/xorg.conf.
78 Linux System and Networking Administration

The directory /usr/lib/xorg/modules/ contains X server modules that can be loaded


dynamically at runtime. By default, only some modules in /usr/lib/xorg/modules/ are
automatically loaded by the X server.
To load optional modules, they must be specified in the X server configuration file,
/etc/X11/xorg.conf.
When Red Hat Enterprise Linux 5 is installed, the configuration files for X are created using
information gathered about the system hardware during the installation process.

The GNOME and KDE Desktops

Overview

Two powerful virtual desktop environments that come with RHEL are the GNOME Desktop
Environment and KDE Desktop Environment. The GNOME desktop, shown in the following
figure, is the default desktop for RHEL that you first see after installing the X Window
System.

Fig - GNOME Desktop


The KDE desktop, shown in the following figure, is the main alternate desktop system. KDE
is the default for several other Linux distributions.
Linux System and Networking Administration 79

Fig – KDE Desktop

GNOME Features

The GNOME desktop includes support for the Common Object Request Broker Architecture
(CORBA), which allows GNOME software components written in any language and running
on different systems to work together. In addition, the GNOME developer community is
also working on an architecture similar to Microsoft’s Object Linking and Embedding (OLE)
architecture that will allow one GNOME application to call and control another GNOME
application. One very nice feature of GNOME-compliant applications is that they are
session aware; that is, when you quit an application, the application “remembers” the
location in the document where you were last working and will reposition your cursor to
that point when you restart the application.

Sawfish Window Manager


Even though you may be using GNOME as your desktop environment, you still need the
services of a window manager. The best way to think of the relationship between the
window manager and GNOME is that they work together to control what you see on your
display. The GNOME desktop will work with any window manager, but it works best with a
GNOME-compliant window manager. Under Red Hat Linux, the default GNOME window
manager is the Sawfish. Popular alternative window managers include Enlightenment and
IceWM. You can find more information about GNOME at http://www.gnome.org.

Using GNOME
Many of the features of the GNOME interface will be familiar to you from other desktop
environments. On the left side of the screen are icons representing files and applications
80 Linux System and Networking Administration

that can be opened by double-clicking them with the mouse. The GNOME desktop
environment also provides you with a virtual desktop. Next to the application buttons on
the right side of the panel is a pager you can use to move from one area of the desktop to
another.
One of the key features of GNOME is the panel, which you can see at the bottom of the
screen in the GNOME desktop. The panel is the control center for most of your activities
while you use GNOME. The button at the far left of the panel with the imprint of a red hat
is the Main Menu button. Use your mouse to click this button, and you will see a list of
applications you can run. You can also launch applications from the panel by clicking the
appropriate icon. The default buttons include a Help menu (the lifesaver icon) and the
gnome-terminal terminal emulator.
GNOME includes a number of applications, including graphics tools and an office suite,
GNOME Office. Most Red Hat GUI administrative utilities are written for GNOME,
nevertheless, the RHCE requirements do not specify a preferred desktop; there should be
no problems using KDE or the command line console to do everything that is required for
the task.
As you’ll be configuring GNOME for your users, you may want to configure GNOME in a
special way. Normally, GNOME opens with a number of icons and possibly default
applications such as nautilus. You can add more default applications such as a new
terminal window or the xcalc calculator with the Startup Programs utility, which you can
access via the gnome-session-properties command.

KDE Features

The KDE desktop is built on the Qt C++ cross-platform GUI toolkit. This is another
versatile way to create GUI applications for Linux.
Many of the features of KDE should also be familiar to you from other desktop
environments. In fact, you can configure KDE to a look and feel that is quite similar to
Windows 9x. As shown in the last figure (KDE Desktop), it includes a Main Menu button,
represented by the red hat and folder in the lower-left corner of the desktop. Like GNOME,
it includes pagers and buttons representing the open programs on the desktop.

Default Desktop
Once you’ve configured X Window, it’s easy to start a Linux GUI. Just run the startx
command. This command, in the /usr/X11R6/bin directory, calls up various other
configuration files in your home directory. If the configuration files don’t exist in your
home directory, they are taken from the default directory for GUI configuration, /etc/X11.
To manage the default desktop, use the switchdesk utility. For example, the following
commands set the default desktop to KDE and GNOME, respectively:

# switchdesk KDE

# switchdesk GNOME

The switchdesk program creates two hidden files in your home directory, ~/.Xclients and
~/.Xclients-default, that are used to start your alternate desktop. You don’t need to use
switchdesk; once you have an ~/.Xclients-default file, you can edit it directly.
It is a simple file; if your default desktop is KDE, this file has one line:

exec startkde

If your default desktop is GNOME, this file has a different line:

exec gnome-session
Linux System and Networking Administration 81

Alternatively, you can use switchdesk to set up twm, known as Tom’s Window Manager.
The version of twm in the latest version of Red Hat Linux includes just the same textured
gray screen that you get with the X command. The ~/.Xclients-default file would include
the following line:

exec /usr/X11R6/bin/twm

If you have other desktops or window managers installed, you can use those instead.
When run at the command line, the switchdesk command can also let you set FVWM,
Enlightenment, or WindowMaker as the default window manager. You’ll see the new
default the next time you run the startx command from a console command line interface.

X Window System Configuration

Introduction

During installation, the system's monitor, video card, and display settings are configured.
To change any of these settings after installation, use the X Configuration Tool.
To start the X Configuration Tool, go to System (on the panel) > Administration > Display,
or type the command system-config-display at a shell prompt (for example, in an XTerm
or GNOME terminal). If the X Window System is not running, a small version of X is started
to run the program.
After changing any of the settings, log out of the graphical desktop and log back in to
enable the changes.

Display Settings

The Settings tab allows users to change the resolution and color depth. The display of a
monitor consists of tiny dots called pixels. The number of pixels displayed at one time is
called the resolution. For example, the resolution 1024x768 means that 1024 horizontal
pixels and 768 vertical pixels are used. The higher the resolution values, the more images
the monitor can display at one time.
The color depth of the display determines how many possible colors are displayed. A
higher color depth means more contrast between colors.
82 Linux System and Networking Administration

Fig – Display Settings

Display Hardware Settings

When the X Configuration Tool is started, it probes the monitor and video card. If the
hardware is probed properly, the information for it is shown on the Hardware tab as shown
in following figure:

Fig - Display Hardware Settings


To change the monitor type or any of its settings, click the corresponding Configure
button. To change the video card type or any of its settings, click the Configure button
beside its settings.
Linux System and Networking Administration 83

Dual Head Display Settings

If multiple video cards are installed on the system, dual head monitor support is available
and is configured via the Dual head tab, as shown in the figure below.

Fig - Dual Head Display Settings


To enable use of Dual head, check the Use dual head checkbox.
To configure the second monitor type, click the corresponding Configure button. You can
also configure the other Dual head settings by using the corresponding drop-down list.
For the Desktop layout option, selecting Spanning Desktops allows both monitors to use an
enlarged usable workspace. Selecting Individual Desktops shares the mouse and keyboard
among the displays, but restricts windows to a single display.
84 Linux System and Networking Administration
Linux System and Networking Administration 85

CHAPTER 5: PERFORMING ADMINISTRATIVE


TASKS

Working with Links

Introducing Links

A link is a mechanism of matching two or more file names to the same set of file data.
There are two ways to achieve this, hard link and soft link. The following figure illustrates
the difference between hard link and soft link.

Fig – Hard Link vs Soft Link

Using Links Commands

The following illustrates various examples of using links:


 To configure hardlink

[root@comp1 ~]#ln <source file> <destination file>

 To configure softlink

[root@comp1 ~]#ln -s <source file> <destination file>

Changing Owner / Group

The following illustrates how to change owner or group for file/directory:


 To change owner/group of the file/directory
86 Linux System and Networking Administration

[root@comp1 ~]#chown <username:groupname> <file/directory>

 To change group of the file/directory

[root@comp1 ~]#chgrp <groupname> <file/directory>

Access Control List

Introducing Access Control List

To configure different set of file permissions for different users on a single resource
(file/folder), ACL’s are implemented. ACL’s can be implemented only on ‘ACL enabled
partitions’. ACL’s can be applied on Users and Groups.
The following figure illustrates example of an ACL:

Fig – Illustrating ACL

Steps for Implementing ACL

The following are the steps for implementing ACL:


1. Create a new partition

[root@comp1 ~]#fdisk /dev/hda

2. Format the partition

[root@comp1 ~]#mkfs.ext3 /dev/hda9

3. Create a new mount point

[root@comp1 ~]#mkdir /aclmount

4. Mount new partition with ACL ‘option’

[root@comp1 ~]#mount -o acl /dev/hda9 /aclmount

5. Create Users
Linux System and Networking Administration 87

[root@comp1 ~]#useradd usr1


[root@comp1 ~]#useradd usr2
[root@comp1 ~]#useradd usr3

6. Create groups

[root@comp1 ~]#groupadd sales

7. Add some users to group

[root@comp1 ~]#gpasswd -M usr1, usr2 sales

8. Create files into the ACL enabled partition

[root@comp1 ~]#vi /aclmount/quotation

The default permissions for the directory / file will be “rw_r__r__”


9. Set ACL permissions using one of the following approach:
o ACL permissions to the directory for the user:

[root@comp1 ~]#setfacl -m u:usr1:- /aclmount/quotation

o ACL permissions to the directory for the group:

[root@comp1 ~]#setfacl -m g:sales:rw /aclmount/quotation

Managing ACL Lists

You use the following commands for viewing or removing ACLs.


To list applied ACL applied on a File

[root@comp1 ~]#getfacl /aclmount/quotation

To remove ACL from a file

[root@comp1 ~]#setfacl �x u:usr1 /aclmount/quotation

Performing Backup

What is Backup?

Backup is the mechanism to copy data to alternate media. It is generally used to prevent
data loss. Only Administrators can backup the data.
The following figure illustrates backing up and restoring data:

Fig – Backup and Restore Data


88 Linux System and Networking Administration

Types of Data

The following are the data that you should take a backup of:
 System Generated Data
 User Generated Data

Types of Backup

The different types of backups are:


 Full backup: It refers to taking a complete backup of entire system.
 Incremental backup: It includes all files that were changed since the last backup. It
always smaller than differential backup.
 Differential backup: It includes all the files that were changed since the last full
backup. As time increases since the last full-backup the size of differential backup
increases.

Commands for Backup

The following are the commands used for taking backups of data:
 tar (tape archive)
 cpio (copy input/output)
 dump

tar command
The general syntax of the tar command is:

[root@comp1 ~]#tar <options> <destination> <source>

The various options are:


 -c: Create
 -v: Verbose
 -f: File
 -t: Table of content
 -x: Extract to
 -w: Interactive
 -z: Zip
The following illustrates some of the usage of the tar command:
 To take the backup

[root@comp1 ~]#tar -cvf <path><file name> <source>

 To list the content of tar file

[root@comp1 ~]#tar -tvf <path><file name>

 To extract the content of tar file

[root@comp1 ~]#tar -xvf <path><file name>

 To backup along with zip


Linux System and Networking Administration 89

[root@comp1 ~]#tar -cvzf <path><file name> <source>

 To uncompress the content of tar.gz file

[root@comp1 ~]#tar -xvzf <path><file name>

cpio - copy input output Command


The following illustrates various usages of the cpio command:
 To backup

[root@comp1 ~]#ls <options> | cpio -ov > <file name>

 To extract

[root@comp1 ~]#cpio -iv < <file name>

dump and restore Command


The following illustrates various usages of the dump and restore command:
 To backup

[root@comp1 ~]#dump -0uf <device> <file name>

 To extract

[root@comp1 ~]#restore -f <path>

Taking Remote Backup

To store the data at another location is called as remote backup.


To backup:

[root@comp1 ~]#rsync -avz <source> -e ssh <destination ip>:<directory>

or

[root@comp1 ~]#scp -r <source> <destination ip>:<directory>

Automation Jobs

As a system administrator some task are repetitive like backup, monitoring log files, etc.
To automate them, you can use the following utilities:
 at
 batch
 cron

Working with Partitions

What is Partitioning?

Partitioning is the method of splitting a disk up into several smaller sections, or partitions.
Each partition is treated as an independent file system.
90 Linux System and Networking Administration

Identifying Partitioning Tools

The partitioning tools can be classified as pre-installation tool and post-installation tool.
The pre-installation tool is the Disk Druid.
The post-installation tools include:
 Fdisk
 Parted
 Cfdisk
 sfdisk

Naming Conventions

The following figure illustrates the naming convention used for naming a partition in Linux
and Solaris:

Fig – Naming Convention for Partitions

Commands for Partitioning

The fdisk command is used to create disk partitions. The following illustrates various
usages of the fdisk command:
To view list of partitions:

[root@comp1 ~]#fdisk -l <device name>

To create a new partition:

[root@comp1 ~]#fdisk <device name>

The following is an example of creating a disk partition:

[root@comp1 ~]# fdisk /dev/hda

The number of cylinders for this disk is set to 4865.


There is nothing wrong with that, but this is larger than 1024, and could in certain setups
cause problems with:
 Software that runs at boot time (e.g., old versions of LILO)
 Booting and partitioning software from other OSs (e.g., DOS FDISK, OS/2 FDISK)
Linux System and Networking Administration 91

Options with fdisk Command


You can use various options with fdisk command. These are listed in the following table:

Option Description

a toggle a bootable flag

b edit bsd disklabel

c toggle the dos compatibility flag

d delete a partition

l list known partition types

m print this menu

n add a new partition

o create a new empty DOS partition table

p print the partition table

q quit without saving changes

s create a new empty Sun disklabel

t change a partition's system id

u change display/entry units

v verify the partition table

w write table to disk and exit

x extra functionality (experts only)

Updating Partition Table


The following command updates the partition table to kernel without restarting:

[root@comp1 ~]#partprobe

Formatting of Partition

The two most common file system supported by Linux are ext2 and ext3. The following
figure illustrates the differences between ext2 and ext3 file systems:
92 Linux System and Networking Administration

Fig – Difference Between ext2 and ext3 File System

To format partition using ext3 file system

[root@comp1 ~]#mkfs.ext3 <partition>

To format partition using ext2 file system

[root@comp1 ~]#mkfs.ext2 <partition>

To format partition using vfat filesystem

[root@comp1 ~]#mkfs.vfat <partition>

Mounting File System

You use the mount command for mounting a file system. The steps for mounting a file
system are:
1. Create a directory for mounting the partition

[root@comp1 ~]#mkdir <directory name>

2. Mount the file system on the created directory

[root@comp1 ~]#mount <partition> <directory name>

To unmount the file system:

[root@comp1 ~]#umount <directory name>

The mount command reads the fstab file to determine which options should be used when
mounting the specified device. You can view the content of fstab file using:

[root@comp1 ~]#vi /etc/fstab

The following figure shows a sample content of /etc/fstab file:


Linux System and Networking Administration 93

Fig – Content of /etc/fstab File

Converting from Ext2 to Ext3

The following are the steps for converting from ext2 to ext3 file system:
1. Unmount the partition

[root@comp1 ~]#umount <partition>

2. Converting from Ext2 to Ext3 filesystem

[root@comp1 ~]#tune2fs -j <partition>

3. Mount the partition to use it

[root@comp1 ~]#mount <partition> <directory name>


[root@comp1 ~]#mount

Converting from Ext3 to Ext2

The following are the steps for converting from ext2 to ext3 file system:
1. Unmount the partition

[root@comp1 ~]#umount <partition>

2. Converting from Ext3 to Ext2 filesystem

[root@comp1 ~]#tune2fs -O ^has_ journal <partition>

3. Mount the partition to use it

[root@comp1 ~]#mount <partition> <directory name>


[root@comp1 ~]#mount

Using Labels

The following illustrates usage of commands for managing labels:


 To assign label

[root@comp1 ~]#e2label <partition> <label_name>


94 Linux System and Networking Administration

 To view existing label

[root@comp1 ~]#e2label <partition>

 To see mounted partition with Label

[root@comp1 ~]#mount –l

Working with Swap Partition

A swap partition is a partition that is used as a swap space by Linux. This is where unused
items taking up memory are placed until they are required again so that the memory they
are using can be freed for something else.
The following figure illustrates how a swap works:

Fig – Working of Swap Partition


Following are the steps to create a swap partition:
1. Creating a new partition

[root@comp1 ~]#fdisk <options> <partition>

2. Make a partition swap partition

[root@comp1 ~]#mkswap <partition>

To enable swap on the swap partition:

[root@comp1 ~]#swapon <partition>

To check the status of swap used:

[root@comp1 ~]#swapon -s <partition>

To disable the swap partition

[root@comp1 ~]#swapoff <partition>


Linux System and Networking Administration 95

Using Quotas

Introducing Quotas

Quotas are a limit set by a system administrator that restricts certain aspects of file
system usage. Quota allows administrator to specify restriction in two ways:
 Restricting a user or a group by creating files in a specific location.
 Restricting a user or a group by the disk space in a specific location.

Advantages of Quotas

The idea behind quotas is that users are forced to stay under their disk consumption limit
or with number of files in a particular location.
Quota is handled on a per user, per file system basis.

Types of Quotas

Quotas are of two types:


 User level quotas - usrquota
 Group level quotas – grpquota

Applying Quota

Steps for applying Quota on new partition are:


1. Initially create a new partition.
2. Create a new mount point.
3. Format the new partition with ext2 or ext3.

Quotas Creation

To enable the new partition with usrquota and grpquota:

[root@comp1 ~]#mount -o usrquota, grpquota <part_name> <mnt_pt>

To generate the database files inside the quota partition:

[root@comp1 ~]#quotacheck -cugv <quota_mnt_pt>

To turn on the quota:

[root@comp1 ~]#quotaon <quota_mnt_pt>

To apply the quotas for the users on quota enabled partition:

[root@comp1 ~]#edquota -u <user name>

To apply the quotas for a group on quota enabled partition:

[root@comp1 ~]#edquota -g <group name>


96 Linux System and Networking Administration

Understanding RAID

Introducing RAID in Linux

RAID’s available in Linux are:


 RAID 0 (striping without parity)
 RAID 1 (disk mirroring)
 RAID 4 (parity)
 RAID 5 (disk striping with parity)

RAID 0

The main features of RAID 0 are listed below:


 Minimum: 2 Hard Disks
 Maximum: 32 Hard Disks
 Data is written alternately and evenly to two or more disks
 Read & Write Speed is Fast
 Fault Tolerance is not available
The following figure illustrates how RAID 0 works:

Fig – RAID 0

RAID 1

The main features of RAID 1 are listed below:


 Minimum: 2 Hard Disks
 Maximum: 2 Hard Disks
 Simultaneously data will be written to two volumes on two different disks
 Read Speed is Fast & Write Speed is Slow
 Fault Tolerance is available
 50% overhead
Linux System and Networking Administration 97

The following figure illustrates how RAID 1 works:

Fig – RAID 1

RAID 4

The main features of RAID 4 are listed below:


 Minimum: 3 Hard Disks
 Maximum: 32 Hard Disks
 Data is written alternately and evenly to two or more disks and a parity is only
written on one disk
 Read & Write Speed is Fast
 Fault Tolerance is available
The following figure illustrates how RAID 4 works:

Fig – RAID 4

RAID 5

The main features of RAID 5 are listed below:


 Minimum: 3 Hard Disks
 Maximum: 32 Hard Disks
 Data is written alternately and evenly to two disks and a parity is written on all
disk
 Read & Write Speed is Fast
 Fault Tolerance is available
98 Linux System and Networking Administration

 Also Known as Striped with parity


The following figure illustrates how RAID 5 works:

Fig – RAID 5

Data Recovery Using RAID

The following fi8gure illustrates how data can be recovered using RAID:

Fig – Data Recovery in RAID

RAID Commands

The following are the examples of various RAID commands that you can use in Linux:
 To club all the RAID partitions in to a single array:

[root@comp1 ~]#mdadm -C /dev/md0 -n3 /dev/hda8 /dev/hda9 /dev/hda10 -l5

 To display RAID device:

[root@comp1 ~]#mdadm -D /dev/md0

 To format RAID device:

[root@comp1 ~]#mkfs.ext3 /dev/md0


Linux System and Networking Administration 99

 To create mount point of RAID device:

[root@comp1 ~]#mkdir /raid

 To mount the RAID device:

[root@comp1 ~]#mount /dev/md0 /raid


[root@comp1 ~]#cd /raid

 To make a partition faulty:

[root@comp1 ~]#mdadm -f /dev/md0 /dev/hda10

 To remove partition from RAID array:

[root@comp1 ~]#mdadm -r /dev/md0 /dev/hda10

 To add a new device into the RAID array:

[root@comp1 ~]#mdadm -a /dev/md0 /dev/hda11

 To stop the RAID:

[root@comp1 ~]#mdadm -S /dev/md0

 To activate RAID:

[root@comp1 ~]#mdadm -A /dev/md0 /dev/hda8 /dev/hda9 /dev/hda10

Working with RPM

What is RPM?

RPM is the acronym for RedHat Package Manager. By using RPM utility the user can install
the new packages, can upgrade and can also remove existing packages.

RPM Pattern

The following figure illustrates the various parts of an rpm filename:

Fig – RPM Filename Components


100 Linux System and Networking Administration

RPM – Install

To install the RPM package

[root@comp1 ~]#rpm <options> <package name-version> --force –aid

The options that you can use with rpm command are:
 -i: To install the package
 -v: To print debugging information
 -h: To display the progress in hashes
 --force: To install package forcefully
 --aid - To install package along with dependencies

How to Install Source RPMs


Sometimes the packages you want to install need to be compiled in order to match your
kernel version. This requires you to use source RPM files:
 Download the source RPMs or locate them on your CD collection. They usually have
a file extension ending with (.src.rpm)
 Run the following commands as root: rpmbuild --rebuild filename.src.rpm

RPM – Upgrade

To upgrade the existing RPM package:

[root@comp1 ~]#rpm <options> <package name.version>

The various options to use with upgrading of RPM package are:


 -U: To Upgrade the existing package
 -v: To print debugging information
 -h: To display the progress in hashes

RPM – Remove

To remove the existing RPM package:

[root@comp1 ~]#rpm <options> <package name> --nodeps

The various options are:


 -e: To uninstall the package from the system
 --nodeps: To uninstall package even if dependencies are there.

RPM – Query

To query the RPM Package

[root@comp1 ~]#rpm <options> <package name>

The various options that you can use with querying the RPM are:
 -q: Queries the availability of installed package.
 -qa: Queries all installed RPM’s in OS. Does not require any package specification.
 -qc: Lists only the configuration files stored in the queried RPM.
Linux System and Networking Administration 101

 -qd: Lists only the documentation files stored in the queried RPM.
 -qi: Displays complete information about the queried RPM.
 -qs: Displays the states of files in the queried RPM.
 -ql: Displays all the files related to the queried RPM.

Automatic Updates with yum

Introducing yum

The yum automatic RPM update program comes as a standard feature of RHEL-5. It has a
number of valuable features:
 Yum is acronym for Yellow Dog Update Manager
 You can configure the URLs of download sites containing the RPM repositories you
need. This provides the added advantage of you choosing the most reliable sites in
your part of the globe.
 yum makes multiple attempts to download RPMs before failing.
 It automatically resolve dependencies
 More advanced than rpm command
 yum automatically figures out not only the RPMs packages that need updating, but
also all the supporting RPMs. It then installs them all.
 You can deploy rpm packages to other client machines also.

Configuring yum

The configuration parameters that affect all packages and all yum server URLs are stored
in the [main] section of the /etc/yum.conf file. You generally don't need to edit this file,
but it can be useful in listing packages that you don't want yum to update. In this example
the kernel and perl packages are excluded.

#
# File: /etc/yum.conf
#

[main]
exclude=kernel perl

The configurations for each RPM repository are stored in the /etc/yum.repos.d directory in
individual configuration files with the .repo file extension. This directory will be populated
with files for your Linux distribution's most important repositories. You can also add your
own custom files for repositories containing non-standard RPM packages. These files will
have the following format:

[repositoryid]
name= Yum repository
baseurl=ftp://server1.hcl.com/pub/repository/

You can also place all your [repositoryid] sections in the yum.conf file. This was the
methodology used in some older versions of yum.
102 Linux System and Networking Administration

Note:
The yum utility can be configured to match the downloaded RPMs against checksum files to
help protect against file corruption and malicious forgeries. This is set using the gpgcheck
variable in the .repo files. Checks are done when the value is set to 1, when set to 0, they
are disabled. Here is an example:

#
# File: example.repo
#
gpgcheck=1

Automating yum

The /etc/yum/yum-updatesd.conf configuration file which governs update frequency, the


types of files to be downloaded and whether they should be automatically installed using
the yum command.
1. Use the chkconfig command to get yum configured to start at boot:

chkconfig yum-updatesd on
chkconfig yum on

2. Use the service command to instruct the /etc/init.d yum script to start/stop yum
after booting

service yum-updatesd start


service yum-updatesd stop
service yum start
service yum stop

Yum Commands

The following is the list of various yum command usage:


 yum install packagename
 yum listall
 yum remove packagename
 yum update

Configuring Yum server with FTP

The steps for configuring yum with ftp are listed below:
1. Configure FTP server on one machine
2. Enable anonymous access
3. Copy RPMs packages into /var/ftp/pub
4. Create a file with .repo extension in /etc/yum.repos.d/
5. Edit .repo file
6. Copy this file to /var/ftp/pub/
7. Run command createrepo –v /var/ftp/pub/package directory
Linux System and Networking Administration 103

8. Go to client and connect to FTP server


9. Download the file with .repo extension
10. Copy this file in client’s /etc/yum.repos.d/
11. Install any package on client machine

Troubleshooting

Recovering Root Password

Root Password can be recovered in a specialized troubleshooting mode (i.e. init 1). The init
1 level provides a shell (i.e. sh) without logging in.
For recovering root password, perform the following steps:
1. Restart the system
2. In the splash screen Select “RedHat Enterprise Linux”
3. Press ‘e’
4. Select Kernel /vmlinuz-2.6.9-5.EL ro root=LABEL=/rhgb quiet
5. Press ‘e’ to edit
6. Edit Kernel /vmlinuz-2.6.9-5.EL ro root=LABEL=/rhgb quiet 1
7. Press ‘Enter’
8. Press ‘b’ to boot with the selected run level
9. directly you will get shell prompt to assign the root password
10. sh-3.00#passwd root

Assigning Grub Password

For assigning Grub password, perform the following steps:


1. Encrypts the password in MD5 format:

[root@comp1~]# grub-md5-crypt >> /boot/grub/grub.conf

2. Open the grub.cong file:

[root@comp1~]# vi /boot/grub/grub.conf

3. Add line in /boot/grub/grub.conf

hidden menu
password --md5 <password>
title Red Hat ------

Recovering Grub Password

For recovering Grub password, perform the following steps:


1. Boot the System in Rescue Mode

# chroot /mnt/sysimage

2. Open the grub.cong file:


104 Linux System and Networking Administration

# vi /boot/grub/grub.conf

3. Remove line from /boot/grub/grub.conf

hidden menu
password -- md5 <password>
title Red Hat ------

Other Troubleshooting Techniques

Sometimes by reconfiguring the problematic device solves the problem. Another commonly
used troubleshooting technique is to monitor various processes and then terminating the
process that appears to be suspicious. Here we will discuss the commands used for
configuring devices like printer and modem and commands used for monitoring and killing
processes.
To configure printer:

[root@comp1~]# system-config-printer

To configure modem:

[root@comp1~]# system-config-network-druid

To view the process:

[root@comp1~]# ps –aux

To kill a specific process:

[root@comp1~]# kill -9 <process id>

To view CPU usage by all process:

[root@comp1~]# top

User and Group Administration

Introduction to User and Groups in Linux

Unix/Linux is multi user and multi tasking OS. Redhat Linux uses User Private Group (UPG)
Scheme where user always get created with primary group. There is only one Primary
Group per User.
When a user is created in Linux, the following are created :--
 home directory (/home/username)
 mail account (/var/spool/mail/username)
 unique UID & GID
Linux System and Networking Administration 105

Types of Users

The following figure illustrates types of users in Linux:

Fig – Linux Users

User and Group Administration Database Files

The following are the various files where user and group information are stored:
 /etc/passwd
 /etc/shadow
 /etc/group

/etc/passwd - Database file of Users


The following figure illustrates a typical entry in a /etc/passwd file:

Fig – A Sample Entry in /etc/passwd File

/etc/shadow
The /etc/shadow file contains the encrypted user passwords assigned by the password
binary file. Password’s are encrypted through DES (Data Encryption Standard ) or MD5
(Message Digest Ver. 5) Algorithm.
The following figure illustrates a typical entry in a /etc/shadow file:
106 Linux System and Networking Administration

Fig – A Sample Entry in /etc/shadow File

/etc/group
The /etc/group file contains Group Name and GID of the groups. The following figure
illustrates a typical entry in a /etc/group file:

Fig – A Sample Entry in /etc/group File

Managing Users

A system administrator can manage a user’s account. The various tasks that a system
administrator can perform include adding, modifying and deleting user account.

User Creation
To create a user, use the useradd command. The syntax is:

[root@comp1 ~]#useradd <options> <username>

The options to useradd command are:


 -u: UID
 -g: Primary group name/ GID
 -o: Override
 -G: Secondary group
 -c: Comment
Linux System and Networking Administration 107

 -d: Home directory


 -s: Shell

User Modification
To modify a user, use the usermod command. The syntax is:

[root@comp1 ~]#usermod <options> <username>

The options to usermod command are:


 -l: Change login name
 -L: Lock the account
 -U: Unlock the account

User Deletion
To delete a user, use the userdel command. The syntax is:

[root@comp1 ~]#userdel <options> <username>

The option to userdel command is:


 -r: Recursively delete

Managing Groups

A system administrator can manage a group’s account. The various tasks that a system
administrator can perform include adding, modifying and deleting group account.

Group Creation
To create a group, use the groupadd command. The syntax is:

[root@comp1 ~]#groupadd <options> <groupname>

The options to groupadd command are:


 -g: GID
 -o: override

Group Modification
To modify a group, use the groupmod command. The syntax is:

[root@comp1 ~]#groupmod <options> <groupname>

The options to groupmod command are:


 -g: GID
 -o: Override
 -n: To change the group name

Group Deletion
To delete a group, use the groupdel command. The syntax is:

[root@comp1 ~]#groupdel <groupname>


108 Linux System and Networking Administration

Changing User Setting


To change a user setting in a group, use the chage command. The syntax is:

[root@comp1 ~]#chage <username>

Changing Group Setting


To change the group setting, use the gpasswd command. The syntax is:
[root@comp1 ~]#gpasswd <options> <groupname>
The options to gpasswd command are:
 -a : Add a user
 -d : Delete a user from group
 -M : Create multiple members

Working with Logical Volume Manager (LVM)

Steps for Configuring LVM

The steps for configuring LVM are described here.

A. Creating Physical Volume


The required steps are listed below:
1. Create two new partitions of size 100 MB each( any size may be taken)

#fdisk /dev/sda
:p: partition table
:n: create new partition (say 10)
:l: see the code for particular system ID
:t: change system ID for sda10(presently it is 83 for Linux, use 8e for Linux LVM)
:w

2. Repeat Step 1 for another partition say sda11.


3. Inform Kernel about this change, without rebooting the system.

#partprobe

4. Create physical volume which will be used for Logical Volume. This will inform the
kernel about the partition which will be used for Logical Volume. It means it attach
a flag on these partition.

#pvcreate /dev/sda10 /dev/sda11

5. Now display the information about physical volume.

#pvdisplay

B. Creating Logical Volume Group


Linux System and Networking Administration 109

The steps are:


6. Create Logical Volume Group

#vgcreate <volume group name> <partition name>


#vgcreate vg00 /dev/sda10

7. Now display the information again. This will display the following information:
o pe size(Physical element size)
o format : lvm1 or lvm2

#pvdisplay

8. Display the information about the Logical Volume.

#vgdisplay

C. Creating a New Volume in a Volume Group


The steps are:
9. Now create a new volume in the existing volume group to implement LVM.

#lvcreate -L +80M -n lv00 vg00

The options are:


o -L: to add size in MB
o -l: to add size in pe
o -n: to give new name
o vg00: new name, any name may be given.
10. Now display the information of Logical Volume.

#lvdisplay

D. Formatting and Mounting The Logical Volume


The steps are:
11. Now format the logical volume lv00, use –j is for journaling.

#mke2fs –j /dev/vg00/lv00

12. Create a new Directory to mount the newly formatted volume.

#mkdir /lvm
#mount /dev/vg00/lv00 /lvm

13. Now to do permanent mounting, make entry in the /etc/fstab. This file is read at
the time of booting.

#vi /etc/fstab
/dev/vg00/lv00 /lvm /ext3 1 2
:wq

14. One of the greatest advantages of LVM is that you can resize the volume, without
rebooting the system. This feature is very useful for servers.
15. Now let’s resize the volume lv00 from 80MB -> 280MB.

E. Increasing the Volume Size


110 Linux System and Networking Administration

The steps are:


16. Now we need to extend the size of volume group to resize logical volume to size
280MB.

#vgextend vg00 /dev/sda11

17. Display information and check the free space.

#vgdisplay
# df –h /lvm

18. Above command will not show the newly added space in vg00. Now we have to
format the added volume without disturbing the pervious data.

#ext2online /dev/vg00/lv00

Note: ext2online will always work on the mounted volume formatted with
ext3.

# df -h

F. Decreasing the Volume Size


The required step is:
19. To decrease the volume size, use lvreduce command.

#lvreduce -L-80M /dev/vg00/lv00

G. Removing Logical Volume


The required steps are:
20. First remove the entry from /etc/fstab.

#vi /etc/fstab

21. Unmount the file system.

#umount /lvm

22. Remove the LVM.

#lvremove /dev/vg00/lv00

23. Remove the physical volume.

#pvremove /dev/sda10 /dev/sda11

24. Remove the partitions.

#fdisk /dev/sda10
#fdisk /dev/sda11

Note:
Linux System and Networking Administration 111

no of LVM = sequence no – metadata area


Concept of metadata area is useful when multiple groups is implemented
LE –> logical element
Overhead depends upon the PE size.

LVM Snapshot

Logical Volume Manager (LVM) provides the ability to take a snapshot of any logical
volume for the purpose of obtaining a backup of a partition in a consistent state. As
applications may access files or databases on a partition during a backup some files may
be backed up in one state, while later files are backed up after an update has been made,
leading to an inconsistent backup.
Traditionally the solution has been to mount the partition read-only, apply table-level write
locks to databases or shut down the database engine etc.; all measures which adversely
impact availability (but not as much as data loss without a backup will). With LVM
snapshots it is possible to obtain a consistent backup without compromising availability.
Please note that this information is only valid for partitions that have been created using
LVM. LVM snapshots cannot be used with non-LVM file systems.
The LVM snapshot works by logging the changes to the file system to the snapshot
partition, rather than mirroring the partition. Thus when you create a snapshot partition
you do not need to use space equal to the size of the partition that you are taking a
snapshot of, but rather the amount of changes that it will undergo during the lifetime of
the snapshot. This is a function of both how much data is being written to the partition and
also how long you intend keeping the LVM snapshot. The longer you leave it, the more
changes there are likely to be on the file system and the more the snapshot partition will
fill up with change information. The higher the rate of change on the partition the shorter
the lifespan of the snapshot. If the amount of changes on the LVM partition exceed the size
of the snapshot then the snapshot is released.
Now we will show an example of how to make an LVM snapshot. Here we create a logical
volume of 500MB to use to take a snapshot. This will allow 500MB of changes on the
volume we are taking a snapshot of during the lifetime of the snapshot.
The following command will create /dev/ops/dbbackup as a snapshot of
/dev/ops/databases.

# lvcreate -L500M -s -n dbbackup /dev/ops/databases


lvcreate -- WARNING: the snapshot must be disabled if it gets full
lvcreate -- INFO: using default snapshot chunk size of 64 KB for "/dev/ops/dbbackup"
lvcreate -- doing automatic backup of "ops"
lvcreate -- logical volume "/dev/ops/dbbackup" successfully created

Now we create the mount point and mount the snapshot.

# mkdir /mnt/ops/dbbackup
# mount /dev/ops/dbbackup /mnt/ops/dbbackup
mount: block device /dev/ops/dbbackup is write-protected, mounting read-only
112 Linux System and Networking Administration
Linux System and Networking Administration 113

CHAPTER 6: CONFIGURING NETWORKS

Setting Up a Domain Name System Server

Introduction

The Domain Name System (DNS) is essentially a distributed database that translates host
names into IP addresses (and IP addresses back to host names). That database also
contains information related to each domain, such as how the domain is organized into
zones, where to route mail for that domain, and who to contact with questions associated
with the domain.
By setting up a DNS server, you become part of a hierarchy of DNS servers that make up
the Internet. At the top of this hierarchy is the root server, represented by a dot (".").
Below the root server are the Top Level Domains, or TLDs (such as .com, .org, and so on).
Domains that individual organizations own and maintain lie below the TLDs. That's where
you come in.
As someone who's setting up a DNS server, you're responsible for managing the host
names and IP addresses for the computers in the domain (or domains) for which you're
responsible. Keeping your DNS information correct means that people can access the
services that you want to share, and the Internet as a whole works that much better as a
result.
Besides using your DNS server to help people from the Internet find the public servers in
your domain, you can also use DNS to provide name and IP address mapping for
computers on your private network. The example in the "DNS name server example"
section later in this chapter describes how to configure both private and public name and
IP address records for a domain.

Understanding DNS

The basic function of a name server is to answer queries by providing the information that
those queries request. A DNS name server primarily translates domain and host names
into IP addresses. Each domain is typically represented by at least two DNS servers.
 Primary (master) name server: This name server contains authoritative
information about the domains that it serves. In response to queries for
information about its domains, this server provides that information marked as
being authoritative. The primary is the ultimate source for data about the domain.
The secondary name server only carries the same authority in that it has received
and loaded a complete set of domain information from the primary.
 Secondary (slave) name server: This name server gets all information for the
domain from the primary. As is the case for the primary, DNS considers the
secondary's information about the domain that it serves authoritative. (You set
secondary servers in the NS RR records for the zone in the named.conf file on the
primary.)
NS records in the parent zone for a domain list the primary and one or more secondary
name servers. This delegation of servers defines the servers that have authority for the
zone.
Because zone records change as you add, remove, or reconfigure the computers in the
zone, you assign expiration times for information about your zone. You set the expiration
time in the time to live (TTL) field, in the named.conf file (which I describe later).
114 Linux System and Networking Administration

Other specialized types of DNS servers are possible as well. Although these types of
servers don't have authority for any zones, they can prove useful for special purposes:
 Caching name server ( This type of server simply caches the information it
receives about the locations of hosts and domains. It holds information that it
obtains from other authoritative servers and reuses that information until the
information expires (as set by the TTL fields).
 Forwarding name server ( Creating a server that's not authoritative for a zone
but that can forward name server requests to other name servers may prove
efficient. This server is essentially a caching name server, but is useful in cases
where computers lie behind a firewall and in which only one computer can make
DNS queries outside that firewall on behalf of all the internal computers.

Understanding Authoritative Zones

As an administrator of a DNS server, you need to configure several zones. Each zone
represents part of the DNS namespace as you view it from your DNS server. Besides the
one or more zones representing your domain, you have a zone that identifies your local
host and possibly your local, private LAN.
If you configure a server as authoritative for a zone, that server has the last word on
resolving addresses for that zone. Your master name server is authoritative for the domain
you configure in the "DNS name server example" section but not for domains outs ide your
domain.
Remember that the DNS server that you configure is the ultimate authority for your zone.
Other zones don't know how you configure your host names and IP addresses unless you
properly set up your DNS server to distribute that information across the Internet.
The definitive data that you set up for your domain exists in the form of resource records.
Resource records consist of the data associated with all names below the authoritative
point in the tree structure. When the DNS server uses the se records to reply to queries, it
sets the authoritative answer (AA) bit in the packet that includes the reply. The AA bit
indicates that your name server has the best and most current information available about
your domain.

Understanding BIND

In Red Hat Linux (and most other Linux and UNIX systems), you implement DNS services
by using the Berkeley Internet Name Domain (BIND) software. The Internet Software
Consortium maintains BIND (at www.isc.org/products/BIND). The basic components of
BIND include the following:
 DNS server daemon (/usr/sbin/named): The named daemon listens on a port
(port number 53 by default) for DNS service requests and then fulfills those
requests based on information in the configuration files that you create. Mostly,
named receives requests to resolve the host names in your domain to IP
addresses.
 DNS configuration files (named.conf and /var/named/*): The /etc/named.conf
file is where you add most of the general configuration information that you need
to define the DNS services for your domain. Separate files in the /var/named
directory contain specific zone information.
 DNS lookup tools: You can use several tools to check that your DNS server is
resolving host names properly. These include commands such as host, dig, and
nslookup (which are part of the bind-utils software package).
To maintain your DNS server correctly, you can also perform the following configuration
tasks with your DNS server:
 Logging ( You can indicate what you want to log and where log files reside.
Linux System and Networking Administration 115

 Remote server options ( You can set options for specific DNS servers to perform
such tasks as blocking information from a bad server, setting encryption keys to
use with a server, or defining transfer methods.
You don't need to give out DNS information to everyone who requests it. You can restrict
access to those who request it based on the following:
 Access control list ( This list can contain those hosts, domains, or IP addresses
that you want to group together and apply the same level of access to your DNS
server. You create acl records to group those addresses, then indicate what
domain information the locations in that acl can or can't access.
 Listen-on ports ( By default, your name server accepts only name server
requests that come to port 53 on your name server. You can add more port
numbers if you want your name server to accept name service queries on different
ports.
 Authentication ( To verify the identities of hosts that are requesting services
from your DNS server, you can use keys for authentication and authorization. (The
key and trusted-keys statements are used for authentication.)

DNS Name Server Example

To get an idea of what you need to set up your DNS server, the following sections step you
through an example of a DNS server for a domain called yourdomain.com. In the example,
you're creating a DNS server for a small office network that includes the following:
 A private, local network that resides behind a firewall.
 A server providing DNS service and acting as a firewall between the LAN and the
Internet.
In this office, other computers on the LAN are using the same Internet connection for
outgoing communications. So the firewall on the server does network address translation
(NAT) to enable the client computers to use the firewall as a router to the Internet. The
figure below shows the configuration of the example yourdomain.com domain.

Fig - The sample yourdomain.com DNS server has a combination of public servers and
private client computers.
116 Linux System and Networking Administration

The preceding figure illustrates a small office network that's sharing a single Internet
connection. The DNS, Web, mail, and FTP servers all have public IP addresses. (These
addresses are fictitious, so please don't try to use them.) Behind the DNS server (which is
also operating as a firewall) are four client computers that have private IP addresses.
The job of the DNS server, in this configuration, is to map the names of the public servers
(www.yourdomain.com, mail.yourdomain.com, ftp.yourdomain.com, and
ns1.yourdomain.com) into the static IP addresses that the ISP assigns (123.45.67.1
through 123.45.67.4). The DNS server also provides DNS service from the private
addresses on the LAN, so each computer can reach the others on the LAN without needing
to store all computer names in their own /etc/hosts file.
A key feature to this example is that it divides the view of this domain between what the
outside world can see and what the computers on the private network can see. Using the
view feature of BIND, I create an outside view that lets queries from the Internet find only
public servers (Web, Mail, and FTP) in the domain. Then I create an inside view that lets
queries from the local LAN find both the public servers and private computers (red, blue,
green and yellow) in the domain.
The sections that follow describe how to set up a DNS server for the example in the last
figure.

Quick-Starting A DNS Server

The DNS server software that comes with the current Red Hat Linux is Berkeley Internet
Name Daemon (BIND) version 9. To configure BIND 9, you work with the following
components:
 Configuration file (/etc/named.conf) ( The main DNS server configuration file.
 Zone directory (/var/named) ( The directory containing files that keep
information about Internet root DNS servers (named.ca file) and information about
the zones that you create for your DNS server.
 Daemon process (/usr/sbin/named) ( The daemon process that listens for DNS
requests and responds with information that the named.conf file presents.
 Debugging tools (named-checkconf, and named-checkzone) ( What you use to
determine whether you created your DNS configuration correctly.
BIND 9 also includes tools for creating DNSSEC secured zones. By using these tools, you
can create and generate keys to provide authentication and secure address resolution. The
example illustrated in these sections doesn't include DNSSEC configuration.
The basic steps in creating a DNS server for your example are as follows:
1. Identifying your DNS servers
2. Creating DNS Configuration files (named.conf and /var/names/*)
3. Starting the named daemon
4. Monitoring named activities
In the example configuration, you set up a primary master DNS server and a slave DNS
server. The primary holds the authoritative records for the domain. The secondary is there
to share requests for information about the domain, particularly in case the primary goes
down.

Identifying Your DNS Servers


If you didn't have your DNS servers set up at the time that you purchased your domain
name with a registration authority, you might have just "parked" the domain name there
until you configured your DNS servers. Whenever you're ready to set up your DNS servers,
return to that registration authority and provide the following information about your DNS
servers:
Linux System and Networking Administration 117

DNS server IP addresses (the static IP addresses of your DNS servers, probably primary
and slave)
DNS server host names (often ns1.yourdomain.com, where you replace yourdomain.com
with your domain name for the primary; the slave host name is ns2.yourdomain.com)
You should register both the primary and slave DNS servers. After you update this record,
that information typically takes a day or two to propagate throughout the Internet. Once
your DNS servers are registered, you also need to tell the registration authority to use
those DNS servers as the authority for addresses in your domain. The registration
authority probably offers an online form you can fill out to identify your DNS servers.

Creating DNS Configuration Files (named.conf and /var/names/*)


In configuring a DNS server, you're actually creating definitions that apply to a particular
zone in the public DNS tree, as well as several local zones that apply to your computer and
local network. To create a useful DNS server for your example small-office environment,
you have the following zones:
 Public DNS server zone ( The DNS server is authoritative for the domain that
you're serving. This zone serves the names and IP addresses for your public
servers. In the example named.conf file shown in the next section, you need to
replace the name yourdomain.com with the domain that you're creating. These
records become accessible to everyone on the Internet.
 Private DNS server zone ( So each computer on the private network doesn't
need to know the IP addresses for other computers on your private network, a
zone is added in the example named.conf file to let the DNS server resolve these
addresses. The names and IP addresses (which are private) are available only to
computers on your LAN.
Note that by creating different views of these zones, different information will be returned
to queries, depending on where the queries come from. For example, when someone from
the Internet requests the address of the DNS server (ns1.yourdomain.com), they will get
the address 123.45.67.89. However, when a query for ns1.yourdomain.com comes from
inside the LAN, the address 10.0.0.1 is returned. Also, any queries from the Internet for
addresses of private computers (red.yourdomain.com, blue.yourdomain.com, and so on)
are rejected.

Editing /etc/named.conf

To begin, you configure the /etc/named.conf file on the primary master DNS server
representing your example yourdomain.com domain. This example starts from the
/etc/named.conf file that comes with the caching-nameserver package in Red Hat Linux.
(Make sure that you install the caching-nameserver and bind packages before you
continue.) Following are a few tips relating to editing the named.conf file:
 If a statement contains substatements, make sure that you end the last
substatement with a semicolon.
 Comments can appear in the same formats that popular programming languages
use. These languages include C (begin with /* and end with */), C++ (begin with
// and go to the end of the physical line), and shell or Perl styles (begin from a #
and go to the end of the physical line).
 A leading exclamation mark (!) negates an element. Putting !123.45.67.89 in a
statement causes the IP address 123.45.67.89 not to match the element. (Just
make sure that the negation occurs before a positive match or the positive match
takes precedence.)
The edited version of the /etc/named.conf file is as follows:

options {
directory "/var/named";
118 Linux System and Networking Administration

};

acl "mylan" {
127/8; 10.0.0.0/24;
};

view "inside" {
match-clients { "mylan"; };
recursion yes;

zone "." IN {
type hint;
file "named.ca";
};

zone "0.0.10.in-addr.arpa" IN {
type master;
file "yourlan.db";
};

zone "yourdomain.com" {
type master;
file "db.yourdomain.com.inside";
allow-transfer { 10.0.0.2; };
};
};

view "outside" {
match-clients { any; };
recursion no;

zone "." IN {
type hint;
file "named.ca";
};

zone "yourdomain.com" {
type master;
file "db.yourdomain.com.outside";
allow-transfer { 123.45.67.2; };
Linux System and Networking Administration 119

};
};

include "/etc/rndc.key";

The options definition lies at the beginning of the /etc/named.conf file and identifies the
/var/named directory as the location where the zone files reside. The acl lines define the
mylan access-control list, which consists of host computers on the 10.0.0.0 local private
network and the localhost (127/8). (You use this definition in the 0.0.10.in-addr.arpa zone
to enable only users on the LAN to perform reverse lookups of names of computers on the
LAN.)
The DNS server is broken up into two views: inside and outside. The inside view defines
how IP addresses are resolved for requests that come from the private LAN and localhost
(as defined in mylan). By having recursion on (recursion yes), the named daemon will
allow name server queries from any computer on the LAN. The outside view defines how
queries coming from all other places (presumably, the Internet) are handled. With
recursion off (recursion no), only queries from other name servers are honored. (Turning
recursion off can help eliminate a common attack, where a cracker causes your server to
seek information from a DNS server controlled by the cracker.)
Each zone entry in the /etc/named.conf file describes the type of server this computer is
for the zone (master in all cases here, except the root zone), the database file (in
/var/named) that contains records for the zone, and other options relating to the zone
records. The named.ca file is set up for you by default. It identifies the locations of the
Internet root servers.
I made the other zones (yourlan.db, db.yourdomain.com.inside,
db.yourdomain.com.outside and 0.0.10.in-addr.arpa) for this example. For the "inside"
view, the yourlan.db file lets the computers on your LAN do reverse address lookups
(getting the names for IP address queries). The db.yourdomain.com.inside file contains
names and addresses for all computers in your domain (including those on the local LAN).
The DNS slave server for the inside view of this domain is at 10.0.0.2. (Clients in your LAN
would use 10.0.0.1 and 10.0.0.2 as DNS servers in /etc/resolv.conf.)
For the "outside" view, the db.yourdomain.com.outside file contains names and IP
addresses for any computers in your domain you want to make public (computers on your
private LAN are excluded). The DNS slave server for the outside view of this domain is
123.45.67.2.
Notice that each zone points to a zone file in the /var/named directory. The following table
shows which file in the /var/named directory each zone points to.

Zone Zone File ( in /var/named


directory)

. (a single dot representing Internet root servers) named.ca

0.0.10.in-addr.arpa yourlan.db

yourdomain.com (inside view) db.yourdomain.com.inside

yourdomain.com (outside view) db.yourdomain.com.outside

Be very careful editing the /etc/named.conf file. Forgetting a semicolon is all too easy,
resulting in the entire file not loading. To ensure that the /etc/named.conf file doesn't
contain any syntax errors, you can run the following command (as root user):

# named-checkconf
120 Linux System and Networking Administration

If a syntax error is present, a message identifies the problematic line and tells what seems
to be wrong with it. If the syntax is correct, continue on to create the zone files in the
/var/named directory.

Setting up the zone files

The /var/named directory contains the zone files that the /etc/named.conf file names. For
the example, you need to create only three zone files from scratch. You can (and should)
leave the named.ca file alone.
The zone files are where most of the real work of the domain name server occurs. In the
example, the db.yourdomain.com.inside file contains the basic records for the
yourdomain.com domain, including all private names and addresses. The following is an
example of that file:

$TTL 86400
@ IN SOA yourdomain.com. hostmaster.yourdomain.com. (
2003040701 ; Serial
28800 ; Refresh
14400 ; Retry
3600000 ; Expire
86400 ) ; Minimum
; Name servers
IN NS ns1.yourdomain.com.
IN NS ns2.yourdomain.com.

; Mail server for domain


IN MX 10 mail.yourdomain.com.

; Public servers
ns1 IN A 10.0.0.1
ns2 IN A 10.0.0.2
mail IN A 123.45.67.2
www IN A 123.45.67.3
ftp IN A 123.45.67.4

; Private clients on the LAN


red IN A 10.0.0.2
blue IN A 10.0.0.3
green IN A 10.0.0.4
yellow IN A 10.0.0.5

; EOF

The zone file for your "inside" yourdomain.com contains resource records that include
information about the zone. Your DNS server uses the TTL (time-to-live) record to tell
name servers that store the information that you provide for this domain how long they
can keep the information before they need to throw it out and get fresh information. The
Linux System and Networking Administration 121

first value is the default for the entire zone, and the time is in seconds. So a value of
86,400 seconds indicates that a client that is using the information should obtain fresh
records about this domain every 24 hours.
The SOA line identifies the start of authority for the domain. The at sign (@) represents
the yourdomain.com. name. The dot (.) must appear at the end of the domain name. The
dot represents the root server of the Internet. If you leave the dot off, your DNS server
appends the domain name, so the DNS server will use the name
yourdomain.com.yourdomain.com. The hostmaster.yourdomain.com string indicates the e-
mail address of the person who is to receive e-mail regarding the domain. (The first dot
changes to an @ sign, resulting in hostmaster@yourdomain.com). Other information
regarding the SOA record is as follows:
 Serial: Start with any number here. If the zone records change, increase the
serial number to alert other servers that they need to get fresh data about your
domain.
 Refresh: Defines how often the slave DNS server for the zone checks for
changes. (Here, 28,800 seconds represents 8 hours.)
 Retry: If the slave can't reach the master, it tries again after this retry interval.
(Here, 14,400 seconds represents 4 hours.)
 Expire: If the slave can't contact the master within the expire time (3,600,000
seconds, or 1,000 hours, here), the slave discards the data.
 Minimum: Defines the cache time to live for negative answers. ( Here, it's 86,400
seconds, or 24 hours.)
The name server (NS) records define the name servers that represent this zone. In this
case, NS records define hosts with the names ns1 and ns2 in yourdomain.com. The MX
record indicates the location of the mail server for the domain, so that the DNS server can
direct e-mail to users in yourdomain.com. The rest of the file defines IP addresses for the
private clients and public servers that are associated with the domain. Notice that the
server at address 10.0.0.2 serves as a client on the LAN and a slave DNS server.
For the "outside" yourdomain.com zone we made a db.yourdomain.com.outside file using
the same information from the "inside" file, with the following exceptions:
 Removed all references to private clients on the LAN. That way, someone poking
around from the Internet can't get information about your private computers.
 Changed the addresses of the primary and slave DNS servers (ns1 and ns2) to
123.45.67.1 and 123.45.67.2, respectively. In that way, only public addresses for
name servers are seen by the public.
The other new file in the example is the yourlan.db file, which contains the information
necessary to perform reverse IP lookups for the computers on your LAN. Here's an
example:

$TTL 86400
@ IN SOA 0.0.0.10.in-addr.arpa. hostmaster.yourdomain.com. (
2002052701 ; Serial
28800 ; Refresh
14400 ; Retry
3600000 ; Expire
86400 ) ; Minimum
IN NS 0.0.0.10.in-addr.arpa.
1 IN PTR yourdomain.com.
2 IN PTR red.yourdomain.com.
3 IN PTR blue.yourdomain.com.
122 Linux System and Networking Administration

4 IN PTR green.yourdomain.com.
5 IN PTR yellow.yourdomain.com.

; EOF

The SOA record identifies 0.0.0.10.in-addr.arpa. as the start of authority for the zone. The
NS line defines 0.0.0.10.in-addr.arpa. as the name server for the zone. Other records are
pointers to host names that reverse-map on the 10.0.0. network. The records represent
the address for the DNS server (yourdomain.com) and each of the clients on the LAN (red,
blue, green, and yellow).
After you finish creating your own zone files, you can use the named-checkzone command
to make sure that each zone file is correctly formed. Here is how you'd run the named-
checkzone command (as root user) to check the two yourdomain.com zone files:

# named-checkzone yourdomain.com /var/named/db.yourdomain.com.inside


zone yourdomain.com/IN: loaded serial 2003082701
OK

# named-checkzone yourdomain.com /var/named/db.yourdomain.com.outside


zone yourdomain.com/IN: loaded serial 2003082701
OK

The output indicates that both files are okay and that named-checkzone command is able
to load the new serial numbers. In this case, the serial number represents the first serial
number (01) on August 27, 2003 (2003082701).

Starting The Named (DNS) Daemon


To start the named daemon and see whether it's working, type the following (as root
user):

# /etc/init.d/named start

If the named daemon starts successfully, clients of your DNS server should start getting
information about your domain. To set the named daemon to start each time that the
system boots up, type the following:

# chkconfig named on

Remember that, whenever you make changes to the named.conf or any of the zone files,
you must increase the serial number for anyone checking your domain records to pick up
those changes. After that, you should restart the named service too (as root user) as
follows:

# /etc/init.d/named restart

If you see the Starting named message, your DNS server is probably up and running. If
you want to make sure that your server is correctly resolving addresses, the following
section describes some tools that you can use to check your DNS name server.

Checking That DNS Is Working


The best way to see if your DNS server is working correctly is to watch it in action. Here
are a few commands you can use to check out your DNS server. The first example uses
the host command to get the IP address for the host computer named blue in the local
domain:

# host blue
Linux System and Networking Administration 123

blue.yourdomain.com has address 10.0.0.3

Instead of using the simple host name to get the computer's IP address, you can enter an
IP address (instead of the name) or a fully qualified host name. In the following example,
the dig command is used with a domain name to get information about the addresses for a
domain:

# dig yourdomain.com
; <<>> DiG 9.2.1 <<>> yourdomain.com
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43728
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 0

;; QUESTION SECTION:
;yourdomain.com. IN A

;; AUTHORITY SECTION:
yourdomain.com. 604800 IN NS ns1.yourdomain.com.
yourdomain.com. 604800 IN NS ns2.yourdomain.com.

;; Query time: 24 msec


;; SERVER: 10.0.0.1#53(10.0.0.1)
;; WHEN: Mon Apr 6 02:12:32 2003
;; MSG SIZE rcvd: 129

Sections in the output from dig include a question section and an authority section. The
results show name server assignments and addresses associated with the domain you're
querying about. The nslookup command is another tool you can use to look up domain
information. In the following example, nslookup looks up the server that is resolving
ftp.yourdomain.com:

# nslookup -sil ftp.yourdomain.com

Server: 123.45.67.1
Address: 123.45.67.1#53

Name: ftp.yourdomain.com
Address: 123.45.67.3

The output from the nslookup command includes the name of the computer fulfilling the
request and its IP address, along with the name and address of the computer you're
asking for. (The -sil prevents a message that nslookup might soon be removed from Red
Hat Linux.) Try nslookup with an IP address (such as 10.0.0.1) to make sure reverse
lookup works.
To check the status of the named server that is running on your local system, use the
same script that starts named. Type the following to check the status of your DNS server
daemon:

# /etc/init.d/named status
124 Linux System and Networking Administration

number of zones: 5
debug level: 0
xfers running: 0
xfers deferred: 0
soa queries in progress: 0
query logging is OFF
server is up and running

If you can't reach the computers that your DNS server is serving by name or IP address,
you should make sure that each client's address records are correct. You can also try to
ping each client and server computer using the full host name or IP address.

Configuring Samba

What is Samba?

Samba is a software package that comes with Red Hat Linux that lets you share file
systems and printers on a network with computers that use the Session Message Block
(SMB) protocol. SMB is the protocol that is delivered with Windows operating systems for
sharing files and printers. Although you can't always count on NFS being installed on
Windows clients (unless you install it yourself), SMB is always available (with a bit of
setup).
On Red Hat Linux, the Samba software package contains a variety of daemon processes,
administrative tools, user tools, and configuration files. To do basic Samba configuration,
you can start with the Samba Server Configuration window. This window provides a
graphical interface for configuring the server and setting directories to share.
Most of the Samba configuration you do ends up in the /etc/samba/smb.conf file. If you
need to access features that are not available through the Samba Server Configuration
window, you can edit /etc/samba/smb.conf by hand or use SWAT, a Web-based interface
to configure Samba.
Daemon processes consist of smbd (the SMB daemon) and nmbd (the NetBIOS name
server). smbd is what makes the file sharing and printing services you add to your Red Hat
Linux computer available to Windows client computers. The client computers this package
supports include:
 Windows 9x
 Windows 2000
 Windows NT
 Windows ME
 Windows XP
 Windows for Workgroups
 MS Client 3.0 for DOS
 OS/2
 Dave for Macintosh Computers
 Samba for Linux
As for administrative tools for Samba, you have several shell commands at your disposal.
You can check your configuration file using the testparm and testprns commands. The
smbstatus command tells you which computers are currently connected to your shared
Linux System and Networking Administration 125

resources. Using the nmblookup command, you can query for NetBIOS names (the names
used to identify host computers in Samba).

Although Samba uses the NetBIOS service to share resources with SMB clients, the
underlying network must be configured for TCP/IP. Although other SMB hosts can use
TCP/IP, NetBEUI, and IPX/SPX to transport data, Samba for Linux supports only TCP/IP.
Messages are carried between host computers with TCP/IP and are then handled by
NetBIOS.

Getting And Installing Samba

To see if Samba is installed on your Red Hat Linux system, type the following:

# rpm -qa | grep samba


samba-*
redhat-config-samba
samba-swat-*
samba-common-*
samba-client-*

You should see the name of each of the five packages above, followed by the version
number (I represented version numbers with an asterisk). Although not installed with all
installation groups in Red Hat Linux, the packages that make up Samba are spread across
Red Hat Linux CD #1 and CD #3. To install Samba, mount the first CD and run the
following:

# mount /mnt/cdrom
# cd /mnt/cdrom/RedHat/RPMS
# rpm -Uhv samba*
# cd ; umount /mnt/cdrom

Repeat the above procedure for the other CD. Before you start trying to configure Samba,
read the README file (probably located in /usr/share/doc/samba*). It provides a good
overview of the SMB protocol and Samba.

Configuring A Simple Samba Server

The Samba Server Configuration window lets you do some basic Samba configuration and
then identify which directories you want to share. To make this procedure useful, I'm
setting up a particular type of shared environment (which you can modify later if you
prefer). Here are the characteristics:
 A single local area network: Contains multiple Windows and Linux machines.
 User level security: Any user who wants to get to the shared Samba files must
have a valid login and password on the Red Hat Linux Samba server.
 Encrypted passwords: Many clients use encrypted passwords with Samba (SMB)
by default. I'll describe how to turn on encrypted passwords for clients that don't.
 A guest user account: The guest user account will be useful later, so you can set
up Samba to let users without special accounts use the server's printers via
Samba.
The following procedure describes how to configure Samba and create a shared directory
in Samba:
126 Linux System and Networking Administration

1. To open the Samba Server Configuration window, click System Settings ® Server
Settings ® Samba Server. The Samba Server Configuration window opens.

2. Click Preferences ® Server Settings. The Server Settings window appears, as


shown in the figure below.

Fig - Define the workgroup and description for your Samba server.

3. Type the workgroup name (to match that of other computers with which you want
to share files) and a short description.
4. Click the Security tab. A window appears like the one shown in the following figure.

Fig - Fill in Basic and Security information for your Samba server.

5. Provide the following information for the fields on the Security tab and click OK:
o Authentication Mode — Select User, Share, Server, or Domain. For this
example, I selected User. (See the "Security options" section later in this
chapter for details on each of the authentication modes.)
Linux System and Networking Administration 127

o Authentication Server — This field is only valid if you are doing Server or
Domain security. It identifies the server (NetBios name) that will be used
to authenticate the user name and password the Samba client enters to
gain access to this Samba server. With user authentication, passwords are
checked on the Samba server (in this example, therefore, this field is
blank.)
o Encrypt Passwords — Select Yes (to expect clients to send encrypted
passwords) or No (to expect clear-text password). See the section on
Samba clients later in this chapter to determine how to configure clients to
use encrypted passwords.
o Guest Account — Set this field to a user name that you want assigned to
requests from anonymous users. Even with User mode security set
globally, you can assign guest access to particular Samba shares (such as
printers).
With User mode security (which is being used in this example), any user that
wants to access a Samba share must have a regular user account on the Linux
system.
6. To add a user as a Samba user (that is, one who can access your Samba server),
click Preferences ® Samba Users. The Samba Users window appears.
7. Click Add User. The Create New Samba User window appears.
8. Provide information for the following fields in the Create New Samba User window
and click OK:

o Unix Username — Click this box, then select the Linux user name to which
you want to give access to the Samba server.
o Windows Username — This is the user name provided by the user when he
or she requests the shared directory. (Often, it is the same as the Unix
username.)
o Samba Password — Type the Samba password, then retype it into the
Confirm Samba Password field.
9. Repeat the previous step for each user you want to access the Samba shared
directory.
10. Now that you have configured the default values for your Samba server, add a
directory to share by clicking File ® Add Share. The Create Samba Share window
appears.
11. Fill in the following fields shown in the Create Samba Share window:
o Directory — Type the name of the directory you want to share. For
example, you might want to share a user's home directory, such as
/home/chris.
o Description — Type any description you like of the Shared directory.
o Basic Permissions — Select either Read-only or Read/Write. For Read-only,
files can be viewed, but not changed, on the shared directory. For
Read/Write, the user is free to add, change, or delete files, provided he or
she has Linux file access to the particular file.
12. Click the Access tab, select one of the following choices for access to the share,
and then click OK:
o Only allow access to specific users — Click here, then choose which users
will be allowed to access the shared directory. For example, if you are
sharing a user's directory (such as /home/chris), you probably want to
restrict access to that directory to the directory's owner (for example,
chris). Read and write access to particular files and directories are
determined by the Linux ownership and group assigned to them.
128 Linux System and Networking Administration

o Allow access to everyone — Choose this option if you want to allow anyone
to access this directory. (All users will have privileges assigned to the
guest user when accessing the directory.)
After you click OK, Samba is started and the new directory is immediately
available. You can close the Samba Server Configuration window.
13. Although Samba should be running at this point, you probably need to set Samba
to start automatically every time you reboot Linux. To do that, type the following
as root user in a Terminal window:

# chkconfig smb on

You can repeat the steps for adding a Samba shared directory for every directory you want
to make available on your network. At this point, you can either:
 Go through your Samba server settings in more detail (as described in
"Configuring Samba with SWAT") to understand how you might want to further
tune your Samba server.
 Try accessing the shared directories you just created from a client computer on
your network.
If you cannot open the shared directory you just configured from a Windows computer or
other Linux computer on your LAN, you are probably experiencing one of the following
problems:
 The client isn't supplying a valid user name and password.
 The client isn't supplying an encrypted password.
The quick way around these problems is to use only share-level security (which, of course,
throws your security right out the window). The other solution is to get passwords up -to-
date and make sure that clients are using encrypted passwords (as described in the
"Setting up Samba clients" section later in this chapter).

Configuring Samba with SWAT

The Samba Web Administration Tool (SWAT) is a Web-based interface for configuring
Samba. While it's not quite as easy to use as the Samba Server Configuration window, it
does offer more options for tuning Samba and Help descriptions for each option.

Caution:
Both SWAT and the Samba Server Configuration window configure Samba by modifying
the /etc/samba/smb.conf file. Different GUI tools can overwrite each other's settings,
sometimes in a way that causes the other tool not to work.

In general, it's best to make a backup copy of your files before switching GUI tools.
Eventually, you should choose one tool and stick with it.

Turning On The SWAT Service


Before you can use SWAT, you must do some configuration. To set up SWAT to run from
your browser, follow these steps:
1. To turn on the swat service, type the following, as root user, from a Terminal
window:

# chkconfig swat on

2. To pick up the change to the swat service, restart the xinetd start-up script as
follows:

# service xinetd restart


Linux System and Networking Administration 129

When you have finished this procedure, use the SWAT program, described in the next
section, to configure Samba.

Starting With SWAT


You can run the SWAT program by typing the following URL from your local browser:

http://localhost:901/

At this point, the browser will prompt you for a user name and password. Enter the root
user name and password. The SWAT window should appear, as shown in the figure below.

Fig - Use SWAT from your browser to manage your Samba configuration.

Tip:
Instead of running SWAT from your local browser, you can run it from another computer
on the network by substituting the server computer's name for localhost. (To allow
computers besides localhost to access the swat service, you must change or remove the
only_from = 127.0.0.1 line from the /etc/xinetd.d/swat file and restart the xinetd service.)

The rest of this section describes how to use SWAT to create your configuration entries (in
/etc/samba/smb.conf) and to work with that configuration.

Caution:
Any time you use a GUI to change a plain-text configuration file (as you do with SWAT),
you may lose some of the information that you put in by hand. In this case, SWAT deletes
comment lines and rearranges other entries. To protect changes you have made manually,
make a backup copy of your /etc/samba/smb.conf file before you edit it with SWAT.

Creating Global Samba Settings In SWAT


A group of global settings affects how file and print sharing are generally accomplished on
a Samba server. They appear under the [global] heading in the /etc/samba/smb.conf file.
To edit global variables, click the GLOBALS button on the SWAT window.
130 Linux System and Networking Administration

Seven option types are available: Base options, security options, logging options, tuning,
printing options, browse options, and WINs options. To view and modify your global
Samba server settings, click the GLOBALS button. Then add the following options.

Base Options

The following options relate to basic information associated with your Samba server:
 workgroup — The name of the workgroup associated with the group of SMB hosts.
By default, the value for this field is WORKGROUP.
 netbios name — The name assigned to this Samba server. You can use the same
name as your DNS host name or leave it blank, in which case the DNS host name
is used automatically.
 server string — A string of text identifying the server. This name appears in places
such as the printer comment box. By default, it says Samba and the version
number.
 interfaces — Lets you set up more than one network interface. This enables Samba
to browse several different subnetworks. The form of this field can be IP
Address/Subnetwork Mask. Or, you could identify a network interface (such as
eth0 for the first Ethernet card on your computer). For example, a Class C network
address may appear as:

192.168.24.11/255.255.255.0

Security Options

Of the security options settings, the first option (security) is the most important one to get
right. It defines the type of security used to give access to the shared file systems and
printers to the client computers.
 security — Sets how password and user information is transferred to the Samba
server from the client computer. As noted earlier, it's important to get this value
right. The default value for security (security=user) is different than the default
value for security (security=share) in pre-2.0 versions of Samba. If you are
coming from an earlier version of Samba and clients are failing to access your
server, this setting is a good place to start. Here are your options:
o user — The most common type of security used to share files and printers
to Windows 95/98/2000 and Windows NT clients. It is the default set with
Samba in the current release. This setting is appropriate if users are doing
a lot of file sharing (as opposed to a Samba server used mostly as a print
server). It requires that a user provide a user name/password before using
the server.
The easiest way to get this method working is to give a Red Hat Linux user
account to every client user who will use the Red Hat Linux Samba server.
This provides basically the same file permissions to a user account through
Samba as the same user would get if he or she were logged in directly to
Red Hat Linux.
o share — The share value for security works best for just print sharing or
for providing file access that is more public (guest sharing). A client
doesn't need to provide a valid user name and password to access the
server. However, the user will typically have a "guest" level of permission
to access and change files. See the sidebar describing guest accounts for
further information.
o server — The security option that, from the client's point of view, is the
same as user security, in that the client still has to provide a valid user
name/password combination to use the Samba server at all. The difference
is on the server side. With server security, the user name/password is sent
Linux System and Networking Administration 131

to another SMB server for validation. If this fails, Samba will try to validate
the client using user security.
o domain — This security option also, from the client's point of view, looks
the same as user security. This setting is used only if the Samba server
has been added to a Windows NT domain (using the smbpasswd
command). When a client tries to connect to the Samba server in this
mode, its user name and password are sent to a Windows NT Primary or
Backup Domain controller. This is accomplished the same way that a
Windows NT server would perform validation. Valid Red Hat Linux user
accounts must still be set up.
 encrypt passwords — Controls whether encrypted passwords can be negotiated
with the client. This is on (Yes) by default. For domain security, this value must be
Yes. Later versions of Windows NT (4.0 SP3 or later) and Windows 98 and
Windows 2000 expect encrypted passwords to be on. (See the "Setting up Samba
clients" section for information on getting clients to use encrypted passwords.)
 update encrypted — Allows users who log in with a plain-text password to
automatically have their passwords updated to an encrypted password when they
log in. Normally, this option is off. It can be turned on when you want an
installation using plain-text passwords to have everyone updated to encrypted
password authentication. It saves users the trouble of running the smbpasswd
command directly from the server. After everyone is updated, this feature can be
turned off. When this option is on, the encrypt passwords option should be set to
no.
 obey pam restrictions — Turn this on (Yes) if you want to use PAM for account and
session management. Even if set as yes, PAM is not used if the encrypted
passwords feature is turned on (encrypt passwords = yes).
 pam password change — Indicates to use the PAM password change control flag
for Samba. If this is on (Yes), SMB clients will use PAM instead of the program
listed in the Password Program value for changing SMB passwords.
 passwd program — Indicates which password program to use to change Linux user
passwords. By default, /usr/bin/passwd is used, with the current user name (%u)
inserted.
 passwd chat — Sets the chat that goes on between the Samba daemon (smbd)
and the Linux password program (/usr/bin/passwd by default) when smbd tries to
synchronize SMB passwords with Linux user passwords.
 username map — This sets the file used to map Samba user names. By default,
this file is /etc/samba/smbusers.
 unix password sync — With this on (Yes), Samba tries to update a user's Linux
user password with his/her SMB password when the SMB password is changed. To
do this, SMB runs the passwd command as the root user. This is on by default.
 guest account — Specifies the user name for the guest account. When a service is
specified as Guest OK, the user name entered here will be used to access that
service. The account is usually the nobody user name.
 hosts allow — Contains a list of one or more hosts that are allowed to use your
computer's Samba services. By default, users from any computer can connect to
the Samba server (of course, they still have to provide valid user names and
passwords). Usually, you use this option to allow connections from specific
computers (such as 10.0.0.1) or computer networks (such as 10.0.0.) that are
excluded by the hosts deny option.
 hosts deny — Contains a list of one or more hosts from which users are not
allowed to use your computer's Samba services. You can make this option fairly
restrictive, and then add the specific hosts and networks you want to use the
Samba server. By default, no hosts are denied.

Logging Options
132 Linux System and Networking Administration

The following options help define how logging is done on your Samba server:
 log level — Sets the debug level used when logging Samba activity. Raise the level
from the default (0) to log more Samba activity.
 log file — Defines the location of the Samba smb log file. By default, Samba log
files are contained in /var/log/samba (with file names log.nmbd, log.smbd, and
smb.log). In this option, the %m is replaced by smb to set the smb log file as
/var/log/samba/smb.log.
 max log size — Sets the maximum amount of space, in kilobytes, that the log files
can consume. By default, the value is set to 0 (no limit).

Assigning Guest Accounts

Samba always assigns the permissions level of a valid user on the Red Hat Linux system to
clients who use the server. In the case of share security, the user is assigned a guest
account (the nobody user account by default).
If the guest account value isn't set, Samba goes through a fairly complex set of rules to
determine which user account to use. The result is that it can be hard to assure which user
permissions will be assigned in each case. This is why it is recommended to use user
security if you want to provide more specific user access to your Samba server.

Tuning Options

The Socket Options option lets you pass options to the protocols Samba uses to
communicate. The following options are set by default: TCP_NODELAY, SO_RCVBUF=8192,
and SO_SNDBUF=8192. The first option disables Nagle's algorithm, which is used to
manage the transmission of TCP/IP packets. The other two options set the maximum size
of the sockets receive buffer and send buffer to 8192, respectively. These options are set
to improve performance (reportedly up to 10 times faster than without setting these
options). In general, you shouldn't change these options.

Printing Options

The printing option is used to define how printer status information is presented. For Red
Hat Linux, the value is typically cups. You can use printing styles from other types of
operating systems, such as UNIX System V (sysv), AIX (aix), HP UNIX (hpux), and
Berkeley UNIX (bsd), to name a few. LPRng (lprng), offered by many UNIX systems, is
also included.

Browse Options

A browse list is a list of computers that are available on the network to SMB services.
Clients use this list to find computers that are not only on their own LAN, but also
computers in their workgroups that may be on other reachable networks.
In Samba, browsing is configured by options described below and implemented by the
nmbd daemon. If you are using Samba for a workgroup within a single LAN, you probably
don't need to concern yourself with the browsing options. If, however, you are using
Samba to provide services across several physical subnetworks, you may consider
configuring Samba as a domain master browser. Here are some points to think about:
 Samba can be configured as a master browser. This allows it to gather lists of
computers from local browse masters to form a wide-area server list.

 If Samba is acting as a domain master browser, Samba should use a WINS server
to help browse clients resolve the names from this list.
 Samba can be used as a WINS server, although it can also rely on other types of
operating systems to provide that service.
Linux System and Networking Administration 133

 There should be only one domain master browser for each workgroup. Don't use
Samba as a domain master for a workgroup with the same name as an NT domain.
If you are working in an environment that has a mix of Samba and Windows NT servers,
you should use an NT server as your WINS server. If Samba is your only file server, you
should choose a single Samba server (nmbd daemon) to supply the WINS services.
To configure the browsing feature in Samba, you must have the workgroup named
properly (described earlier in this section). Here are the global options related to SMB
browsing.
 os level — Set a value to control whether your Samba server (nmbd daemon) may
become the local master browser for your workgroup. Raising this setting increases
the Samba server's chance to control the browser list for the workgroup in the
local broadcast area.
If the value is 0, a Windows machine will probably be selected. A value of 60 will
probably ensure that the Samba server is chosen over an NT server. The default is
20.
 preferred master — Set this to Yes if you want to force selection of a master
browser. By setting this to Yes, the Samba server also has a better chance of being
selected. (Setting Domain Master to Yes along with this option should ensure that
the Samba server will be selected.) This is set to Auto by default, which causes
Samba to try to detect the current master browser before taking that
responsibility.
 local master — Set this to Yes if you want the Samba server to become the local
browser master. (This is not a guarantee, but gives it a chance.) Set the value to
No if you do not want your Samba server selected as the local master. Local
Master is Auto by default.
 domain master — Set this to Yes if you want the Samba server (nmbd daemon) to
identify itself as the domain master browser for its workgroup. This list will then
allow client computers assigned to the workgroup to use SMB-shared files and
printers from subnetworks that are outside of their own subnetwork. This is set to
No by default.

WINS Options

Use the WINS options if you want to have a particular WINS server provide the name-to-
address translation of NetBIOS names used by SMB clients. As noted earlier, you probably
don't need to use a WINS server if all of the clients and servers in your SMB workgroup are
on the same subnetwork. That's because NetBIOS names can be obtained through
addresses that are broadcast. It is possible to have your Samba server provide WINS
services.
 wins server — If there is a WINS server on your network that you want to use to
resolve the NetBIOS names for your workgroup, you can enter the IP address of
that server here. Again, you will probably want to use a WINS server if your
workgroup extends outside of the local subnetwork.
 wins support — Set this value to Yes if you want your Samba server to act as a
WINS server. (It's No by default.) Again, this is not needed if all the computers in
your workgroup are on the same subnetwork. Only one computer on your network
should be assigned as the WINS server.
Besides the values described here, you can access dozens more options by clicking the
Advanced View button. When you have filled in all the fields you need, click Commit
Changes on the screen to have the changes written to the /etc/samba/smb.conf file.

Configuring Shared Directories With SWAT


To make your shared directory available to others, you can add an entry to the SWAT
window. To use SWAT to set up Samba to share directories, do the following:
134 Linux System and Networking Administration

1. From the main SWAT window, click the SHARES button.


2. Type the name of the directory that you want to share in the Create Share box,
then click Create Share.
3. Add any of these options:
o comment — A few words to describe the shared directory (optional).
o path — The path name of the directory you are sharing.
o guest account — If Guest OK is selected, then the user name that is
defined here is assigned to users accessing the file system. No password
will be required to access the share. The nobody user account (used only
by users who access your computer remotely) is the default name used.
(The FTP user is also a recommended value.)
o read only — If Yes, then files can only be read from this file system, but no
remote user can save or modify files on the file system. Select No if you
want users to be allowed to save files to this directory over the network.
o guest ok — Select Yes to enable anyone access to this directory without
requiring a password.
o hosts allow — Add the names of the computers that will be allowed to
access this file system. You can separate host names by commas, spaces,
or tabs. Here are some valid ways of entering host names:
o localhost — Allow access to the local host.
o 192.168.74.18 — IP address. Enter an individual IP address.
o 192.168.74. — Enter a network address to include all hosts on a network.
(Be sure to put a dot at the end of the network number or it won't work!)
o maple, pine — Enable access to individual hosts by name.
o EXCEPT host — If you are allowing access to a group of hosts (such as by
entering a network address), use EXCEPT to specifically deny access from
one host from that group.
o hosts deny — Deny access to specific computers by placing their names
here. By default, no particular computers are excluded. Enter host names
in the same forms you used for Hosts Allow.
o browseable — Indicates whether you can view this directory on the list of
shared directories. This is on (Yes) by default.
o available — Enables you to leave this entry intact, but turns off the service.
This is useful if you want to close access to a directory temporarily. This is
on (Yes) by default. Select No to turn it off.
4. Select Commit Changes.
At this point, the shared file systems should be available to the Samba client computers
(Windows 9x, Windows NT, Windows 2000/2003, Windows XP, OS/2, Linux, and so on)
that have access to your Linux Samba server. Before you try that, however, you can check
a few things about your Samba configuration.

Checking Your Samba Setup With SWAT


From the SWAT window, select the STATUS button.
From this window, you can restart your smbd and nmbd processes. Likewise, you can see
lists of active connections, active shares, and open files. (The preferred way to start the
smbd and nmbd daemons is to set up the smb service to start automatically. Type
chkconfig smb on to set the service to start at boot time.)

Working With Samba Files And Commands


Linux System and Networking Administration 135

Although you can set up Samba through the Samba Server Configuration window or SWAT,
many administrators prefer to edit the /etc/samba/smb.conf directly. As root user, you can
view the contents of this file and make needed changes. If you selected user security (as
recommended), you will also be interested in the smbusers and smbpasswd file (also in the
/etc/samba directory). These files, as well as commands such as testparm and smbstatus,
are described in the following sections.

Editing the smb.conf File


Changes you make using the Samba Server Configuration window or SWAT Web interface
are reflected in your /etc/samba/smb.conf file. Here's an example of an smb.conf file (with
comments removed):

[global]
workgroup = ESTREET
server string = Samba Server on Maple
hosts allow = 192.168.0.
printcap name = /etc/printcap
load printers = yes
printing = cups
log file = /var/log/samba/%m.log
max log size = 0
smb passwd file = /etc/samba/smbpasswd
security = user
encrypt passwords = Yes
unix password sync = Yes
passwd program = /usr/bin/passwd %u
passwd chat = *New*password* %n\n *Retype*new*password* %n\n *passwd:
*all*authentication*tokens*updated*successfully*
pam password change = yes
obey pam restrictions = yes
socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
username map = /etc/samba/smbusers
dns proxy = no

[homes]
comment = Home Directories
browseable = no
writable = yes
valid users = %S
create mode = 0664
directory mode = 0775

[printers]
136 Linux System and Networking Administration

comment = All Printers


path = /var/spool/samba
browseable = no
guest ok = no
writable = no
printable = yes

In the [global] section, the workgroup is set to ESTREET, the server is identified as the
Samba Server on Maple, and only computers that are on the local network (192.168.0.)
are allowed access to the Samba service. You must change the local network to match
your network.
Definitions for the local printers that will be shared are taken from the /etc/printcap file,
the printers are loaded (yes), and the cups printing service (which is the default print
service used by Red Hat Linux) is used.
Separate log files for each host trying to use the service are created in
/var/log/samba/%m.log (with %m automatically replaced with each host name). There is
no limit to log file size (0).
In this case, we are using user-level security (security = user). This allows a user to log in
once and then easily access the printers and the user's home directory on the Red Hat
Linux system. Password encryption is on (encrypt passwords = yes) because most
Windows systems have password encryption on by default. Passwords are stored in the
/etc/samba/smbpasswd file on your Linux system.
The dns proxy = no option prevents Linux from looking up system names on the DNS
server (used for TCP/IP lookups).
The [homes] section allows each user to be able to access his or her Linux home directory
from a Windows system on the LAN. The user will be able to write to the home directory.
However, other users will not be able see or share this directory. The [printers] section
allows all users to print to any printer that is configured on the local Linux system.

Adding Samba Users


Doing user-style Samba security means assigning a Linux user account to each person
using the Linux file systems and printers from his or her Windows workstation. (You could
assign users to a guest account instead, but in this example, all users have their own
accounts.) Then you need to add SMB passwords for each user. For example, here is how
you would add a user whose Windows 98 workstation login is chuckp:
Type the following as root user from a Terminal window to add a Linux user account:

# useradd -m chuckp

Add a Linux password for the new user as follows:

# passwd chuckp
Changing password for user chuckp
New UNIX password: ********
Retype new UNIX password: ********

Repeat the previous steps to add user accounts for all users from Windows workstations on
your LAN that you want to give access to your Linux system to.
Type the following command to create the Samba password file (smbpasswd):

# cat /etc/passwd | /usr/bin/mksmbpasswd.sh > /etc/samba/smbpasswd

Add an SMB password for the user as follows:


Linux System and Networking Administration 137

# smbpasswd chuckp
New SMB password: **********
Retype new SMB password: **********

Repeat this step for each user. Later, each user can log in to Linux and rerun the passwd
and smbpasswd commands to set private passwords.

Starting The Samba Service


To start the Samba SMB and NMB daemons, you can run the /etc/init.d/smb start-up script
by typing the following as the root user:

# service smb start

This runs the Samba service during the current session. To set up Samba to start
automatically when your Linux system starts, type the following:

# chkconfig smb on

This turns on the Samba service to start automatically in run levels 3, 4, or 5. You can now
check SMB clients on the network to see if they can access your Samba server.

Testing Your Samba Permissions


You can run several commands from a shell to work with Samba. One is the testparm
command, which you can use to check the access permissions you have set up. It lists
global parameters that are set, along with any shared directories or printers.

Checking The Status Of Shared Directories


The smbstatus command can view who is currently using Samba shared resources offered
from your Linux system. The following is an example of the output from smbstatus:

Samba version 2.2.8a


Service uid gid pid machine
----------------------------------------------
chris chris chris 1753 duck (10.0.0.5)
Tue Sep 2 09:16:20 2003

Locked files:
Pid DenyMode Access R/W Oplock Name
--------------------------------------------------------------
1753 DENY_NONE 0x2019f RDWR NONE /home/chris/~WRL35.tmp
Tue Sep 2 09:24:45 2003
1753 DENY_NONE 0x2019f RDWR NONE /home/chris/media.doc
Tue Sep 2 09:24:45 2003

This output shows that from your Red Hat Linux Samba server, the chris service (which is
a share of the /home/chris directory) is currently open by the computer named duck. The
user and group chris is being used to access the resource. PID 1753 is the process number
of the smbd daemon on the Red Hat Linux server that is handling the service. The files
open are the media.doc and ~WRL35.tmp in /home/chris. Both have read/write access.

Setting Up Samba Clients


138 Linux System and Networking Administration

Once you have configured your Samba server, you can try using the shared directories
from a client computer on your network. The following sections describe how to use your
Samba server from another Linux system or from various Windows systems.

Using Samba Shared Directories From Linux


There are several methods of connecting to shared directories from your Samba client. The
following sections address these methods.

Using Samba From Nautilus


Type smb: into your Nautilus file manager window Location box.
A list of SMB workgroups on your network appears in the window. You can select a
workgroup, choose a server, and then select a resource to use. This should work for shares
requiring no password.
The Nautilus interface seems to be a bit buggy when you need to enter passwords. Also, it
requires you to either send clear-text passwords or type the user and password into your
location box. For example, to get to my home directory (/home/chris) through Nautilus, I
can type my user name, password, server name, and share name as follows:

smb://chris:my72mgb@toys/chris

Mounting Samba Directories In Linux


Linux can view your Samba shared directories as it does any other medium (hard disk,
NFS shares, CD-ROM, and so on). Using the mount command, you can mount a Samba
shared file system so that it is permanently connected to your Linux file system.
The following example of the mount command shows how I would mount my home
directory (/home/chris) from a computer named toys on a local directory (/mnt/toys). As
root user, from a Terminal window, type:

# mkdir /mnt/toys
# mount -t smbfs -o username=chris,password=my72mgb //toys/chris
/mnt/toys

The file system type for a Samba share is smbfs (-t smbfs). I pass the username (chris)
and password (my72mgb) as options (-o). The remote share of my home directory on toys
is //toys/chris. The local mount point is /mnt/toys. At this point, you can access the
contents of /home/chris on toys as you would any file or directory locally. You will have the
same permission to access and change the contents of that directory (and its
subdirectories) as you would if you were the user chris using those contents directly from
toys.
To mount the Samba shared directory permanently, you can add an entry to your
/etc/fstab file. For the example just described, you could add the following line (as root
user):

//toys/chris /mnt/toys smbfs username=chris,password=my72mgb

Accessing Samba Shares from Windows Clients


Head over to a Windows machine to try out your new setup. Your new server should
appear in Windows' My Network Places (look for the shortcut on your desktop, by default).
Alternatively, open the Start menu and click "Run...", then enter:

\\server
Linux System and Networking Administration 139

Replacing server with the name or IP address of the machine running your Samba server.
A Windows Explorer window with the browseable shares from your server should open up.
If you've made a non-browseable share, access it using this link:

\\server\share name

Is is easy to make shared directories more accessible. In Windows XP, right click on the
share in Explorer and choose "Map Network Drive..." You will be able to assign them a
drive letter, such as Z:, so that they may be easily found in My Computer, even after a
reboot.
In my testing on Windows XP with the security level set to share, printers are
automatically be detected and available to use from the Windows machine. With user level
security set, it was necessary to log into the server in a Windows Explorer window before
trying to print. Your experience on other versions of Windows may vary.

Sharing with Network File System (NFS)

NFS – A Brief Overview

NFS, or Network File System, is a server-client protocol for sharing files between
computers on a common network. It is available on a variety of UNIX-based operating
systems, not just Linux. The server and client do not have to use the same operating
system. The client system just needs to be running an NFS client compatible with the NFS
server.
The NFS server exports one or more directories to the client systems, and the client
systems mount one or more of the shared directories to local directories called mount
points. After the share is mounted, all I/O operations are written back to the server, and
all clients notice the change as if it occurred on the local filesystem. A manual refresh is
not needed because the client accesses the remote filesystem as if it were local. Access is
granted or restricted by client IP addresses.
One advantage of NFS is that the client mounts the remote filesystem to a directory thus
allowing users to access it in the same method used to access local files. Furthermore,
because access is granted by IP address, a username and password are not required.
However, there are security risks to consider because the NFS server knows nothing about
the users on the client system. The files from the NFS server retain their file permissions,
user ID, and group ID when mounted. If the client uses a different set of user and group
IDs, file ownership will change.

NFS Server Configuration and Operation

NFS servers are relatively easy to configure. All that is required is to export a filesystem,
either generally or to a specific host, and then mount that filesystem remotely.

Required Packages
Two RPM packages are associated with NFS: portmap and nfs-utils. Use the rpm –q
packagename command to check for these packages, which should provide a number of
key files. The nfs-utils package includes:
 /etc/rc.d/init.d/nfs (start/stop script for NFS)
140 Linux System and Networking Administration

 /etc/rc.d/init.d/nfslock (start/stop script for lockd and statd)


 /usr/share/doc/nfs-utils-version (documentation, mostly in HTML format)
 Server daemons in /usr/sbin: rpc.mountd, rpc.nfsd
 Server daemons in /sbin: rpc.lockd, rpc.statd
 Control programs in /usr/sbin: exportfs, nfsstat, nhfsstone, showmount
 Status files in /var/lib/nfs: etab, rmtab, statd/state, xtab
The portmap package includes the following key files:
 /etc/rc.d/init.d/portmap (start/stop script)
 /usr/share/doc/portmap-version (documentation)
 Server daemon in /sbin: portmap
 Control programs in /usr/sbin: pmap_dump, pmap_set

Starting and Stopping NFS


Once it is configured, you can set up NFS to start during the Linux boot process, or you
can start it yourself with the /sbin/service nfs start command. NFS also depends on the
portmap package, which helps secure NFS directories that are shared through
/etc/exports. Because of this dependency, make sure to start the portmap before starting
NFS, and don’t stop it until after stopping NFS.
The nfs service script starts the following processes:
 rpc.mountd: Handles mount requests
 nfsd: Starts an nfsd kernel process for each shared directory
 rpc.rquotad: Reports disk quota statistics to clients
If any of these processes are not running, NFS won’t work. Fortunately, it’s easy to check
for these processes. Just run the rpcinfo -p command.

The /etc/exports File


The /etc/exports file is the only major NFS configuration file. You can set it up to list the
directories that are to be exported via the exportfs command. Each line in this file lists one
directory that may be exported, the hosts it will be exported to, and the options that apply
to this export. You can export a given directory only once. Take the following examples
from an /etc/exports file:

/pub (ro,sync) someone.mylocaldomain.com(rw,sync)


/home *.mylocaldomain.com(rw,sync)
/opt/diskless-root diskless.mylocaldomain.com(rw,no_root_squash,sync)

In the preceding example, /pub is exported to all users as read-only. It is also exported to
one specific computer with read-write privileges. /home is exported, with read-write
privileges, to any computer on the .mylocaldomain.com network. /opt/diskless-root is
exported with full read-write privileges (even for root users) on the
diskless.mylocaldomain.com computer.
All of these options include the sync flag. This requires all changes to be written to disk
before a command such as a file copy is complete. This is a new change for Red Hat 8.0; in
future releases, sync may become the default for all NFS shares.

Wildcards and Globbing


In Linux network configuration files, you can specify a group of computers with the right
wildcard. This process in Linux is sometimes also known as globbing. What you do for a
Linux System and Networking Administration 141

wildcard varies with the type of configuration file. The NFS /etc/exports file is somewhat
conventional in this respect; for example, the *.mydomain.com entry specifies all
computers within the mydomain.com domain. In contrast, /etc/hosts.deny is less
conventional; .mydomain.com, with the leading dot, specifies all computers in that same
domain.
Sometimes you can specify a group of computers with the right IP address line; for
example, 192.168.0.0/255.255.255.0 specifies the 192.168.0.0 network of computers with
IP addresses that range from 192.168.0.1 to 192.168.0.254. Some services allow the use
of CIDR (Classless Inter-Domain Routing) notation; in that case, you can specify the same
network with the 192.168.0.0/24 entry.

Activating the List of Exports


Changing /etc/exports is not enough. This file is simply the default set of exported
directories. You need to activate them with the /usr/sbin/exportfs -a command. This file
can be set up to run when Linux boots. Alternatively, you can run this command yourself
to test your changes to /etc/exports. You can even use /usr/sbin/exportfs to export a
directory directly, bypassing /etc/exports.
When you add a share to /etc/exports, the /usr/sbin/exportfs -r command adds the new
directories. However, if you’re modifying, moving, or deleting a share, it is safest to first
temporarily unexport all filesystems with the /usr/sbin/exportfs –ua command before
reexporting the shares with the /usr/sbin/exportfs -a command.
Once exports are active, they’re easy to check. Just run the /usr/sbin/showmount –e
command on the server. If you’re looking for the export list for a remote NFS server, just
add the name of the NFS server as an argument to this command. If this command doesn’t
work, you may have NFS messages blocked on the client or the server with a firewall.

NFS Client Configuration and Operation

Now you can mount a shared NFS directory from a client computer. The commands and
configuration files are similar to those used for any local filesystem.

NFS and /etc/fstab


NFS clients can be configured to mount remote NFS filesystems, as well as local
filesystems during the boot process, based on the configuration in /etc/fstab. For example,
the following entry in a client /etc/fstab mounts the /homenfs share from the computer
named nfsserv, on the local /nfs/home directory:

Alternatively, an automounter, such as autofs or amd, can be used to dynamically mount


NFS filesystems as required by the client computer. The automounter can also unmount
these remote filesystems after a period of inactivity.

Client-Side Helper Processes


When you start NFS as a client, it adds a few new system processes, including:
 rpc.statd Tracks the status of servers, for use by rpc.lockd in recovering locks after
a server crash
 rpc.lockd Manages the client side of file locking
142 Linux System and Networking Administration

Diskless Clients
NFS supports diskless clients, which are computers without a hard drive. A diskless client
may use a boot floppy or a boot PROM to get started. Then embedded commands can
mount the appropriate root (/) directory, swap space, the /usr directory as read-only, and
other shared directories such as /home in read/write mode. If your computer uses a boot
PROM, you’ll also need access to DHCP and TFTP servers for network and kernel
information.

Configuring NIS Clients

Introduction to NIS

Generally, access to a Red Hat Linux system requires a valid username and password. One
problem with a large network of Linux systems is that “normally,” each user requires an
account on every Linux computer.
The Network Information System (NIS) allows you to set up one centrally managed
database of usernames and passwords for your Unix and Linux systems.
With NIS, you can maintain one password database on an NIS server and configure the
other systems on the network as NIS clients. When a user logs into an NIS client, that
system first checks its local password file, usually /etc/passwd. If it can’t find your
username, it looks up the corresponding file on the NIS server.
NIS clients and NIS servers are organized in NIS domains. You can have multiple NIS
domains on a single network, but clients and servers can belong to only one domain. If
you are using NIS, you can find out the name of your NIS domain by using this command:

Domainname

NIS provides you with more than a shared authorization database. With NIS, you can
provide shared access to any kind of information. By default, NIS under Red Hat Linux
shares the following files:
 /etc/passwd
 /etc/group
 /etc/hosts
 /etc/rpc
 /etc/services
 /etc/protocols
 /etc/mail/*
You can configure NIS to share other files as well. This is easy to configure in the NIS
configuration file, /var/yp/Makefile.
NIS services require at least one NIS master server. This is where the centralized NIS
database files, known as maps, are stored. NIS changes require an update to the map on
the master server. You can have only one NIS master server per NIS domain.
(NIS maps are stored in the /var/yp/DOMAIN directory, where DOMAIN is the name of
your NIS domain.)
For larger networks or redundancy, you may also want an NIS slave server. NIS slaves
take copies of the NIS maps from the master server. NIS clients can then get their
configuration files from either the master server or a slave server. You can have multiple
NIS slave servers on a network.
Linux System and Networking Administration 143

NIS clients are systems that use information from an NIS server. NIS clients don’t store
any information that is contained in the NIS databases; whenever that information is
needed, it is retrieved from a server.

NIS Components on Red Hat Linux

The /usr/lib/yp directory includes the utilities you need to configure and manage NIS
services. The ypinit program can configure an NIS server. The following table lists the files
needed to configure an NIS server.

File Description

/usr/lib/yp/ypinit Shell script to build initial database maps on


an NIS server in /var/yp; ypinit -m builds
the databases for a master server.

/var/yp/Makefile Configuration file. Edit this file to control


which files are shared via NIS. Implement
the changes from the /var/yp directory with
the make command.

/usr/sbin/ypserv NIS server daemon. Remember to use


/sbin/chkconfig to make sure it will start
when you boot Linux.

/usr/sbin/yppasswdd NIS password update daemon. Allows users


to change their NIS passwords with the
yppasswd command. Remember to use
/sbin/chkconfig to make sure it starts when
you boot Linux.

/etc/ypserv.conf The ypserv daemon configuration file.

/var/yp/securenets Controls which systems can access NIS


databases. See the ypserv man page for an
example.

Although NIS was designed to enable you to manage security by controlling who has
access to the systems on your network, NIS is not a very secure product. Anyone who
knows your NIS domain name and can connect to your network can read all the
information stored in your NIS databases, such as /etc/passwd.
You can do a couple of things to help protect your NIS database. The /var/yp/securenets
file can control who can connect to your NIS server. This file is easy to configure. Only two
lines are required for a LAN:

host 127.0.0.1
255.255.255.0 192.168.0.0

The first line allows access from the local computer. The second line may look a bit
backward, but it allows access from all of the computers with IP addresses on the
192.168.0.0 network.
Once you’ve configured an NIS server, it’s easy to configure an NIS client. Just use
authconfig. The figure below shows the authconfig screen used to configure NIS. This will
configure your system to use the ypbind daemon, and add the appropriate entries in the
/etc/yp.conf, /etc/nsswitch.conf, and /etc/pam.d/system-auth files. All you need is the
name of the NIS domain, and the name of the computer where it’s located.
144 Linux System and Networking Administration

Fig - Configuring an NIS Client with authconfig


The other command you need to know about when running an NIS client is yppasswd. All
users can manage their NIS password with this command.

The Name Service Switch File

The Name Service Switch file (/etc/nsswitch.conf ) governs the search order. For example,
when an NIS client looks for a computer host name, it might start with the following entry
from /etc/nsswitch.conf:

hosts: files nisplus nis dns

This line tells your computer to search through name databases in the following order:
1. Start with the database of host names and IP addresses in /etc/hosts.
2. Next, search for the host name in a map file based on NIS+ (NIS Version 3).
3. Next, search for the host name in a map file based on NIS (Version 2).
4. If none of these databases includes the desired host name, refer to the DNS
server.
Linux System and Networking Administration 145

Configuring the Apache Web Server

Introduction to Apache Web Server

Apache is by far the most popular Web server in use today. Based on the HTTP daemon
(httpd), Apache provides simple and secure access to all types of content using the
regular HTTP protocol as well as its secure cousin, HTTPS.
Apache was developed from the server code created by the National Center for
Supercomputing Applications (NCSA). It included so many patches that it became known
as "a patchy" server. The Apache Web server continues to advance the art of the Web and
provides one of the most stable, secure, robust, and reliable Web servers available. This
server is under constant development by the Apache Software Foundation
(www.apache.org).
While there are numerous other Web servers available, Apache is the only Web service
described in the current RH300 course outline.
Apache is a service; basic Apache clients are Web browsers. This section provides the
briefest of overviews on Apache. For more information, read the documentation online at
http://httpd.apache.org/docs-2.2.

Apache 2.2

Red Hat Enterprise Linux includes the latest major release of Apache, which is 2.2.x as of
this writing. While there are major differences from previous versions of Apache (1.3.x,
2.0.x), if you're a Web administrator or developer, the differences with respect to the
RHCE exam are fairly straightforward. The current version supports virtual hosts and
access control, as well as secure (HTTPS) Web services. If you're interested in more, a full
list of new features is available from
http://httpd.apache.org/docs/2.2/new_features_2_2.html.
The following cites a few of the major changes:
 New packages If you're installing Apache from the Red Hat Installation RPMs, all
the package names have changed. As you'll see in the following section, most start
with httpd. Strangely enough, the username associated with Apache services is
now apache.
 Modular directive files Basic directives, such as those based on Perl, PHP, or the
Secure Socket Layer, are now configured separately in the /etc/httpd/conf.d
directory. They are automatically included in the Apache configuration with the
following directive in /etc/httpd/conf/httpd.conf:

Include conf.d/*.conf

 Revised directives Some directives have changed in the httpd.conf configuration


file. For example, Apache listens for computers that are looking for Web pages on
port 80. You can now change that port with the Listen directive.
 Virtual hosts Apache configuration is now normally based on virtual hosts, which
allows you to host multiple Web sites on the same Apache server, using a single I P
address.
 Larger files Apache now supports files greater than 2GB.
 Encryption Apache now supports encrypted authentication, as well as LDAP.
You may see some of these characteristics if you use Apache 1.3.x, as many of these
features have been "backported" from current versions of Apache.
146 Linux System and Networking Administration

Installation

The RPM packages required by Apache are included in the Web Server package group. If
required on the Installation and Configuration portion of the exam, you should install
Apache during the installation process. But mistakes happen. Just remember that the
simplest way to install Apache after installation is with the following command:

# yum install httpd

Alternatively, if you need the Red Hat GUI Apache Management tool, run the following
command, which also installs the Apache httpd RPM as a dependency:

# yum install system-config-httpd

Another option is to just install the default packages associated with the entire Web Server
package group with the following command:

# yum groupinstall web-server

If you don't remember the names of available groups, run the yum grouplist command.
From the output, you should see "Web Server"; in other words, the following command
also works:

# yum groupinstall "Web Server"

If your exam instructions require the installation of other packages such as mod_ssl
(required for secure Web sites) and Squid, you can combine their installation in the same
command:
# yum install mod_ssl squid
If in doubt about package names, you can find them in the Web Server package group, as
documented on the first installation CD in the Server/repodatata/comps-rhel5-server-
core.xml file. If you're working with the RHEL 5 desktop, substitute Client for Server
(upper- and lowercase). Once you've connected to a repository such as the RHN, the same
information should be available in comps.xml in the /var/cache/yum/rhel-i386-server-5
directory. If you're working a different architecture and a client, substitute accordingly.

Starting on Reboot

Once Apache is installed, you'll want to make sure it starts the next time you boot Linux. If
it doesn't start when the person who grades your Red Hat exam reboots your computer,
you may not get credit for your work on the Apache service.
The most straightforward way to make sure Apache starts the next time you boot Linux is
with the chkconfig command. You'll need to set it to start in at least runlevels 3 and 5,
with a command such as:

# chkconfig --level 35 httpd on

Alternatively, you can configure it to start in all standard runlevels (2, 3, 4, and 5) with the
following command:

# chkconfig httpd on

To determine whether the chkconfig command worked, use the --list switch:

# chkconfig --list httpd

Normally to start services, it's best to use the associated script in the /etc/init.d directory,
which contains an httpd script. However, Apache often starts and stops more gracefully
with the following commands:

# apachectl stop

# apachectl start
Linux System and Networking Administration 147

Once you've got Apache running, start a Web browser and enter a URL of
http://localhost. If Apache installation is successful, you should see the screen similar to
the following figure.

Fig - The default Apache Web page


Read the screen and you will see that RHEL looks for Web page files in the /var/www/html
directory. You can verify this with the DocumentRoot directive in the main Apache
configuration file. If you want to create a custom error page, you can set it in the
/etc/httpd/conf.d/welcome.conf file.

The Apache Configuration Files

There are two key configuration files for the Apache Web server: httpd.conf in the
/etc/httpd/conf directory and ssl.conf in the /etc/httpd/conf.d directory. The default
versions of these files create a generic Web server service you can further customize and
optimize, as desired. There are other configuration files in two directories: /etc/httpd/conf
and /etc/httpd/conf.d. They're illustrated in the following figure.

Fig - Apache configuration files


148 Linux System and Networking Administration

You need to know the httpd.conf file in the /etc/httpd/conf directory well. If you're
required to configure a secure Web server, you'll also need to configure the ssl.conf
configuration file in the /etc/httpd/conf.d directory.

Analyzing the Default Apache Configuration

Apache comes with a well-commented set of default configuration files. In this section,
you'll look at the key commands in the httpd.conf configuration file, in the /etc/httpd/conf
directory. Browse through this file in your favorite text editor or using a command such as
less. Before beginning this analysis, keep two things in mind:
If you configure Apache with the Red Hat HTTP tool (system-config-httpd), it overwrites
any changes that you may have made with a text editor.
The main Apache configuration file incorporates the files in the /etc/httpd/conf.d directory
with the following directive:

Include conf.d/*.conf

There are a couple of basic constructs in httpd.conf. First, directories, files, and modules
are configured in "containers." The beginning of the container starts with the name of the
directory, file, or module to be configured, contained in directional brackets (< >).
Examples of this include:

<Directory "/var/www/icons">
<Files ~ "^\.ht">
<IfModule mod_mime_magic.c>

The end of the container starts with a forward slash (/). For the same examples, the ends
of the containers would look like:

</Directory>
</Files>
</IfModule>

Next, Apache includes a substantial number of directives-commands that Apache can


understand that have some resemblance to English. For example, the ExecCGI directive
allows executable CGI scripts.
As the RHCE course divides the discussion of Apache into different units, I do the same
here. However, the following sections, with the exception of secure virtual hosts, are based
on the same httpd.conf file in the /etc/httpd/conf/ directory.

Analyzing httpd.conf

This section examines the default Apache configuration file, httpd.conf. If you want to
follow along, open it on your system. Only the default active directives in that file are
discussed here. Read the comments; they include more information and options.
For detailed information on each directive, see
http://httpd.apache.org/docs/2.2/mod/quickreference.html. The default directives are
summarized in the following three tables. The following table specifies directives
associated with Section 1: Global Environment.

Directive Description

ServerTokens Specifies the response code at the bottom of error pages; if


you're interested, see what happens when you change the
values between OS, Prod, Major, Minor, Min, and Full.
Linux System and Networking Administration 149

Directive Description

ServerRoot Sets the default directory; other directives are subdirectories.

PidFile Names the file with the Process ID (and locks the service).

Timeout Limits access time for both sent and received messages.

KeepAlive Supports persistent connections.

MaxKeepAliveRequests Limits requests during persistent connections (unless set to 0,


which is no limit).

KeepAliveTimeout Sets a time limit, in seconds, before a connection is closed.

StartServers Adds child Apache processes; normally set to 8, which means 9


Apache processes run upon startup.

MinSpareServers Specifies a minimum number of idle child servers.

MaxSpareServers Specifies a maximum number of idle child servers; always at


least +1 greater than MinSpareServers.

ServerLimit Sets a limit on configurable processes; cannot exceed 20000.

MaxClients Limits the number of simultaneous requests; other requests to


the server just have to wait.

MaxRequestsPerChild Limits the requests per child server process.

MinSpareThreads Specifies the minimum number of spare threads to handle


additional requests.

MaxSpareThreads Specifies the maximum number of available idle threads to


handle additional requests.

ThreadsPerChild Sets the number of threads per child server process.

Listen Specifies a port and possibly an IP address (for multihomed


systems) to listen for requests.

LoadModule Loads various modular components, such as authentication,


user tracking, executable files, and more.

Include Adds the content of other configuration files.

User Specifies the username run by Apache on the local system.

Group Specifies the group name run by Apache on the local system.

In all three tables, directives are listed in the order shown in the default version of
httpd.conf. If you want to experiment with different values for each directive, save the
change and then use apachectl restart to restart the Apache daemon. If not defined in
150 Linux System and Networking Administration

these tables, directives are described, later in this chapter, as they appear in the
configuration file.
The following table specifies directives associated with Section 2: Main Server
Configuration.

Directive Description

ServerAdmin Sets the administrative e-mail address; may be shown (or linked
to) on default error pages.

UseCanonicalName Supports the use of ServerName as the referenced URL.

DocumentRoot Assigns the root directory for Web site files.

Options Specifies features associated with Web directories, such as


ExecCGI, FollowSymLinks, Includes, Indexes, MultiViews, and
SymLinksIfOwnerMatch.

AllowOverride Supports overriding of previous directives from .htaccess files.

Order Sets the sequence for evaluating Allow and Deny directives.

Allow Configures host computers that are allowed access.

Deny Configures host computers that are denied access.

UserDir Specifies location of user directories; can be set to enable or


disable for all or specified users.

DirectoryIndex Specifies files to look for when navigating to a directory; set to


index.html by default.

AccessFileName Sets a filename within a directory for more directives; normally


looks for .htaccess.

TypesConfig Locates mime.types, which specifies file types associated with


extensions.

DefaultType Sets a default file type if not found in mime.types.

MIMEMagicFile Normally looks to /etc/httpd/conf/magic to look inside a file for


its MIME type.

HostNameLookups Requires URL lookups for IP addresses; results are logged.

ErrorLog Locates the error log file, relative to ServerRoot.

LogLevel Specifies the level of log messages.

LogFormat Sets the information included in log files.

CustomLog Creates a customized log file, in a different format, with a


location relative to ServerRoot.
Linux System and Networking Administration 151

Directive Description

ServerSignature Adds a list with server version and possibly ServerAdmin e-mail
address to error pages and file lists; can be set to On, OFF, or
EMail.

Alias Configures a directory location; similar to a soft link.

DAVLockDB Specifies the path to the lock file for the WebDAV (Web-based
Distributed Authoring and Versioning) database.

ScriptAlias Similar to Alias; for scripts.

IndexOptions Specifies how files are listed from a DirectoryIndex.

AddIconByEncoding Assigns an icon for a file by MIME encoding.

AddIconByType Assigns an icon for a file by MIME type.

AddIcon Assigns an icon for a file by extension.

DefaultIcon Sets a default icon for files not otherwise configured.

ReadmeName Configures a location for a README file to go with a directory


list.

HeaderName Configures a location for a HEADER file to go with a directory


list.

IndexIgnore Adds files that are not included in a directory list.

AddLanguage Assigns a language for file name extensions.

LanguagePriority Sets a priority of languages if not configured in client browsers.

ForceLanguagePriority Specifies action if a Web page in the preferred language is not


found.

AddDefaultCharset Sets a default character set; you may need to change it for
different languages.

AddType Maps file name extensions to a specified content type.

AddHandler Maps file name extensions to a specified handler; commonly


used for scripts or multiple languages.

AddOutputFilter Maps file name extensions to a specified filter.

BrowserMatch Customizes responses to different browser clients.

The following table specifies directives associated with Section 3: Virtual Hosts. While
virtual host directives are disabled by default, I include those directives in the commented
example near the end of the default httpd.conf file. While these directives were already
152 Linux System and Networking Administration

used in other sections, you can-and should-customize them for individual virtual hosts to
support different Web sites on the same Apache server.

Directive Description

NameVirtualHost Specifies an IP address for multiple virtual hosts.

ServerAdmin Assigns an e-mail address for the specified virtual host.

DocumentRoot Sets a root directory for the virtual host.

ServerName Names the URL for the virtual host.

ErrorLog Creates an error log; the location is based on the


DocumentRoot.

CustomLog Creates an custom log; the location is based on the


DocumentRoot.

Basic Apache Configuration for a Simple Web Server

As described earlier, Apache looks for Web pages in the directory specified by the
DocumentRoot directive. In the default httpd.conf file, this directive points to the
/var/www/html directory.
In other words, all you need to get your Web server up and running is to transfer Web
pages to the /var/www/html directory.
The default DirectoryIndex directive looks for an index.html Web page file in this
directory. You can test this for yourself by copying the default Firefox home page file,
index.html, from the /usr/share/doc/HTML directory.
The base location of configuration and log files is determined by the ServerRoot directive.
The default value from httpd.conf is

ServerRoot "/etc/httpd"

You'll note that the main configuration files are stored in the conf and conf.d subdirectories
of the ServerRoot. If you run the ls -l /etc/httpd command, you'll find that Red Hat
links /etc/httpd/logs to the directory with the actual log files, /var/log/httpd.

Configuring Dynamic Host Configuration Protocol


(DHCP)

Introduction

There are two protocols that allow a client computer to get network configuration
information from a server: DHCP (Dynamic Host Configuration Protocol) and BOOTP. DHCP
works if you have a DHCP server on the local network. The BOOTP protocol is required if
you're getting information from a DHCP server on another network.
DHCP servers can simplify and centralize network administration if you're administering
more than a few computers on a network. They are especially convenient for networks
with a significant number of mobile users. The BOOTP protocol is essentially just a way to
access a DHCP server on a remote network.
Linux System and Networking Administration 153

As of this writing, Red Hat does not include any GUI tool to configure a DHCP server. You'll
have to do your work in this section from the command line interface.

Installing DHCP Packages

As with most network services, DHCP has a client and a server. These are based on the
dhcp and dhclient RPM packages. The dhclient RPM package should be installed by default;
if you're using a service such as NetworkManager, you'll also need the dhcdbd package. If
you're working with IPv6, you'll need the dhcpv6_ client. On the server side, the dhcp RPM
package is installed by default with the Network Server package group.

DHCP Server Configuration

A DHCP server sends messages to multiple computers on a LAN. This is also known as a
multicast. It should be enabled by default. You can confirm this with the ifconfig
command. The output should resemble the following figure, which includes a MULTICAST
setting for the active network card.

Fig - Active network interfaces MULTICAST


If you don't see MULTICAST associated with your network card, someone has compiled
this feature out of your kernel.
Now configure the DHCP server daemon, dhcpd, by creating or editing the /etc/dhcpd.conf
configuration file. Normally, this file allows the DHCP server to assign IP addresses
randomly from a specific range. But the default version of this file is blank. You can start
with the dhcpd.conf.sample file in the /usr/share/doc/dhcp-versionnum directory. The lines
that start with a hash mark (#) are comments in the file. Let's analyze this sample file in
detail:
 ddns-update-style interim With this command, the RHEL DHCP server conforms
as closely as possible to the current Dynamic DNS standard, where the DNS
database is updated when the DNS server renews its DHCP lease. It is "interim"
because the standards for DDNS are not complete as of this writing.
 ignore client-updates A good setting if you don't want to allow users on client
computers to change their host names.
154 Linux System and Networking Administration

 subnet 192.168.0.0 netmask 255.255.255.0 Describes a network with an


address of 192.168.0.0 and a subnet mask of 255.255.255.0. This allows the local
DHCP server to assign addresses in the range 192.168.0.1 to 192.168.0.254 to
different computers on this network. If you've configured a different network IP
address, you'll want to change these settings accordingly.
 option routers Lists the default router. You can use more than one option
routers directive if you have more than one connection to an outside network.
This information is passed to DHCP clients as the default gateway, which supports
access to outside networks such as the Internet. You'll want this command to
reflect the IP address for the gateway for your network.
 option subnet-mask Specifies the subnet mask for the local network.
 option nis-domain Notes the server that provides the NIS shared authorization
database. If you've configured NIS on your network, you'll want to substitute the
name of your NIS domain for domain.org. Otherwise, you should comment out this
command.
 option domain-name Adds the domain name for your network. Substitute the IP
address for the DNS servers you want your clients to use.
 option domain-name-servers Notes the IP address for the DNS server for your
network. You can add more commands of this type to specify additional DNS
servers.
 option time-offset Lists the difference from Greenwich Mean Time, also known as
UTC (a French acronym), in seconds.
 option ntp-servers Notes any Network Time Protocol (NTP) servers for keeping
the time on the local computer in sync with UTC. I describe NTP later in this
chapter.
 option netbios-name-servers Adds the location of any Windows Internet
Naming Service (WINS) servers for your network.
 option netbios-node-type 2 Peer-to-peer node searches, associated with WINS.
 range dynamic-bootp 192.168.0.128 192.168.0.254 Specifies the assignable
IP addresses to remote networks, using the BOOTP protocol.
 default-lease-time Specifies the lease time for IP address information, in
seconds.
 max-lease-time Specifies the maximum lease time for IP address information, in
seconds.
 next-server Notes the boot server for network computers. If you don't have any
network computers, you can comment out this entire stanza.
You can also assign a specific IP address to a computer based on a client's Ethernet
address. Just add an entry similar to the following to /etc/dhcpd.conf:
host mommabears {
hardware ethernet 08:00:12:23:4d:3f;
fixed-address 192.168.0.201;
}
This specifies what the DHCP server does when a network card with a hardware address of
08:00:12:23:4d:3f tries to connect via Ethernet. In this case, the IP address
192.168.0.201 is assigned to a client named mommabears.
Naturally, you'll want to modify this file accordingly for your particular network. For
example, if you've configured computers on the example.org network described earlier in
this book, you'll want to substitute example.org and the associated IP addresses in your
/etc/dhcpd.conf file. I've done this for my network in the following figure.
Linux System and Networking Administration 155

Fig -Sample DHCP configuration file


DHCP can be customized for individual computers. You can set up static IP addresses for
servers. Once you're ready, start the dhcpd service with the following command:

# service dhcpd start

By default, this starts a DHCP server, which listens for requests on the eth0 network card.
Alternatively, to have a DHCP server listen on the eth1 network interface, run the following
command:

# service dhcpd start eth1

If these commands don't get a response, you probably haven't created a /etc/dhcpd .conf
configuration file.
You can watch the DHCP server in action. Stop the DHCP server with the service dhcpd
stop command. You can then restart it in the foreground with standard error descriptors
with the following command:

# /usr/sbin/dhcpd -d -f

Start another Linux/Unix client. Make it look for another DHCP lease with the dhclient -r
and dhclient commands, and then watch the console of the server. You'll see a number of
DHCP communication messages on the server that illustrates the process of leasing an IP
address to a client.
Once you've configured your DHCP server to your satisfaction, remember to activate it at
the appropriate runlevels with a command such as:

# chkconfig dhcpd on
156 Linux System and Networking Administration

DHCP and Microsoft Windows

In order for the DHCP server to work correctly with picky DHCP clients such as Microsoft
Windows 9x, the server needs to send data to the broadcast address: 255.255.255.255.
Unfortunately, Linux insists on changing 255.255.255.255 into the local subnet broadcast
address. The mixed message results in a DHCP protocol violation, and while Linux DHCP
clients don't notice the problem, Microsoft DHCP clients do. Normally, such clients can't see
DHCPOFFER messages and therefore don't know when to take an IP address offered from
the DHCP server. If you're configuring a DHCP server for a network with Microsoft Windows
computers, run the following command,

# route add --host 255.255.255.255 dev eth0

where eth0 is the name of the NIC that connects the server to the network.

Client Configuration

You can set up DHCP as a client using the dhclient command, or you can use the Red Hat
Network Configuration tool (which you can also start with the System | Administration |
Network command). Alternatively, configuring a DHCP client at the command line is not
difficult (and is faster on the Red Hat exams). Make sure that the /etc/sysconfig/network
configuration file includes the following line:

NETWORKING=yes

Next, make sure that the /etc/sysconfig/network-scripts/ifcfg-eth0 script contains the


following lines (if you're using a different network device, modify the appropriate file in
/etc/sysconfig/network-scripts directory):

BOOTPROTO='dhcp'
ONBOOT='yes'

If you don't want the DHCP server to assign a DNS server in the client's /etc/ resolv.conf,
add the following directive:

PEERDNS=no

The next time you reboot, your network configuration should look for DHCP address
information automatically from the DHCP server for your network.
Alternatively, you can use the Network Configuration tool from a GUI to configure DHCP.
You can also start it from a GUI terminal console with the system-config-network
command. When the tool opens, select your network card and click Edit. You should see a
window similar to what is shown in the following figure.
Linux System and Networking Administration 157

Fig - Configuring your network card


If you want to use DHCP on this computer, select the Automatically Obtain IP Address
Settings With option. You'll then get to choose between getting IP address information
from a DHCP server on your local network, using BOOTP to get IP address information
from a remote network, or going through a dial-up connection, such as to an ISP. Once
you've activated the changes, restart the network daemon with the service network
restart command. Your network card will then look for IP address information from a
DHCP server.

DHCP Client Troubleshooting

If the DHCP client configuration instructions in this chapter are not working, there may be
a problem with the way the network is set up on your Linux computer. For example,
The NIC is not configured properly. Reconfigure your network card.
If the computer is still having problems finding a DHCP server, check your firewall. If port
67 or 68 is blocked, your computer won't be able to get a message to the server.
158 Linux System and Networking Administration

Configuring File Transfer Protocol (FTP)

Introduction to FTP

FTP, the File Transfer Protocol, is one of the original network applications developed with
the TCP/IP protocol suite. It follows the standard model for network services, as FTP
requires a client and a server. The FTP client is installed by default on most operating
systems, including Red Hat Linux. The FTP server often needs to be installed separately.
Unlike other network services, FTP servers are controlled through the xinetd superserver.
If you have installed an FTP server such as wu-ftpd, you’ll find it controlled through the
/etc/xinetd.d directory. By default, these types of servers are disabled.

FTP Client

The original FTP client software was a basic command line, text-oriented client application
that offered a simple but efficient interface. Most Web browsers offer a graphical interface
and can also be used as an FTP client.
Any FTP client allows you to view the directory tree and files. Using ftp as a client is easy.
Take a look at ftp.redhat.com with the commands shown in the following figure.

Fig - Using the FTP text client


The RedHat FTP site requires anonymous logins.
Almost all commands in FTP mode are run at the remote host, similar to a Telnet session.
You can also run commands locally from the FTP prompt. When you start the command
with an !, you can run regular shell commands. Basic FTP client commands are shown in
the following figure.
Linux System and Networking Administration 159

Fig - Basic FTP client commands


This is only a subset of the commands available from the FTP client. Typing the help
command will give you a full list of the available commands. The command help cmd yields
a brief description of the command itself.
For a more functional command line–driven FTP client, check out the ncftp package, which
is currently available on one of the Red Hat Installation CDs. This FTP client adds these
features:
 Recursive directory downloads
 Command line recall and edit (in the style of bash)
 Command line history
 Automatic anonymous logins
 Much easier command line FTP use
One graphical FTP client for Linux is GNOME FTP (GFTP). GNOME FTP provides an easy-to-
use GUI interface to FTP. It also offers these features:
 Restartable transfers
 Multiple independent transfers
 Download file queuing
 Transferring whole directory trees (recursive transfers)
 Drag-and-drop transfer activation
 Session names and settings
all without requiring you to know a single FTP command. See the following figure for a
view of GNOME FTP. You can start the GFTP client from the command line with the gftp
command from a GUI terminal window.
160 Linux System and Networking Administration

Fig - The GNOME FTP client

FTP Installation

Two of the ways you can set up an FTP server are with the following packages: anonftp
and wu-ftpd. As always, you can check whether or not they’re installed with the rpm -q
packagename command.

anonftp
The anonftp package allows you to set up an FTP server without having to go through the
trouble of setting up user accounts for those who need access. The installation creates a
/var/ftp directory tree. Add files that you want to make available through the anonftp
server to the /var/ftp/pub directory.
For security, users won’t be able to cd above the /var/ftp directory. This limitation is made
possible through anonftp’s use of the chroot system call. This means that users who
connect to your anonymous FTP server see /var/ftp as the root (/) directory.

WU-FTP
The FTP server for authenticated (known) users is known as wu-ftpd. This package lets you
set up usernames, passwords, and more for all users who connect to this server.
Additional features include control of transfer and command logs, on -the-fly compression
and archiving (using gzip), user type and location classification, limits on a per-class (local,
remote) basis, directory upload permissions, restricted guest accounts, messages per
directory and system, and virtual name support.
Linux System and Networking Administration 161

One of the other excellent advanced features of WU-FTP is its ability to provide full user
and group-specific authorization of FTP services. WU-FTP adds a third group of “guest”
users. You can configure access for various users and groups in /etc/ftpaccess.

Configuring a Simple Anonymous FTP Server

When you install the anonftp package, you’ve set up an FTP service that allows anonymous
access. Before you test your installation from any host on the network, make sure th at the
FTP server service is active.
As strange as it sounds, you can activate anonftp by changing the following line in
/etc/xinetd.d/wu-ftpd from yes to no:

disable = yes

Then restart the xinetd script with the /etc/rc.d/init.d/xinetd restart command.
This rereads the settings in all of the files in the /etc/xinetd.d directory. Alternatively, use
the /sbin/chkconfig wu-ftpd on command. That also changes the value of the disable
variable in /etc/xinetd.d/wu-ftpd.
Testing Your FTP Service Now you can test the anonymous login features of your new FTP
server. From any command line, use the FTP client to connect to any FTP server. Like any
network connection, the FTP client needs a valid network address.
If you use a host name, the system needs to be able to resolve the computer name such
as redhattest to an IP address, using a file such as /etc/hosts, or a DNS server.

Configuring Telnet

What is Telnet?

Telnet is a terminal emulation program that allows you to connect to remote computers.
The Linux telnet server is controlled by the /etc/xinetd.d/telnet configuration file.

Telnet Installation and Configuration

In order to turn Telnet on:


1. Make sure that you have install the telnet-server and telnet RPMs:

yum install telnet-server telnet

2. Open /etc/xinetd.d/telnet

vi /etc/xinetd.d/telnet

3. Make sure that disable = yes is changed to read disable = no.

disable = no

4. Type following to enable and start service on port 23:

chkconfig telnet on
chkconfig xinetd on
162 Linux System and Networking Administration

service xinetd restart

Telnet Usage

The command to do remote logins via telnet from the command line is simple. You enter
the word telnet and then the IP address or server name to which you want to connect.
Here is an example of someone logging into a remote server named smallfry from server
bigboy. The user looks at the routing table and then logs out.
[root@bigboy tmp]# telnet 192.168.1.105
Trying 192.168.1.105...
Connected to 192.168.1.105.
Escape character is '^]'.

Linux 2.4.18-14 (smallfry.my-site.com) (10:35 on Sunday, 05 January


2003)

Login: peter
Password:
Last login: Fri Nov 22 23:29:44 on ttyS0
You have new mail.
[peter@smallfry peter]$
[peter@smallfry peter]$ netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt
Iface
255.255.255.255 0.0.0.0 255.255.255.255 UH 40 0 0
wlan0
192.168.1.0 0.0.0.0 255.255.255.0 U 40 0 0
wlan0
127.0.0.0 0.0.0.0 255.0.0.0 U 40 0 0
lo
0.0.0.0 192.168.1.1 0.0.0.0 UG 40 0 0
wlan0
[peter@smallfry peter]$ exit
logout

Connection closed by foreign host.


[root@bigboy tmp]#

Configuring Squid

What is Squid?

Squid is a high-performance HTTP and FTP caching proxy server. It can make your
network connections more efficient. As it stores data from frequently used Web pages and
files, it can often give your users the data they need without having to look to the
Internet.
Extremely large studies have shown bandwidth reduction of 10–20 percent for all HTTP
and FTP traffic, which is economically compelling for large installations. You can join the
worldwide hierarchy of Harvest Cache sites; see http://www.ircache.net/ for more
information.
Squid conforms to the Harvest Cache architecture and uses the Inter-Cache Protocol (ICP)
for transfers between participating peer and parent/child cache servers. It can be used
Linux System and Networking Administration 163

either as a traditional caching proxy or as a front-end accelerator for a traditional Web


server. Squid accepts only HTTP requests but speaks FTP on the server side when FTP
objects are requested.

Required Packages for Squid

To run Squid, you need the following files installed on your computer:
 /etc/rc.d/init.d/squid Start/stop script
 /etc/squid/ Configuration directory
 /usr/share/doc/squid-version Documentation, mostly in HTML format
 /usr/lib/squid/ Support files and internationalized error messages
 /usr/sbin/client Command line diagnostic client program
 /usr/sbin/squid Main Squid daemon
 /var/log/squid/ Log directory
 /var/spool/squid/ Cache directory (Hundreds of MB and maybe more in many
hashed directories)

Initializing Squid

When you start Squid for the first time, the /etc/rc.d/init.d/squid start script automatically
runs squid -z to create the /var/spool/squid/ cache directories and then starts the Squid
daemon. Squid runs as a caching proxy server on port 3128. You can then set up Web
browsers on your LAN to point to your computer through port 3128 as the proxy server.

Configuration Options

Advanced configuration features are adjusted via the /etc/squid/squid.conf configuration


file. The default configuration file allows you to tune and secure Squid in a number of
ways. A key configuration section contains cache_peer lines, which specify parent and
sibling Squid cache servers. If your Linux computer is part of a group of Squid servers in a
harvest cache, these lines allow your Squid servers to check these other Squid servers
before going to the Internet.
The following figure illustrates an excerpt from the default squid.conf configuration file,
which specifies one parent and two sibling cache hosts. Squid first checks its own cache
and then queries its siblings and parents for the desired object such as a Web page. If
neither the cache host nor its siblings have the object, it asks one of its parents to fetch it
from the source. If no parent servers are available, it fetches the object itself.
164 Linux System and Networking Administration

Fig - Squid can refer to parent and sibling Squid servers

Configuring Squid to Act as a Proxy for Web and FTP Service

This exercise assumes you have a LAN. One of the computers on the LAN is also a server
that is connected to the Internet. In this exercise, you’ll install Squid on that server. Then
you can configure Squid to act as a proxy for Web and FTP service for your LAN.
1. Open the Squid configuration file, /etc/squid/squid.conf. If you have enough
computers on your LAN, configure one parent and one child cache site.
2. Start and stop the Squid service.
3. Configure a test client such as a Web browser to use your Squid service. Test your
client by using both HTTP and FTP addresses in the browser address.
Use it to retrieve files from various sites on the Internet, such as www.redhat.com and
ftp.redhat.com.
Linux System and Networking Administration 165

CHAPTER 7: SHELL SCRIPTING

Shells
A shell can be used in one of two ways:
 A command interpreter, used interactively
 A programming language, to write shell scripts (your own custom commands)
There are two popular classes of shells:
 C shell (csh) and variants (tcsh)
 Bourne shell (sh) and variants (bash, ksh)

Shell Scripts
A shell script is just a file containing shell commands, but with a few extras:
 The first line of a shell script should be a comment of the following form:

#!/bin/sh

for a Bourne shell script. Bourne shell scripts are the most common, since C Shell
scripts have buggy features.
 A shell script must be readable and executable.

chmod u+rx scriptname

 As with any command, a shell script has to be “in your path” to be executed.
If “.” is not in your PATH, you must specify “./scriptname” instead of just
“scriptname”

The echo Command


The echo Command:
 Displays messages on the screen
 Displays the text, enclosed within double-quotes
 Puts a newline character at the end of the text by default
Example:

$ echo "This is an example of the echo command”


This is an example of the echo command
$_
166 Linux System and Networking Administration

Shell Script Example


Here is a “hello world” shell script:

$ ls -l
-rwxr-xr-x 1 horner 48 Feb 19 11:50 hello*
$ cat hello
#!/bin/sh
# comment lines start with the # character
echo "Hello world"
$ hello
Hello world
$

Shell Variables
The user variable name can be any sequence of letters, digits, and the underscore
character, but the first character must be a letter.
To assign a value to a variable:

number=25
name="Bill Gates“

There cannot be any space before or after the “=“. Internally, all values are stored as
strings.

Creating Variables
Variables in shell scripts:
 Are not declared as integers or characters
 Are treated as character strings
 Can be mathematically manipulated
 Do not have to be explicitly declared
 Can be created at any point of time by a simple assignment of value
The syntax for creating a variable is:

<variable name>=<value>

Variables can be created:


 In shell scripts: A variable created within a shell script is lost when the script stops
executing.
 At the shell prompt: A variable created at the prompt remains in existence until
the shell is terminated.
To use a variable, precede the name with a “$”:
Linux System and Networking Administration 167

$ cat test1
#!/bin/sh
number=25
name="Bill Gates"
echo "$number $name"

$ test1
25 Bill Gates

Referencing Variables
The $ symbol is used to refer to the content of a variable:

variable1=${variable2}

The braces are essentially used to delimit the variable name.


The command to assign the value of today variable to x variable is:

$ x=$today

Reading a Value into a Variable


The read command is used to enter a value from the keyboard into a variable during the
execution of a shell script.
The read command reads one line of input from the keyboard and assigns it to one or
more user-supplied variables.
The syntax to use the read command is:

$ read <variable_name>

The read command, on execution, waits for the user to enter a value for the variable.
When the user presses <Enter> key after entering the value, the remaining part of the
shell script, if any, is executed.
Example

$ cat test2
#!/bin/sh
echo "Enter name: “
read name
echo "How many branches are there? "
read number
echo "$name has $number branches.“
168 Linux System and Networking Administration

$ test2
Enter name:
HCL
How many branches are there?
more than 300
HCL has more than 300 branches.

Local and Global Shell Variables


A local variable is a variable that can be given a different value in the child shell without
the parent shell knowing about it, as shown in the following example:

$ continent=Africa
$ echo "$continent"
Africa
$ bash [Creates a new shell]
$ echo "$continent" [There is no response]
$ continent=Asia [Gives new value Asia to continent]
$ echo "$continent"
Asia
Press <Ctrl> d
$ exit [Displays exit and returns to parent shell]

The export variable is a global variable that is passed on by the export command as an
argument to all child shells.

Environment Variables
All exported variables are environment variables, some of which are meaningful to the
shell. By changing the values of these variables, a user can customize the environment.
Some of the environment variables are:
 HOME: Stores the location of the HOME directory of a user
 PATH: Contains a list of colon-delimited path names of directories that are to be
searched for an executable program
 PS1: Contains the shell prompt, the $ symbol. You can change the shell prompt by
setting the value of this variable to the desired prompt
 PS2: Sets a value for the secondary prompt, which is by default >
 LOGNAME: Contains the user’s login name
 SHLVL: Contains the shell level that you are currently working in
 SHELL: Stores the user’s default shell
Linux System and Networking Administration 169

Special Characters to Use with PS1

Printing $
Use a backslash before $ if you really want to print the dollar sign:

$ cat test4
#!/bin/sh
echo "Enter amount: “
read cost
echo "The total is: \$$cost“

$ test4
Enter amount:
18.50
The total is $18.50

You can also use single quotes for printing dollar signs. Single quotes turn off the special
meaning of all enclosed dollar signs:

$ cat test5
#!/bin/sh
echo "Enter amount: “
read cost
echo ‘The total is: $’ "$cost"

$ test5
170 Linux System and Networking Administration

Enter amount:
18.50
The total is $ 18.50

Command Substitution

Introduction

Command substitution allows you to use more than one command in a single command
line. The expr command is used to evaluate arithmetic expressions as shown below:

$ expr 4 + 5

The test and [] Command

Evaluates an expression and returns either a true (0) or a false (1)


Can also be replaced with []
Uses the following syntax:

test expression or [ expression ]

Enables you to test multiple conditions in one command using the options -a and -o

expr

Shell programming is not good at numerical computation, it is good at text processing.


However, the expr command allows simple integer calculations.
Here is an interactive Bourne shell example:

$ i=1
$ expr $i + 1
2

To assign the result of an expr command to another shell variable, surround it with
backquotes:

$ i=1
$ i=`expr $i + 1`
$ echo "$i"
2

The * character normally means “all the files in the current directory”, so you need a “ \” to
use it for multiplication:

$ i=2
$ i=`expr $i \* 3`
$ echo $i
6
Linux System and Networking Administration 171

expr also allows you to group expressions, but the “(“ and “)” characters also need to be
preceded by backslashes:

$ i=2
$ echo `expr 5 + \( $i \* 3 \)`
11

expr Example:

$ cat test6
#!/bin/sh
echo "Enter height of rectangle: “
read height
echo "Enter width of rectangle: “
read width
area=`expr $height \* $width`
echo "The area of the rectangle is $area"

$ test6
Enter height of rectangle:
10
Enter width of rectangle:
5
The area of the ractangle is 50
$ test6

Enter height of rectangle:


10.1
Enter width of rectangle:
5.1

expr: non-numeric argument

Backquote
A command or pipeline surrounded by backquotes causes the shell to:
 Run the command/pipeline
 Substitute the output of the command/pipeline for everything inside the quotes
You can use backquotes anywhere:

$ whoami
gates
172 Linux System and Networking Administration

$ cat test7
#!/bin/sh
user=`whoami`
numusers=`who | wc -l`
echo "Hi $user! There are $numusers users logged on."

$ test7
Hi gates! There are 6 users logged on.

Control Flow

Introduction

The shell offers constructs for looping and decision-making, which can be used in shell
scripts.
The shell allows several control flow statements:
 If
 case…esac
 while
 for

The if Construct

The if Construct is used to perform decision making in shell scripts. The if construct is
usually used in conjunction with the test command:

if <condition>
then <command(s)>
[else <command(s)>]
fi

Example of if Construct:

# see if a file exists


if [ -e /etc/passwd ]
then
echo “/etc/passwd exists”
else
echo “/etc/passwd not found!”
fi

The if…elif Construct


Linux System and Networking Administration 173

Another variant of if construct is the if...elif construct. In this construct, the elif works as
an else if. The elif part of the construct always appears before the else part of the
construct, and is executed if the if condition is false.
The syntax of which is as follows:

if condition(s)
then command(s)
elif condition
then command(s)
else command(s)
fi

Example of if…elif Construct

$ cat test8
#!/bin/sh
users=`who | wc -l`
if [ $users -ge 4 ]
then
echo "Heavy load"
elif [ $users -gt 1 ]
then
echo "Medium load"
else
echo "Just me!"
fi

$ test8
Heavy load!

The case…esac Construct

Is often used in place of the if construct if a variable is tested against multiple values.
Evaluates the value of the variable and compares it with each value specified.
The syntax to use the case ... esac construct is:

case $variable-name in
value1) command
.
command;;
value2) command
.
command;;
*) command;;
esac
174 Linux System and Networking Administration

Example of case…esac Construct

echo -n "Enter a string: "


read xval
case ${xval} in
dozen)
echo "12"
;;
score)
echo "20"
;;
*)
echo "Neither a dozen nor a score";;
esac

The while Construct

The while Construct supports iteration in shell scripts. The while construct has the
following syntax:

while <condition>
do
<command (s)>
Done

The while statement loops indefinitely, while the condition is true, such as a user-
controlled condition.
Example of while Construct

reply=y
while test "$reply" != "n"
do
echo –n "Enter file name?"
read fname
cat ${fname}
echo –n "wish to see more files :"
read reply
done

The for Construct

The for construct takes a list of values as input, and executes the loop for every value in
the loop. The for construct has the following syntax:

for variable_name in <list_of_values>


do

Linux System and Networking Administration 175

done

The for construct supports wildcard characters in the list of values such as, *.c
Example of the for Construct
Example #1

for name in Ruby Samuel


do
echo "${name}"
done

Example #2

for NAMEFILE in `ls tempdir`


do
echo "Displaying contents of ${NAMEFILE}"
cat tempdir/${NAMEFILE}
done

The exit Command

The exit command is used to stop execution of the shell script and return to the command
prompt based on the result of the test command.
The following is an example of the exit command,

echo "Do you wish to quit?"


read ans
if [ $ans = "y" ]
then exit
fi

The exit command can also be used in the then part of the if…else construct.

The break and continue Command

The break and continue commands are used with while loop. The break command causes
the termination of a loop. The continue command is used to resume execution in the while
loop.
An example of the break command is as shown below:

while true
do
echo "Enter choice"
echo "(press 'q' to exit)"
echo "1 date 2 who"
echo "3 ls 4 pwd"
read choice
case $choice in
1)date;;
176 Linux System and Networking Administration

2)who;;
3)ls;;
4)pwd;;
q)break;;
*)echo "That was not one of the choices";;
esac
done

An example of the break command is as shown below:

while true
do
echo "Enter choice"
echo "(press 'q' to exit)"
echo "1 date 2 who"
echo "3 ls 4 pwd"
read choice
case $choice in
1)date;;
2)who;;
3)ls;;
4)pwd;;
q)break;;
*)echo "That was not one of the choices";;
esac
done

File Tests
The test command options used to test the file status are listed in the following table:
Linux System and Networking Administration 177

Some more test command options used to test the file status are listed in the following
table:

Arithmetic Tests
The test command can also be used for arithmetic tests as listed in following table.
178 Linux System and Networking Administration

String Tests
The test command can also be used with strings. The string test operators available are
listed in the following table.

Parameter Handling In Shell Scripts


Parameters are used to pass arguments from the command line to a shell script. A
parameter is any word, normally a file name, or a string, which is specified along with a
command name or file name at the shell prompt.
Within the script itself, the parameter is referred to as an argument.
The shell creates a maximum of nine variables other than $0. The variables, $1 through
$9, are also called positional parameters of the command line.
Besides the variables, $0 to $9, the shell assigns values to the following variables when a
command is entered:
 $*: Contains the entire string of arguments.
 $#: Contains the number of arguments specified in the command.
Parameters can be used to create new commands or programs

The shift Command


The shift command is useful if you want to pass more than nine parameters to a shell
script.
The following shell script uses the shift command in parameter handling:

if test $# -eq 0
then echo "Arguments required"
exit
fi
command=$1
shift

if test $command = 'c'


Linux System and Networking Administration 179

then
if test $# -ne 2
then echo "Invalid number of arguments for copy"
else cp $1 $2
fi
elif test $command = 'd'
then
if test $# = 0
then echo "Invalid number of arguments for delete"
else rm $*
fi
else echo "Invalid argument - must be 'c' or 'd'"
fi

Functions
A function:
 Is a block of statements that are referred to by a specific name and perform a
specific task
 Should be used when you need to perform the same task repeatedly
 Is invoked by specifying the function name
 Should be created before invoking it
The syntax to create a function is:

function <function_name>
{
<commands>
}

An example of a function is shown below:

function ftype
{
if test -f $fname
then echo "$fname is an ordinary file."
elif test -d $fname
then echo "$fname is a directory file."
elif test ! -r "$fname"
then echo "No readable file called $fname exists"
fi
180 Linux System and Networking Administration

}
echo "Enter a file name"
read fname
ftype

Shell scripting also allows you to pass arguments to function.


The syntax to pass arguments to a function is:

<function name> [ arg1 arg2 ... ]


Linux System and Networking Administration 181

CHAPTER 8: HANDLING ELECTRONIC MAIL

Introduction
With the popularity of e-mail, these days just about everyone has an e-mail address.
Because of that, people often expect to receive data via e-mail instead of seeing files or
printouts. That’s no different in the shell script world. If you generate any type of report
from your shell script, most likely at some point you’ll be asked to e-mail the results to
someone. This chapter shows you just how to set up your Linux system to support e -
mailing directly from your shell scripts. It also shows you how to make sure that your
Linux system can send outbound mail messages, and how to make sure you have a mail
client that can do that from the command line. But first, the chapter presents a brief
overview of the way Linux handles e-mails in general.

The Basics of Linux E-Mail


Sometimes the hardest part of using e-mail in your shell scripts is understanding just how
the e-mail system works in Linux. Knowing what software packages perform what tasks is
crucial in getting e-mails from your shell script to your inbox. This section walks you
through the basics of how Linux systems use e-mail, and what you need to have in place
before you can use it.

E-Mail in Linux

The Linux system derives its e-mail system from the Unix environment. One of the main
goals of the Unix operating system was to modularize software. Instead of having one
monolithic program that handles all of the required pieces of a function, Unix developers
created smaller programs each of which handles a smaller piece of the total functionality of
the system.
182 Linux System and Networking Administration

Fig - Linux modular e-mail environment


This philosophy was used when implementing the e-mail systems used in Unix, and was
carried over to the Linux environment. In Linux, e-mail functions are divided into separate
pieces, each assigned to separate programs. Figure 26-1 shows how most open source e-
mail software modularizes e-mail functions in the Linux environment.
As you can see in Figure below, in the Linux environment the e-mail process is normally
divided into three functions:
 The Mail Transfer Agent (MTA)
 The Mail Delivery Agent (MDA)
 The Mail User Agent (MUA)
The lines between these three functions are often fuzzy. Some e-mail packages combine
functionality for the MDA and MTA functions, whereas others combine the MDA and MUA
functions.
The following sections describe these basic e-mail components and how they are
implemented in Linux systems in more detail.

The Mail Transfer Agent

The MTA software is the core of the Linux e-mail system. It’s responsible for handling both
incoming and outgoing mail messages on the system. For each outgoing mail message the
must determine the destination of the recipient addresses. If the destination host is the
local system, the MTA can either deliver it to the local mailbox directly or pass the
message off to the local MDA for delivery. However, if the destination host is a remote mail
server, the MTA must establish a communication link with the MTA software on the remote
host to transfer the message. There are two common methods that MTA software
packages use to deliver mail to remote hosts:
 Direct delivery
 Proxy delivery
Linux System and Networking Administration 183

If your Linux system is directly connected to the Internet, it can often deliver messages
destined for recipients on remote hosts directly to the remote host. The MTA software uses
the Domain Name System (DNS) to resolve the proper network IP address to deliver the
mail message, then establishes the TCP connection using the Simple Mail Transfer Protocol
(SMTP).
There are plenty of times when a host is not directly connected to the Internet, or it
doesn’t want to communicate directly with other remote hosts. In those situations, it
usually uses a smart host. The smart host is a proxy server that accepts mail messages
from your Linux system, then attempts to directly deliver them to the intended recipient.
Smart hosts are becoming more difficult to work with on the Internet due to relay spam. A
rogue server sends relay spam by bouncing thousands of unsolicited commercial e-mail
(UCE) messages off of a smart host to hide its identity. Most smart hosts now require
some type of authentication before forwarding messages to other hosts.
For incoming messages, the MTA must be able to accept connection requests from remote
mail servers and receive messages destined for local users. Again, the most common
protocol used for this process is SMTP.
The Linux environment has many different types of open source MTA programs. Each
program offers different features that distinguish it from the others. By far the two most
popular you’ll run into are:
 sendmail
 Postfix
We’ll examine both of these e-mail MTA packages in detail in the ‘‘Setting Up Your Server’’
section.

The Mail Delivery Agent

The MDA program’s responsibility is to deliver a message destined for a local user. It
receives messages from the MTA program and must determine exactly how and where
those messages should be delivered. Figure 26-2 demonstrates how the MDA program
interacts with the MTA program to deliver mail.

Fig – Using an MDA program


While sometimes the MDA function is performed within the MTA program itself, often Linux
e-mail implementations rely on a separate stand-alone MDA program to deliver messages
to local users. Because these MDA programs concentrate only on delivering mail to local
184 Linux System and Networking Administration

users, they can add additional bells and whistles that aren’t available on MTA programs
that include MDA functionality.
This enables the mail administrator to offer additional mail features to mail users, such as
mail filtering for spam, out-of-office redirections, and automatic mail sorting. When the
MDA program receives a message, it must ensure that the message is delivered to the
proper location, either to the local user’s mailbox or to an alternate location defined by the
local user.
There are currently three different types of user mailboxes commonly used on Linux
systems:
 /var/spool/mail or /var/mail files
 $HOME/mail files
 Maildir-style mailbox directories
Each mailbox type has its own features that make it attractive to use. Most Linux
distributions use either the /var/spool/mail or /var/mail directories to contain individual
mailbox files, one file for each user account on the system. This is a central location for all
mailbox files so that MUA programs know where to find everyone’s mailbox file.
A few Linux distributions allow you to move the individual mailbox files to each user’s
$HOME directory. This provides greater security, in that each mailbox file is located in an
area already set with the proper access privileges.
Maildir-style mailboxes are a relatively new feature supported by some more advanced
MTA, MDA, and MUA applications. Instead of each message being part of a mailbox file,
the mailbox is a directory, and each message is a separate file in that directory. This helps
cut down on mailbox corruption, as a single message won’t corrupt the entire mailbox.
While Maildir-style mailbox directories offer increased performance, security, and fault
tolerance, there are many popular MDA and MUA programs that aren’t able to use them.
Just about all MDA and MUA programs can use the /var/spool/mail mailbox files.
The original Unix location for mailboxes is /var/spool/mail. Most Linux
distributions use this file-naming convention; however, there are a few Linux
distributions that use /var/mail instead.
If your system does use a special MDA program to process incoming mail messages, most
likely it’s the popular Procmail program. Procmail allows each individual user to create a
customized configuration file to define mail filters, out-of-office destinations, and separate
mailboxes.

The Mail User Agent

So far we’ve followed the e-mail traffic from the remote host to the local host to an
individual user’s mailbox. The next step in the process is to allow individual users to view
their e-mail messages.
The Linux e-mail model uses a local mailbox file or directory for each user to hold
messages for that user. The job of the MUA program is to provide a method for users to
interface with their mailboxes to read their messages.
It’s important to remember that MUAs don’t receive messages; they only display messages
that are already in the mailbox. Many MUA programs also offer the ability to create
separate mail folders so the user can move mail from the default mailbox (often called the
inbox) to separate folders for organization.
Most MUA programs also provide the ability to send messages. This part gets a little fuzzy,
because as you’ve already seen, sending e-mail messages is the job of the MTA program.
To perform this function, most MUA programs utilize the smart host feature in SMTP.
Either the MUA program automatically delivers messages to the local MTA program for
delivery, or you must define a remote smart host in the MUA configuration for it to send
messages to for delivery.
Linux System and Networking Administration 185

Throughout the years, many different open source MUA programs have been available for
the Linux platform. The following sections describe some of the more popular MUA
programs you’ll run across in Linux.

Mailx

The Mailx program is the most popular command line MUA program in use for the Linux
environment. The name Mailx comes from its being an improvement over the original mail
program developed for Unix. In all installations the Mailx program installs with the
executable file mail, indicating that it’s a replacement for the mail program, rather than a
separate program.
The Mailx program allows users to access their mailboxes to read stored messages, as well
as to send messages to other mail users, all from the command line. Here’s a sample Mailx
session.

$ mail
Mail version 8.1.2 01/15/2001. Type ? for help.
"/var/mail/rich": 2 messages 2 new
›N 1 atest@testbox Fri Feb 1 17:42 16/664 This is a test
N 2 atest@testbox Fri Feb 1 17:43 16/676 This is another
test
&1
Message 1:
From atest@testbox Fri Feb 1 17:42:56 2008
Date: Fri, 1 Feb 2008 17:42:56 -0500
From: atest@testbox
To: rich@localhost.localdomain
Subject: This is a test
This is a test message.
&d
&q
Held 1 message in /var/mail/rich
$mail Barbara
Subject: This is a test message
This is a test message that I’m sending to Barbara.
.
Cc:
$

The first line shows the Mailx program being executed with no command line options. By
default this allows the user to check the messages in his mailbox. After entering the mail
command, a summary of all of the messages in the user’s mailbox is displayed. The Mailx
program can only read messages in the /var/mail format or $HOME/mail format. It’s not
able to process mail using the Maildir mail folder format.
Each user has a separate file that contains all of his messages. The filename is usually the
system login name of the user and is located in the system mailbox directory. Thus, all
186 Linux System and Networking Administration

messages for user name rich are stored in the file /var/mail/rich on the Linux system. As
new messages are received for the user, they are appended to the end of the file.
The second use of the mail command demonstrates sending a mail message to another
user from the command line. The name of the recipient is included on the command line
with the program name. The Mailx program queries for the message subject, then allows
you to type in the text of the message. To terminate the message, enter a line with a
single period. To finish, the Mailx program queries if there should be any additional
recipients to receive a copy of the message, then it terminates and attempts to pass the
message to the MTA program for delivery.

Mutt

As advancements were made to the Unix environment, MUA programs became fancier.
One of the first attempts at graphics on Unix systems was the ncurses graphics library.
Using ncurses a program could manipulate the location of a cursor on the terminal screen
and place characters almost anywhere on the terminal.
One MUA program that takes advantage of the ncurses library is the Mutt program. When
you start Mutt it paints a user-friendly menu on the terminal display, listing the messages
similar to the output of the Mailx program. You can select a message and view it in the
display, as shown in Figure below:
The Mutt program uses key combinations to perform standard functions, such as read a
message and start a new message. Possibly the most useful feature for shell script
programmers is the ability to send messages directly from the command line, without
going into text-graphics mode.

Graphical e-mail clients

Almost all Linux systems support the graphical X Window environment. There are many e-
mail MUA programs that utilize the X Window system to display message information. The
two most popular graphical MUA programs available are:
 KMail for the KDE windows environment
 Evolution for the GNOME windows environment
Linux System and Networking Administration 187

Fig- The KMail MUA program main screen


Each of these packages allows you to interact with your local Linux mailbox, as well as
connect to remote mail servers to read mail messages. The preceding figure shows a
sample KMail session screen.
To connect with remote servers, both KMail and Evolution support the Post Office Protocol
(POP), and the more advanced Internet Message Access Protocol (IMAP). While the KMail
and Evolution MUA programs are great for desktop Linux, they aren’t so useful in shell
scripting.

Setting Up Your Server


Before you can start sending your automated e-mail messages off to the universe, you’ll
need to ensure that your Linux system has an MTA package running and that it’s
configured correctly.
This is no small task in itself, but fortunately, some Linux distributions provide some basic
tools to help you out.
This section walks you through the basics of the two most popular e-mail MTA programs
used in Linux: sendmail and Postfix. While there have been complete books written on
properly configuring each of these packages, we’ll just look at the basics to see how to get
e-mails off the Linux system and into your inbox.

sendmail

The sendmail MTA package is one of the most popular open source MTA packages used by
Internet mail servers. In the past it had been plagued with stories about backdoors and
security flaws; however, it has been rewritten not only to remove the security flaws but
also to incorporate many newer MTA features such as spam control. The newer versions of
the sendmail program have proven to be secure as well as versatile.
188 Linux System and Networking Administration

Parts of the sendmail program

The main executable program is called sendmail. It normally runs in background mode,
listening for SMTP connections from remote mail servers, and forwarding outbound
messages from local users.
Besides the main sendmail program, there’s a configuration file and several tables that it
uses to contain information used while processing incoming and outgoing mail messages.
Table 26-1 lists all the parts used in a normal sendmail installation.
Unless you’re running the main mail server for a corporation or Internet service provider,
all you’ll need to worry about is the sendmail.cf configuration file. In fact, many Linux
distributions that use sendmail create and configure a core sendmail.cf configuration file
for you automatically that should work just fine in most simple applications.

The sendmail.cf file

The sendmail program needs to be told how to handle messages as the server receives
them. As an MTA, sendmail processes incoming mail and redirects it to another mail
package, either on a remote system or on the local system. The configuration file is used
to direct sendmail how to manipulate the destination mail addresses to determine where
and how to forward the messages.
The default location for the configuration file is /etc/mail/sendmail.cf. The sendmail.cf file
consists of rule sets that parse the incoming mail message and determine what actions to
take. Each rule set is used to identify certain mail formats and instruct sendmail how to
handle that message.
As the sendmail program receives a message, it parses the message header and passes
the message through the various rule sets to determine an action to take on the message.
The sendmail configuration file includes rules that allow sendmail to handle mail in many
different formats. Mail received from an SMTP host has different header fields than mail
received from a local user. The sendmail program must know how to handle any mail
situation.
Linux System and Networking Administration 189

Rules also have helper functions defined in the configuration file. There are three different
types of helper functions that you can define:
 Classes define common phrases that are used to help the rule sets identify certain
types of messages.
 Macros are values that are set to simplify the typing of long strings in the
configuration file.
 Options are defined to set parameters for the sendmail program’s operation.
The configuration file is made up of a series of classes, macros, options, and rule sets.
Each function is defined as a single text line in the configuration file.
Each line in the configuration file begins with a single character that defines the action for
that line. Lines that begin with a space or a tab are continuation lines from a previous
action line. Lines that begin with a pound sign (#) indicate comments and are not
processed by sendmail.
190 Linux System and Networking Administration

The action at the beginning of the text line defines what the line is used for. Table below
shows the standard sendmail actions and what they represent.
As I mentioned, most likely you won’t have to start from scratch with your sendmail.cf
configuration file, the Linux distribution should create a standard template file for you.
Figure below shows part of the sendmail.cf configuration file from a Debian-based Linux
system.
Most likely, the only piece you’ll have to worry about is if you must use a smart host to
forward mail for you. The DS configuration line controls this feature:
 DSmyisp.com
 Just add the hostname of the smart host immediately after the DS tag.

Postfix

The Postfix software package is quickly becoming one of the more popular e-mail packages
available for Unix and Linux systems. Postfix was developed by Wietse Venema to provide
an alternative MTA for standard Unix-type servers. The Postfix software is capable of
turning any Unix or Linux system into a fully functional e-mail server.
It is the responsibility of the MTA package to manage messages that come into or leave
the mail server. Postfix accomplishes this message tracking by using several different
modular programs, and a system of mail queue directories. Each program processes
messages through the various message queues until they are delivered to their final
destinations. If at any time the mail server crashes during a message transfer, Postfix can
determine what queue the message was last successfully placed in and attempt to
continue the message processing.

Parts of the Postfix system

The Postfix system consists of several mail queue directories and executable programs, all
interacting with each other to provide mail service. Figure 26-6 shows a block diagram of
the core Postfix parts.
Linux System and Networking Administration 191

Each piece of the Postfix block diagram provides a different function for the whole e -mail
process.
The following sections describe the different pieces of the Postfix block diagram in more
detail.
The Postfix package utilizes a master program that runs as a background process at all
times. The master program allows Postfix to spawn programs that scan the mail queues for
new messages and send them to the proper destinations. The core program s can be
configured to remain running for set times after they are utilized. This allows the master
program to reutilize a running helper program if necessary, saving processing time. After a
set time limit, the helper program quietly stops itself.

Fig - Block diagram of Postfix

The master program is used to control the overall operation of Postfix. It is responsible for
starting other Postfix processes as needed. The qmgr and pickup programs are configured
to remain as background processes longer than other core programs. The pickup program
determines when messages are available to be routed by the Postfix system. The qmgr
program is responsible for the central message routing system for Postfix.
Table below shows other core programs that Postfix uses to transfer mail messages.
192 Linux System and Networking Administration

Unlike some other MTA packages, Postfix uses several different message queues for
managing e-mail messages as they are processed. Each message queue contains
messages in a different message state in the Postfix system. The table below lists the
message queues that are used by Postfix. If the Postfix system should be shut down at any
time, messages remain in the last queue in which they were placed. When Postfix is
restarted, it will automatically begin processing messages from the queues.
Linux System and Networking Administration 193

Postfix configuration files

The next block in the diagram is the Postfix configuration files. The configuration files
contain information that the Postfix programs use when processing messages. Unlike some
other MTA programs, it’s possible to change configuration information while the Postfix
server is running and issue a command to have Postfix load the new information without
completely downing the mail server.
There are three Postfix configuration files, which are located in a common Postfix directory.
Often the default location for this directory is /etc/postfix. Usually, all users have access to
view the configuration files, whereas only the root user has the ability to change values
within the files. Of course, this can be modified for your own security situation. Table 26-5
lists the Postfix configuration files.
The install.cf configuration file allows you to retrieve installation parameters that were
used when the Postfix software was first installed on the system. This provides an easy
way to determine which features are or aren’t available in the software setup.
The master.cf configuration file controls the behavior of the core Postfix programs. Each
program is listed in a separate line along with the parameters to control its operation.
Here’s a sample master.cf file with default settings.

The master.cf configuration file also includes lines for directing Postfix on how to interface
with external MDA software, such as Procmail. The Postfix operational parameters are set
in the main.cf configuration file. All of the Postfix operational parameters have default
values that are implied within the Postfix system. If a parameter value is not present in the
main.cf file, its value is preset by Postfix. If a parameter value is present in the main.cf
file, its contents override the default value.
Each Postfix parameter is listed on a separate line in the configuration file along with its
value, in the form:

parameter = value

Both parameter and value are plain text strings that can be easily read and changed if
necessary.
194 Linux System and Networking Administration

The Postfix master program reads the parameter values in the main.cf file when Postfix is
first started, and again whenever a postfix reload command is issued.
Two examples of Postfix parameters are the myhostname and mydomain parameters. If
they are not specified in the main.cf configuration file, the myhostname parameter
assumes the results of a gethostname() command on the Linux system, whereas
mydomain assumes the domain part of the default myhostname parameter. Often a single
mail server will handle mail for an entire domain. This is an easy setting in the Postfix
configuration file:

myhostname = mailserver.smallorg.org
mydomain = smallorg.org

When Postfix starts, it will recognize the local mail server as mailserver.smallorg.org and
the local domain as smallorg.org and will ignore any system set values. If you need to
specify a smart host, do that with the relayhost parameter:

relayhost = myisp.com

You can also specify an IP address here, but it must be enclosed in square brackets.

Sending a Message with Mailx


The main tool you have available for sending e-mail messages from your shell scripts is
the Mailx program. Not only can you use it interactively to read and send messages, but
you can also use the command line parameters to specify how to send a message.
The format for the Mailx program’s command line for sending messages is:

mail [-eIinv] [-a header] [-b addr] [-c addr] [-s subj] to-addr

The mail command uses the command line parameters shown in Table below.
As you can see from Table below, you can pretty much create an entire e-mail message
just from the command line parameters. The only thing you need to add is the message
body. To do that, you need to redirect text to the mail command. Here’s a simple example
of how to create and send an e-mail message directly from the command line:

$ echo "This is a test message" | mail -s "Test message" rich


Linux System and Networking Administration 195

$ mail
Mail version 8.1.2 01/15/2001. Type ? for help.
"/var/mail/rich": 1 message 1 new
›N 1 rich@testbox Fri Feb 1 19:12 16/664 Test message
&
Message 1:
From rich@testbox Fri Feb 1 14:12:03 2008
From: rich ‹rich@testbox›
To: rich@localhost.localdomain
Subject: Test message

This is a test message

&

The Mailx program sent the text from the echo command as the message body. This
provides an easy way for you to send messages from your shell scripts. Here’s a quick
example:

$ cat factmail
#!/bin/bash
# mailing the answer to a factorial
MAIL=`which mail`
factorial=1
counter=1
read -p "Enter the number: " value
while [ $counter -le $value ]
do
factorial=$[$factorial * $counter]
counter=$[$counter + 1]
done
echo The factorial of $value is $factorial | mail -s "Factorial
answer" $USER
echo "The result has been mailed to you."

The first thing this script does is not assume that the Mailx program is located in the
standardlocation. It uses the which command to determine just where the mail program is.
After calculating the result of the factorial function, the shell script uses the mail command
to send the message to the user-defined $USER environment variable, which should be the
person executing the script.

$ ./factmail
Enter the number: 5
The result has been mailed to you.
$
All you need to do is check your mail to see if the answer arrived:
$ mail
196 Linux System and Networking Administration

Mail version 8.1.2 01/15/2001. Type ? for help.


"/var/mail/rich": 1 message 1 new
›N 1 rich@testbox Fri Feb 1 19:24 16/671 Factorial answer
&
Message 1:
From rich@testbox Fri Feb 1 14:24:33 2008
Date: Fri, 1 Feb 2008 19:24:33 -0500
From: rich ‹rich@testbox›
To: rich@localhost.localdomain
Subject: Factorial answer
The factorial of 5 is 120
&

It’s not always convenient to send just one line of text in the message body. Often you’ll
need to send an entire output as the e-mail message. In those situations, you can always
redirect text to a temporary file, then use the cat command and redirect the output to the
mail program.
Here’s an example of sending a larger amount of data in an e-mail message:

$ cat diskmail
#!/bin/bash
# sending the current disk statistics in an e-mail message
date=`date +%m/%d/%Y`
MAIL=`which mail`
TEMP=`mktemp tmp.XXXXXX`
df -k › $TEMP
cat $TEMP | $MAIL -s "Disk stats for $date" $1
rm -f $TEMP
$ ./diskmail rich
$ mail
Mail version 8.1.1 6/6/93. Type ? for help.
"/var/spool/mail/rich": 1 message 1 new
›N 1 rich@test2.dfas.mil Mon Feb 3 14:15 15/594 "Disk stats
for 02/03/"
&
Message 1:
From rich Mon Feb 3 14:15:57 2008
Delivered-To: rich@test2.dfas.mil
To: rich@test2.dfas.mil
Subject: Disk stats for 02/03/2008
Date: Mon, 3 Feb 2008 14:15:57 -0500 (EST)
From: rich@test2.dfas.mil (Rich)
Filesystem 1k-blocks Used Available Use% Mounted on
Linux System and Networking Administration 197

/dev/hda1 3526172 1464476 1882576 44% /


/dev/hda6 16002168 6570168 8619116 43% /home
&

The diskmail program gets the current date using the date command (along with some
special formatting), finds the location of the Mailx program, then creates a temporary file.
After all that, it uses the df command to display the current disk space statistics,
redirecting the output to the temporary file.
It then redirects the temporary file to the mail command, using the first command line
parameter for the destination address, and the current date in the Subject header.

The Mutt Program

The Mutt program is another popular e-mail client package for the Linux command line,
developed in 1995 by Michael Elkins. It has one feature that’s not available in the Mailx
program which makes it a good tool to have handy for your shell scripts.
The Mutt program has the ability to send files as attachments in your e-mail messages.
Instead of having to incorporate a long text file in the body of your e-mail message as we
did with Mailx, you can use the Mutt program and include the text file as a separate
attachment to the main message body. This feature is great for e-mailing long files, such
as log files.
This section walks through installing Mutt on your Linux system, and using it to attach files
to e-mail messages in your shell scripts.

Installing Mutt

The Mutt program is not a popular package in this day of fancy graphical e-mail clients
such as KMail or Evolution, so it’s a good bet that your Linux distribution doesn’t have it
installed by default. However, most Linux distributions include it in the normal distribution
files for installation using the standard software installation methods.
If your Linux distribution doesn’t include the Mutt package, or you just want to install the
latest version, here are the steps to do that:
1. Go to the Mutt package Web site at www.mutt.org. From here, select the
Downloading link to go to the download page.
2. On the download page, there are compiled binary executable packages for specific
Linux distributions, as well as a source code distribution package. If your Linux
distribution has a compiled binary executable package, download that and follow
the appropriate steps for installing software on your Linux distribution. Otherwise,
download the current source code distribution (there are two packages, a stable
release and a development release).
3. After downloading the source code package, extract it into a working directory
using the tar command:
4. tar -zxvf mutt-1.4.2.3.tar.gz
5. Change to the newly created directory:
cd mutt-1.4.2.3
6. Run the configure script to build the necessary files for compiling Mutt on your
system: ./configure
7. As the root user, run the make utility with the install option to create and install
Mutt:
make install
198 Linux System and Networking Administration

This will install the Mutt program on your Linux system for you to use from the command
line.

The Mutt command line

The mutt command provides parameters for you to use to control how Mutt operates.
Table below shows the command line parameters available to you.
With the myriad of command line parameters you can customize your e-mail message
directly from the command line, which is exactly what you’ll want to do in your shell
scripts. Much as with the Mailx program, there’s one thing that you can’t specify on the
command line with the Mutt program, and that’s the message body text. If you don’t
redirect text to the Mutt program, it’ll start in text-graphics mode with an editor window
for you to type the message body in.
This is not a good thing for the shell script, so you’ll always want to redirect some type of
text for the message body, even if you’re using the attachment option to specify a file to
attach. The next section demonstrates how to do this.
Using Mutt
Now you’re ready to start using the Mutt program in your shell scripts. To create the basic
mutt command in your shell script, you’ll want to include command line options that
specify the subject of the message, the attachment file, and all the recipients of the
message:
mutt -s Subject -a file recipients
The recipients list is a space-separated list of the e-mail addresses to send the message
to. If you want to attach more than one file, you’ll need to use multiple -a options, as each
option can only declare one filename. The file parameter must be an absolute pathname,
or a relative pathname relative to the current working directory from which you’re running
the mutt command.
There’s one other catch with the mutt command. If you don’t redirect text for the message
body, Mutt will automatically go to full-screen mode for you to enter the text in an editor
window. Most likely this is not what you want to do, so be sure to redirect some text for
the message body, even if it’s an empty file:
# echo "Here’s the log file" | mutt -s "Log file" -a
/var/log/messages rich
This command sends the system log file as an attachment to the e-mail address rich on
the local system. Note that you must also have the proper permissions to access the file
you want to attach.
Linux System and Networking Administration 199
200 Linux System and Networking Administration

Fig - Using KMail to view a message with an attachment


The preceding figure shows the received e-mail message in the KMail mail client.
Notice that the message includes the body text from the echo statement, along with a
separate icon for the attached file. You can save the attached file directly from the KMail
client.
Linux System and Networking Administration 201

CHAPTER 9: IMPLEMENTING NETWORK USING


LINUX OS

Getting Introduced to LAN Setup in Linux OS


Linux is increasingly popular in the computer networking/telecommunications industry.
Acquiring the Linux operating system is a relatively simple and inexpensive task since
virtually all of the source code can be downloaded from several different FTP or HTTP sites
on the Internet.
This section describes how to put together a Local Area Network (LAN) consisting of two or
more computers using the Red Hat Linux operating system. A LAN is a communications
network that interconnects a variety of devices and provides a means for exchanging
information among those devices. The size and scope of a LAN is usually small, covering a
single building or group of buildings. In a LAN, modems and phone lines are not required,
and the computers should be close enough to run a network cable between them.
For each computer that will participate in the LAN, you'll need a network interface card
(NIC) to which the network cable will be attached. You will also need to assign a unique
hostname and IP address to each computer in the LAN.

Installing the Hardware

Assuming that all LAN hardware is available, the next step is to install it. First turn off all
the computers that will participate in the LAN. Next, open the case on each computer and
install each NIC in the appropriate slot on the motherboard, being careful to follow the
manufacturer's instructions.
Find a convenient but safe location for the Ethernet hub, preferably a centralized location
in the same building or room along with the computers. Next, run the cable from the NIC
in each computer to the Ethernet hub ensuring all cables are out of the way of users who
will need physical access to each computer in the LAN. Moreover, make sure you follow all
instructions provided with the LAN hardware before starting up any of the computers that
will participate in the LAN.
If you are using a router to connect the LAN to the Internet or using a DHCP server, you
will need to do some configuration as required by the user's manual. Lastly, assuming all
computers are attached to the Ethernet hub via the NIC and a specific port on the hub,
you can now begin the software configuration process using the Red Hat operating system.

Configuring the LAN

How you configure the computers on the LAN will depend on whether the Red Hat OS was
installed before or after the LAN hardware. If you installed the LAN hardware before
installing Red Hat you will be prompted for network configuration during the Red Hat
installation process. However, if you installed the Red Hat OS after the LAN hardware, a
program called "Kudzu" will detect the newly installed Ethernet card and initiate the
configuration process automatically. Follow these steps when configuring each Ethernet
card using the "Kudzu" program:
1. During the bootup process look for a dialog box titled "Welcome to Kudzu." Press
Enter to begin the configuration process.
2. Next, you should see another dialog box that displays the brand name for the
installed Ethernet card. Press Enter again to continue.
202 Linux System and Networking Administration

3. After a brief delay you should see "Would You Like to Set up Networking".
4. Select the NO option using the Tab key and then press Enter. I will describe setting
up networking using a utility called LinuxConf later in this article.
At this point, the bootup process should continue normally and you will be required to log
on to the computer as the root user. You should have been given the opp ortunity to create
a root account during the initial installation of Red Hat.

Using LinuxConf to Configure Ethernet Card

You can use an application program called LinuxConf to configure or reconfigure the NIC of
each computer in the LAN. You can launch the LinuxConf utility by typing linuxconf at
the command prompt of any terminal window in the KDE or GNOME desktop environment.
Another way to start the LinuxConf utility is to click the Main menu button, select System,
then LinuxConf. When the LinuxConf application is displayed, follow the steps below to
configure the Ethernet card:
1. From the LinuxConf tree structure, select Config, Networking, Client Tasks, Basic
Host Information.
2. Type the fully qualified hostname that you assigned to this computer on the Host
name tab.
3. Next, click the Adaptor 1 tab, which displays your Ethernet card settings.
4. Verify that the Enabled button is selected to ensure that the Ethernet card will be
accessible.
5. Choose the Manual option if you will not be using a DHCP or BootP server on your
LAN and continue to step 6. Otherwise, if you will be using a DHCP or BootP
server, choose either DHCP or BootP accordingly and continue to step 12.
6. Enter this computer's hostname followed by a period and the domain name of the
LAN for the Primary name + domain option.
7. Enter the computer's hostname in addition to any aliases separated by a blank
space under the Aliases option.
8. Enter the IP address assigned to this computer next to IP Address (such as
192.168.1.1).
9. Type in 255.255.255.0 for the Netmask.
10. For net device, type eth0, which represents the first Ethernet card located inside
the computer.
11. The driver or Kernel Module option for the Ethernet card should automatically be
filled in upon exiting LinuxConf.
12. Click the Accept button to activate all changes.
13. Repeat steps 1-12 for each computer in the LAN, verifying that you've entered the
correct hostname and the corresponding IP address.

Configuring Nameserver Specification

Another important step in setting up LAN is to configure the Nameserver specification,


which is used by Linux to look up IP addresses when only the computer's hostname is
given. There are two methods that are used by Red Hat Linux to resolve hostnames into IP
addresses. One method is via Domain Name Services (DNS), and the other is by means of
a local file at /etc/hosts. Locate the hosts file by typing cd /etc to change to the /etc
directory. The /etc directory is where most system configuration files are found for each
computer. Next, follow the steps below to resolve hostnames into IP address using the
/etc/hosts file:
Linux System and Networking Administration 203

1. In the left column of LinuxConf, open the Nameserver specification (DNS)


category.
2. Left-click the DNS Usage option. (The button should be pushed in.)
3. Enter localdomain next to the Search Domain 1 category.
4. If you know the primary and secondary IP addresses for the nameserver, which
should be available for this Ethernet card, enter those in the IP of nameserver 1
and IP of nameserver 2 categories. Otherwise, you can leave those categories
blank.
5. Left-click the Accept button to activate all changes.

Configuring Hostname Search Path

The hostname search path is used by Red Hat Linux to search for IP addresses assigned to
hostnames. To configure the hostname search path so that the local host (/etc/hosts) file
is used to resolve local hostnames, and the ISP domain services to resolve Internet
domain services, follow these steps:
1. In the left column of LinuxConf, open the Routing and Gateways category.
2. Select the Host Name Search path option.
3. In the right column of LinuxConf, select the Multiple IPs for One Host option.
4. Select the hosts, dns option in the right portion of LinuxConf.
5. Left-click the Accept button to activate all changes.

Setting up /etc/hosts File

The Red Hat Linux OS needs some way to find IP addresses within the LAN based on the
each computer's hostname. I described earlier in the article that the Domain Name Service
(DNS) is one method of resolving hostnames into IP addresses. In a DNS configuration the
hostnames and IP addresses should already be listed in a pre-existing nameserver. Consult
your local ISP to obtain those IP addresses. On the other hand, if there is a centralized
nameserver, as with small LANs, a host file will need to be configured on each computer
that was assigned a hostname, IP address, and any aliases. This configuration process
involves editing a text file located at /etc/host. You will need to go to one of the computers
in the LAN and follow the below steps in order to create and configure the /etc/hosts file:
1. In the left column of LinuxConf, open the Misc category.
2. Open the Information about hosts category. You should see an entry for this
computer that includes the IP address, hostname, and any aliases.
3. Left-click the Add button once to add an entry for another host in the LAN.
4. Type the Primary + Domain Name for another host in the LAN in the dialog box
that appears (such as trinity.yourcompanyname.com).
5. Type one or more aliases for this computer next to the Alias option (such as tank).
6. Enter the IP address for the hostname that you've assigned for this computer next
to IP number.
7. Left-click the Accept button to activate all changes.
8. Repeat steps 1-7 for each computer in your LAN.
After you have done steps 1-7 for all computers, the /etc/hosts tab of LinuxConf should list
one entry for every computer in your LAN, in addition to the local host's loopback
interface. The local host name should appear as localhost. Finally, you can save all
changes and exit the LinuxConf application by following the steps below:
204 Linux System and Networking Administration

1. Left-click the Quit button in the /etc/host screen after all hostnames and IP
addresses have been entered.
2. To exit the LinuxConf application, left-click the Quit button at the bottom-left
corner.
3. Left-click the Activate the Changes button to activate all changes and exit
LinuxConf.

Repeating for Every Host

Now that you have configured one computer in you LAN, you will need to go back and
repeat all the above steps for each computer starting with the section "Configuring the
LAN". If you would prefer a less time-consuming procedure of configuring each computer,
you can modify the /etc/hosts file on each computer manually using a copy method.
You can copy the /etc/hosts file that you have just created to a floppy disk or CD-ROM (if
you have a writeable CD-ROM drive) and copy that file to the /etc directory of each
computer in your LAN. To copy the /etc/hosts file to a floppy disk, type the command cp
/etc/hosts /mnt/floppy at the command prompt. Do this on the computer where
you configured the initial /etc/hosts file using the LinuxConf utility.
Next, take the floppy to each computer in the LAN and type the command cp
/mnt/floppy hosts /etc/host in a terminal window. This will copy the hosts file
to the /etc directory on each host. If you are using a CD-ROM, replace the
/mnt/floppy/ in the above commands with //mnt/cdrom/ to copy files to and from
a writeable CD-ROM. The /etc/hosts file, as you probably noticed, is just a text file with a
list of hostnames and IP addresses separated into three columns. Lastly, make sure that
the local computer and its associated IP address are listed twice and all the other
computers in the LAN are listed only once.

Testing the LAN

To test the completely configured LAN, make sure that the computers are able to
communicate with each other after the bootup process. You can start by typing reboot at
the command prompt at a command terminal on each computer. This allows you to
monitor the testing information that scrolls down the screen as a standard procedure
during the Linux boot process. Look for the following information:

Setting hostname:
<hostname you assigned to this computer>
Bringing up Interface lo:
<OK> or <FAILED>
Bringing up interface eth0
<OK> or <FAILED>

The Setting hostname field should display the hostname that you assigned for this
computer. The lo and eth0 interfaces should display [OK] to indicate that both tests were
successful.
To determine whether each computer can communicate with every other computer in the
LAN, use the ping command. Open any terminal window on the current host and type the
command ping <IP address> or <hostname>, where <IP address> or
<hostname> is the IP address and/or the hostname that you assigned to this computer.
Note that you must type either the IP address or the hostname in order for the ping
command to work properly.
Ifyou have configured the DNS nameserver specification properly, the ping
<hostname> command should resolve the hostname into a corresponding IP address.
Linux System and Networking Administration 205

Otherwise, you will need to use the IP address that you should currently already have
listed for all computers in the LAN. The ping command will send messages across the LAN
to the designated IP address or computer. You should see several messages or packets
(consisting of bytes of information) if the computers are "talking" or communicating with
each other. These packets look similar to the following:

64 bytes from 192.168.1.x : icmp_seq=0 ttl=255 time=0.8ms


64 bytes from 192.168.1.x : icmp_seq=0 ttl=255 time=0.8ms
64 bytes from 192.168.1.x : icmp_seq=0 ttl=255 time=0.8ms

Note that the "192.168.1" represents the LAN that this particular host is a member of and
the x indicates the specific host number that you are attempting to ping (e.g. such as
Oracle) which jointly makes up the IP address. You can press the Ctrl+C to terminate the
test and you should see the following basic information about the entire ping test:

--- hostname.yourcompanyname.com ping statistics ---


4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.3/0.4/0.8 ms

Verify that the packet loss is 0%, which is an immediate indication that the test was
successful. However, there is a problem if the ping command results in the following
message:

From hostname.comanyname.com (192.168.1.1): Destination Host Unreachable

This is an immediate indication that the two computers are not communicating at all. If the
computers are not communicating, see the next section, "Troubleshooting the LAN".
Otherwise, when you can successfully ping all other computers in the LAN from one
designated computer, the overall basic communications functionality is indeed a success.
At this point, you can consider this LAN to be a fully functional network that you can install
and on which you can configure various network services as desired.

Troubleshooting the LAN

If you are unable to ping another computer in the LAN, here's how to get to the source of
the problem. First of all, it's a good idea to shut down every computer in the LAN using the
halt command. At the command prompt on each computer, type halt. The main reason
for shutting down all computers is to monitor feedback from the boot process when each
computer is started up again.
Check all cable connections between every computer, making sure that all RJ45 jacks are
connected properly. After verifying that all the cables are secured properly, start each
computer one at a time and look for the following response during the boot process:

Setting hostname: hostname.networkname [OK]

You can turn on the interactive mode by typing I at the LILO boot prompt during the initial
bootup process of Red Hat to get a closer view of the feedback. Ensure that the hostname
and network name that was assigned to this computer is spelled correctly. If this is not the
case, you will need to return to the Basic Host Information section of LinuxConf. In
interactive mode you will be prompted to start several services. Respond to each question
with Yes and pay close attention to results of various tests. If the Kudzu program detects
an Ethernet card, then this an indication that the card was not properly configured the first
time around. Proceed to let Kudzu configure the card. When you are prompted to configure
the network, choose "Yes" and type the correct IP address and other related information
for this particular computer.
Another important response to examine carefully is the following:

Bringing up interface eth0 [OK]

This line indicates whether the Ethernet card is working properly. If this test fails you
should check all network settings using LinuxConf to ensure that the card was configured
206 Linux System and Networking Administration

properly. If the network settings are correct, there is probably a defect in the Ethernet
card itself. In order to verify this, consult the manufacturer of the Ethernet card or a
computer technician to determine whether or not the card is defective. Repeat the
preceding troubleshooting procedures on each new Ethernet card installed.

Summarizing Network Setup in Linux

The process of setting up a LAN using Red Hat Linux is a relatively straightforward task --
even for users with little or no LAN background -- when the preceding steps are carefully
understood and performed. Moreover, there are vast resources available on the Web that
describe in more detail the topics covered in this article. A good start would be to feed
keywords (like LANs, configuring LANs, Linux network configuration, and TCP/IP) into your
favorite Web search engine. You will be amazed at the wealth of information that is
available on configuring LANs, building networks, Red Hat Linux network
installation/configuration, the TCP/IP protocol suite, and on and on. Good luck!

Illustrating Linux Networking Setup

Identifying Required Information

To enable networking, you must configure your network interface card or cards with an IP
address and netmask. The kernel must have support for your cards compiled in, either as
modular support or direct support. If you don't have kernel support read the sections
about the kernel and how to compile it. To set your cards up, do the following.
In my example my network is 192.168.1.0, IP=192.168.1.100,
broadcast=192.168.1.255, netmask=255.255.255.0, gateway-192.168.1.1,
nameserver=192.168.1.10.
1. Determine your machines IP address from your network administrator
2. Your network mask. This determines which portion of the IP address specifies the
subnetwork number and which portion specifies the host.

Class C (most networks) 255.255.255.0


Class B 255.255.0.0

3. Your network address which is your IP address bit wise anded with the network
mask.

IP: 192.168.1.100

Mask: 255.255.255.0

Net Addr:: 192.168.1.0

4. Your broadcast address. Used to broadcast packets to every machine on your


subnet.

IP: 192.168.1.100

Mask: 255.255.255.0

Net Addr: 192.168.1.255


Linux System and Networking Administration 207

5. Your gateway address. The address of the machine that is your gateway to the
outside world.

IP: 192.168.1.100 Gateway: 192.168.1.1

6. Your nameserver address. Translates host names into IP addresses. 192.168.1.10.

Identifying Configuration tools

There are many network configuration tools today. They are:


Netconf: A GUI interactive interface available on Redhat
linuxconf: A GUI interactive interface available on Redhat which includes netconf
configuration.
netconfig: A GUI step by step interface
ifconfig: A text based program to configure the network interface. Type "man ifconfig"
for info.
These programs will modify values in the following files:
/etc/sysconfig/network: Defines your network and some of its characteristics.
/etc/HOSTNAME: Shows the host name of this host. IF your name is "myhost" then
that is exactly the text this file will contain.
/etc/resolv.conf: Specifies the domain to be searched for host names to connect to,
the nameserver address, and the search order for the nameservers.
/etc/host.conf: Specifies the order nameservice looks to resolve names.
/etc/hosts: Shows addresses and names of local hosts.
/etc/networks: Provides a database of network names with network addresses similar
to the /etc/hosts file. This file is not required for operation.
/etc/sysconfig/network-scripts/ifcfg-eth*: There is a file for each network interface.
This file contains the IP address of the interface and many other setup variables.

Identifying Analysis Tools

The following are the analysis tools that you can use:
netstat: Displays information about the systems network connections, including port
connections, routing tables, and more. The command "netstar -r" will display the
routing table.
traceroute: This command can be used to determine the network route from your
computer to some other computer on your network or the internet. To use it you
can type "route IPaddress" of the computer you want to see the route to.
nslookup: Used to query DNS servers for information about hosts.
arp: This program lets the user read or modify their arp cache.
tcpdump: This program allows the user to see TCP traffic on their network.
dig(1): Send domain name query packets to name servers for debugging or testing.

Configuring Manually

You can use one of the above tools or configure the network the old fashioned way as
follows:
1. First to use networking on any permanent basis you should setup the file
/etc/sysconfig/network similar to the example shown below.
208 Linux System and Networking Administration

2. Assign an ip address with "ifconfig eth0 192.168.1.100 netmask 255.255.255.0


up".
3. Tell your machine that a hub is ready for information with the command "route add
-net 192.168.0.0 netmask 255.255.255.0 eth0"
4. To contact hosts outside your network if a machine with IP address 192.168.1.1 is
the gateway use the command "route add default gw 192.168.1.1 eth0"
5. If using a dialup connection use the command "route add default ppp0" The word
default says if the packet is not for a machine on your local network, send it to the
default device.
These settings are not permanent, but go away the next time you boot. They are normally
set up in the directory /etc/sysconfig/network-scripts. Add the network interface to the file
/etc/sysconfig/network-scripts/ifcfg-eth*. For example the file ifcfg-eth0 if for the first
ethernet interface, ifcfg-eth1 for the second, ifcfg-lo is for the local interface.
An example file is shown below:

DEVICE="eth0"
IPADDR="192.168.1.100"
NETMASK="255.255.0.0"
ONBOOT="yes"
BOOTPROTO="none"
IPXNETNUM_802_2=""
IPXPRIMARY_802_2="no"
IPXACTIVE_802_2="no"
IPXNETNUM_802_3=""
IPXPRIMARY_802_3="no"
IPXACTIVE_802_3="no"
IPXNETNUM_ETHERII=""
IPXPRIMARY_ETHERII="no"
IPXACTIVE_ETHERII="no"
IPXNETNUM_SNAP=""
IPXPRIMARY_SNAP="no"
IPXACTIVE_SNAP="no"

Unless you know what you're doing it is best to use a network configuration tool. I cannot
guarantee the accurateness of how to set these files up on your system.

Configuring an Interface for Multiple IP Addresses

If you want to configure your network card to act as more than one IP address, issue the
following command:

ifconfig dummy 192.168.1.102 netmask 255.255.255.0

This uses the dummy system interface capability supported in the kernel to setup another
virtual interface which operates at IP address 192.168.1.102. Substitute the IP address
that you want your virtual interface to be with an appropriate netmask for your network.
To disable this, issue the following command.

ifconfig dummy down


Linux System and Networking Administration 209

Another way to use multiple IP addresses on one ethernet card is to set up a new file in
your /etc/sysconfig/network-scripts directory. Copy your ifcfg-eth0 role to ifcfg-eth0:0.
Edit that file and rename the device to "eth0:0" and the IP address to the desired IP
address. You may also want to modify BROADCAST, NETWORK, or NETMASK. You can
continue adding IP addresses by using :1, :2, etc such as ifcfg-eth0:2.

To make it effective, you must reboot your system or issue the command
"/etc/rc.d/init.d/network restart" as root.

Configuring IP Address Dynamically

To get the IP address of a dynamically allocated network interface in a script file enter the
following command:

dynip=`/sbin/ifconfig | grep -A 4 ppp0 | awk '/inet/ { print $2 } ' | sed -e s/addr://`

Substitute the correct interface that you get your dynamic IP address in for ppp0 in the
example above. This script line gets your dynamic IP address for use in a masquerade
script. You can use the variable $dynip as in any other configuration. The next time you
make a new connection you will need to extract the dynip value again and re-run the
masquerade script.

Delving Deep into Networking Files

Below are listed some more in depth information about the networking files.
/etc/sysconfig/network
The /etc/inittab file contains the entry "si::sysinit:/etc/rc.d/rc.sysinit" which causes
the system at startup to run the rc.sysinit script. The rc.sysinit file expects to find
the file /etc/sysconfig/network if networking is to be enabled.
The network file looks like this:

NETWORKING=yes
FORWARD_IPV4=false
HOSTNAME=mymachine.mycompany.com
DOMAINNAME=mycompany.com
GATEWAY=192.168.1.1
GATEWAYDEV=eth0

Where GATEWAYDEV is the network interface card that is attached to the network
the gateway machine is on. The GATEWAY is the actual IP address of the gateway
machine.

/etc/hosts
Defines local hosts.

127.0.0.1 localhost localhost.localdomain


192.168.1.100 mymachine.mycompany.com mymachine

/etc/services
Internet network services list. It associates port numbers with names of services.
The file contains three fields which are name, port/protocol, and aliases with an
optional comment.
210 Linux System and Networking Administration

/etc/protocols
Describes DARPA internet protocols available from the TCP/IP subsystem. Maps
protocol ID numbers to protocol names. It includes protocol name, number, and
aliases. The protocol file on my system:

# /etc/protocols:
# $Id: protocols,v 1.1 1995/02/24 01:09:41 imurdock Exp $
#
# Internet (IP) protocols
#
# from: @(#)protocols 5.1 (Berkeley) 4/17/89
#
# Updated for NetBSD based on RFC 1340, Assigned Numbers (July 1992).

ip 0 IP # internet protocol, pseudo protocol number


icmp 1 ICMP # internet control message protocol
igmp 2 IGMP # Internet Group Management
ggp 3 GGP # gateway-gateway protocol
ipencap 4 IP-ENCAP # IP encapsulated in IP (officially ``IP'')
st 5 ST # ST datagram mode
tcp 6 TCP # transmission control protocol
egp 8 EGP # exterior gateway protocol
pup 12 PUP # PARC universal packet protocol
udp 17 UDP # user datagram protocol
hmp 20 HMP # host monitoring protocol
xns-idp 22 XNS-IDP # Xerox NS IDP
rdp 27 RDP # "reliable datagram" protocol
iso-tp4 29 ISO-TP4 # ISO Transport Protocol class 4
xtp 36 XTP # Xpress Tranfer Protocol
ddp 37 DDP # Datagram Delivery Protocol
idpr-cmtp 39 IDPR-CMTP # IDPR Control Message Transport
rspf 73 RSPF #Radio Shortest Path First.
vmtp 81 VMTP # Versatile Message Transport
ospf 89 OSPFIGP # Open Shortest Path First IGP
ipip 94 IPIP # Yet Another IP encapsulation
encap 98 ENCAP # Yet Another IP encapsulation

/etc/named.conf
Used for domain name service to configure named. Other files used are dependent
on this file.
Linux System and Networking Administration 211

/etc/resolv.conf
Specifies the domain to be searched for host names to connect to, the nameserver
address, and the search order for the nameservers.

domain mycompany.com
search mycompany.com mynet.net
nameserver 192.168.1.100
nameserver 192.168.199.1
nameserver 192.168.1.10

The third line specifies that DNS should be tried on the machine first then use the
normal nameserver on the fifth line. The fourth line specifies that the machine is
running nameservices on another network which is using interface 192.168.199.1.
This assumes the nameserver is set up on the machine.

/etc/host.conf
Specifies the order nameservice looks to resolve names. An example file:

order hosts, bind


multi on
nospoof on

The order specifies that when resolving names to first look in the /etc/host file,
then use BIND8 (DNS) to resolve the name. The line "multi on" specifies that all
valid addresses for a host found in the hosts file should be returned.
The files in /etc/sysconfig/network-scripts control your network interfaces. The network
interface file is described above in the section "Manual Configuration". If you want or need
more in depth knowledge about how these files are used, you will need to read the
document "How Linux Works CTDP Guide" or "The CTDP Linux Startup Manual". Otherwise
you will need to analyze the system startup scripts which is no small task.

Understanding Older X Windows Configuration

In X Windows a working configuration is set up as follows:


NAMES:
hostname: mymachine.mycompany.com
Domain: mycompany.com
Nameservers: 192.168.1.10
HOSTS:
IP - 192.168.1.100
Name - mymachine.mycompany.com
INTERFACES:
Interface - eth0
IP- 192.168.1.100
proto - none
atboot - yes
Netmask: 255.255.255.0
Network: 192.168.1.0
212 Linux System and Networking Administration

Broadcast: 192.168.1.255
ROUTING:
Default gateway: 192.168.1.1
Default gateway device: eth0
Interface - 192.168.1.100
Network Address - 192.168.1.0
Network gateway 192.168.1.1
Netmask - 255.255.255.0

Overview of Routing

Routing table information is used to route incoming and outgoing network diagrams to
other machines. On most simple configurations, there are three routes. One for sending
packets to your own machine, one for sending packets to other machines on your network
and one for sending packets to other machines outside your network through the gateway.
Two programs (ifconfig and route) are used to configure these parameters. They are
described in more detail in later chapters.
Linux System and Networking Administration 213

CHAPTER 10: SECURING LINUX


IMPLEMENTATION

Introduction to Linux Security


With the growth of the Internet, computer and network security has become more
important than ever. Assaults on your Red Hat Linux system can come in many forms,
such as denial-of-service attacks, break-in attempts, or hijacking your machine as a spam
relay, to name a few.
In many cases, good practices for setting and protecting passwords, monitoring log files
and creating good firewalls will keep out many would-be intruders. Sometimes, more
proactive approaches are needed to respond to break-ins. This chapter will familiarize you,
as a Red Hat Linux administrator, with the dangers that exist and the tools necessary to
protect your system.

Hacker versus Cracker


In short, a hacker is someone who programs creatively and usually for the pure enjoyment
of it (most programmers who work on Linux are hackers in this sense). The correct term
for someone who breaks into computer systems is a cracker.
There are many types of crackers, ranging from professional computer criminals to the
hobbyist types that break into computers for the thrill. The growth of the cracker problem
has kept pace with the growth of the Internet. A new, younger generation of cracker is
emerging. These teenage pseudo-crackers do not have all the knowledge and skill of their
true cracker counterparts, but they have access to a growing number of cracker tools that
automate the breaking of a system's security.
By using programs and scripts created by more advanced crackers, youngsters can often
break into systems without really knowing the details of how it is done. Because they are
usually young and mostly dependent on tools provided by others, they are sometimes
referred to as "scriptkiddies." Make no mistake, if your system is not properly secured,
scriptkiddies can do just as much damage as any other cracker.
Whatever you call them, crackers pose a serious risk to anyone connecting a computer to
the Internet. Their reasons for breaking into systems are varied; some hope to steal
financial information, others wish to gain bragging rights among their peers.
Often, a system is broken into solely for use as a jumping-off point to launch further
attacks on other systems. In some cases, the damage may be as little as an altered Web
page, the Internet equivalent of graffiti. In other cases, the cracker may wipe out your
entire hard drive to cover his or her tracks. Fortunately, there are ways to protect yourself.

Understanding Attack Techniques


Attacks on computing systems take on different forms, depending on the goal and
resources of the attacker. Some attackers desire to be disruptive, while others desire to
infiltrate your machines and utilize the resources for their own nefarious purposes. Still
others are targeting your data for financial gain or blackmail. Here are three major
categories of attacks:
214 Linux System and Networking Administration

 Denial of Service (DOS) — The easiest attacks to perpetrate are Denial of


Service attacks. The primary purpose of these attacks is to disrupt the activities of
a remote site by overloading it with irrelevant data. DOS attacks can be as simple
as sending thousands of page requests per second at a Web site. These types of
attacks are easy to perpetrate and easy to protect against. Once you have a
handle on where the attack is coming from, a simple phone call to the
perpetrator's ISP will get the problem solved.

 Distributed Denial of Service (DDOS) — More advanced DOS attacks are called
Distributed Denial of Service attacks. DDOS attacks are much harder to perpetrate
and nearly impossible to stop. In this form of attack, an attacker takes control of
hundreds or even thousands of weakly secured Internet connected computers. The
attacker then directs them in unison to send a stream of irrelevant data to a single
Internet host. The result is that the power of one attacker is magnified thousands
of times. Instead of an attack coming from one direction, as is the case in a normal
DOS, it comes from thousands of directions at once. The best defense against
DDOS attack is to contact your ISP to see if it can filter traffic at its border routers.
Many people use the excuse, "I have nothing on my machine anyone would want" to avoid
having to consider security. The problem with this argument is that attackers have a lot of
reasons to use your machine. The attacker can turn your machine into an agent for later
use in a DDOS attack. More than once, authorities have shown up at the door of a
dumbfounded computer user asking questions about threats originating from their
computer. By ignoring security, the owners have opened themselves up to a great deal of
liability.

 Intrusion attacks — To remotely use the resources of a target machine,


attackers must first look for an opening to exploit. In the absence of inside
information such as passwords or encryption keys, they must scan the target
machine to see what services are offered. Perhaps one of the services is weakly
secured and the attacker can use some known exploit to finagle his way in.
A tool called nmap is generally considered the best way to scan a host for services (note
that nmap is a tool that can be used for good and bad). Once the attacker has a list of the
available services running on his target, he needs to find a way to trick one of those
services into letting him have privileged access to the system. Usually, this is done with a
program called an exploit.
While DOS attacks are disruptive, intrusion type attacks are the most damaging. The
reasons are varied, but the result is always the same. An uninvited guest is now taking up
residence on your machine and is using it in a way you have no control over.

Protecting Against Denial-of-Service Attacks

As explained earlier, a denial-of-service attack attempts to crash your computer or at least


degrade its performance to an unusable level. There are a variety of denial-of-service
exploits. Most try to overload some system resource, such as your available disk space or
your Internet connection. Some common attacks and defenses are discussed in the
following sections.

Mailbombing

Mailbombing is the practice of sending so much e-mail to a particular user or system that
the computer's hard drive becomes full. There are several ways to protect yourself from
mailbombing. You can use the Procmail e-mail-filtering tool or configure your sendmail
daemon.

Blocking mail with Procmail

The Procmail e-mail-filtering tool is installed by default with Red Hat Linux and is tightly
integrated with the sendmail e-mail daemon; thus, it can be used to selectively block or
Linux System and Networking Administration 215

filter out specific types of e-mail. You can learn more about Procmail at the Procmail Web
site www.procmail.org.
To enable Procmail for your user account, create a .procmailrc file in your home directory.
The file should be mode 0600 (readable by you but nobody else). Type the following,
replacing evilmailer with the actual e-mail address that is mailbombing you.

# Delete mail from evilmailer


:0
* ^From.*evilmailer
/dev/null

The Procmail recipe looks for the From line at the start of each e-mail to see if it includes
the string evilmailer. If it does, the message is sent to /dev/null (effectively throwing it
away).

Blocking mail with sendmail

The Procmail e-mail tool works quite well when only one user is being mailbombed. If,
however, the mailbombing affects many users, you should probably configure your
sendmail daemon to block all e-mail from the mailbomber. Do this by adding the
mailbomber's e-mail address or system name to the access file located in the /etc/mail
directory.
Each line of the access file contains an e-mail address, host name, domain, or IP address
followed by a tab and then a keyword specifying what action to take when that entity
sends you a message. Valid keywords are OK, RELAY, REJECT, DISCARD, and ERROR.
Using the REJECT keyword will cause a sender's e-mail to be bounced back with an error
message. The keyword DISCARD will cause the message to be silently dropped without
sending an error back. You can even return a custom error message by using the ERROR
keyword.
Thus, an example /etc/mail/access file may look similar to this:

# Check the /usr/share/doc/sendmail/README.cf file for a description


# of the format of this file. (search for access_db in that file)
# The /usr/share/doc/sendmail/README.cf is part of the sendmail-doc
# package.
#
# by default we allow relaying from localhost...
localhost.localdomain RELAY
localhost RELAY
127.0.0.1 RELAY
#
# Senders we want to Block
#
evilmailer@yahoo.com REJECT
stimpy.glaci.com REJECT
cyberpromo.com DISCARD
199.170.176.99 ERROR:"550 Die Spammer Scum!"
199.170.177 ERROR:"550 Email Refused"
216 Linux System and Networking Administration

As with most Linux configuration files, lines that begin with a # pound sign are comments.
Our list of blocked spammers is at the end of this example file. Note that the address to
block can be a complete e-mail address, a full host name, a domain only, an IP address, or
a subnet.
To block a particular e-mail address or host from mailbombing you, log in to your system
as root, edit the /etc/mail/access file, and add a line to DISCARD mail from the offending
sender.
After saving the file and exiting the editor, you must convert the access file into a hash
indexed database called access.db. The database is updated automatically the next time
sendmail starts. Or you can convert the database immediately, as follows:
# cd /etc/mail
# make
Sendmail should now discard e-mail from the addresses you added.

Spam relaying

Another way in which your e-mail services can be abused is by having your system used as
a Spam Relay. Spam refers to the unsolicited junk e-mail that has become a common
occurrence on the Internet. Spammers often deliver their annoying messages from a
normal dial-up Internet account. They need some kind of high-capacity e-mail server to
accept and buffer the payload of messages. They deliver the spam to the server all in one
huge batch and then log off, letting the server do the work of delivering the messages to
the many victims.
Naturally, no self-respecting Internet Service Provider will cooperate with this action, so
spammers resort to hijacking servers at another ISP to do the dirty work. Having your
mailserver hijacked to act as a spam relay can have a devastating effect on your system
and your reputation. Fortunately, mail relaying is deactivated by default on Red Hat Linux
installations. This is one security issue that you will not have to attend to.
You can allow specific hosts or domains to relay mail through your system by adding those
senders to your /etc/mail/access file with keyword RELAY. By default, relaying is only
allowed from the local host.

Tip One package you might consider using to filter out spam on your mail server is
Spamassassin. Spamassassin examines the text of incoming mail messages and
attempts to filter out messages that are determined to be spam.

Smurf amplification attack

Smurfing refers to a particular type of denial-of-service attack aimed at flooding your


Internet connection. It can be a difficult attack to defend against because it is not easy to
trace the attack to the attacker. Here is how smurfing works.
The attack makes use of the ICMP protocol, a service intended for checking the speed and
availability of network connections. Using the ping command, you can send a network
packet from your computer to another computer on the Internet. The remote computer will
recognize the packet as an ICMP request and echo a reply packet to your computer. Your
computer can then print a message revealing that the remote system is up and telling you
how long it took to reply to the ping.
A smurfing attack uses a malformed ICMP request to bury your computer in network
traffic. The attacker does this by bouncing a ping request off an unwitting third party in
such a way that the reply is duplicated dozens or even hundreds of times. An organization
with a fast Internet connection and a large number of computers is used as the relay. The
destination address of the ping is set to an entire subnet instead of a single host. The
return address is forged to be your machine's address instead of the actual sender. When
the ICMP packet arrives at the unwitting relay's network, every host on that subnet replies
to the ping! Furthermore, they reply to your computer instead of to the actual sender. If
Linux System and Networking Administration 217

the relay's network has hundreds of computers, your Internet connection can be quickly
flooded.
The best fix is to contact the organization being used as a relay and inform them of the
abuse. Usually, they need only to reconfigure their Internet router to stop any future
attacks. If the organization is uncooperative, you can minimize the effect of the attack by
blocking the ICMP protocol on your router. This will at least keep the traffic off your
internal network. If you can convince your ISP to block ICMP packets aimed at your
network, it will help even more.

Protecting Against Distributed DOS Attacks

DDOS attacks are much harder to initiate and nearly impossible to stop. A DDOS attack
begins with the penetration of hundreds or even thousands of weakly secured machines.
These machines can then be directed to attack a single host based on the whims of the
attacker.
With the advent of DSL and cable modem, millions of people are enjoying Internet access
with virtually no speed restrictions. In their rush to get online, many of those people
neglect even the most basic security. Since the vast majority of these people run Microsoft
operating systems, they tend to get hit with worms and viruses rather quickly. Once the
machine has been infiltrated, quite often the worm or virus installs a program on the
victim's machine that instructs it to quietly call home and announce that it is now ready to
do the master's bidding.
At the whim of the master, the infected machines can now be used to focus a concentrated
stream of garbage data at a selected host. In concert with thousands of other infected
machines, a scriptkiddie now has the power take down nearly any site on the Internet.
Detecting a DDOS is similar to detecting a DOS attack. One or more of the following signs
are likely to be present:
 Sustained saturated data link
 No reduction in link saturation during off-peak hours
 Hundreds or even thousands of simultaneous network connections
 Extremely slow system performance
To determine if your data link is saturated, the act of pinging an outside host can tell much
of the story. Much higher than usual latency is a dead giveaway. Normal ping latency (that
is, the time it takes for a ping response to come back from a remote host) looks like the
following:
# ping www.example.com
PING www.example.com (192.0.34.166) from 10.0.0.11: 56(84) bytes of data
64 bytes from 192.0.34.166: icmp_seq=1 ttl=49 time=40.1 ms
64 bytes from 192.0.34.166: icmp_seq=2 ttl=49 time=42.5 ms
64 bytes from 192.0.34.166: icmp_seq=3 ttl=49 time=39.5 ms
64 bytes from 192.0.34.166: icmp_seq=4 ttl=49 time=38.4 ms
64 bytes from 192.0.34.166: icmp_seq=5 ttl=49 time=39.0 ms

--- www.example.com ping statistics ---


5 packets transmitted, 5 received, 0% loss, time 4035ms
rtt min/avg/max/mdev = 38.472/39.971/42.584/1.432 ms
In the preceding example, the average time for a ping packet to make the round trip was
about 39 thousandths of a second.
A ping to a nearly saturated link will look like the following:
218 Linux System and Networking Administration

# ping www.example.com
PING www.example.com (192.0.34.166): from 10.0.0.11: 56(84)bytes of data
64 bytes from 192.0.34.166: icmp_seq=1 ttl=62 time=1252 ms
64 bytes from 192.0.34.166: icmp_seq=2 ttl=62 time=1218 ms
64 bytes from 192.0.34.166: icmp_seq=3 ttl=62 time=1290 ms
64 bytes from 192.0.34.166: icmp_seq=4 ttl=62 time=1288 ms
64 bytes from 192.0.34.166: icmp_seq=5 ttl=62 time=1241 ms

--- www.example.com ping statistics ---


6 packets transmitted, 5 received, 0% loss, time 5032ms
rtt min/avg/max/mdev = 1218.059/1258.384/1290.861/28.000 ms
In this example, a ping packet took, on average, 1.3 seconds to make the round trip. From
the first example to the second example, latency increased by a factor of 31! A data link
that goes from working normally to slowing down by a factor of 31 is a clear sign that link
utilization should be investigated.
For a more accurate measure of data throughput, a tool such as ttcp can be used. To test
your connection with ttcp you must have installed the ttcp RPM package on machines
inside and outside of your network. (The ttcp package comes on CD #3 included with this
book.) If you are not sure if the package is installed, simply type ttcp at a command
prompt. You should see something like the following:
# ttcp
Usage: ttcp -t [-options] host [ < in ]
ttcp -r [-options > out]
Common options:
-l ## length of bufs read from or written to network (default 8192)
-u use UDP instead of TCP
-p ## port number to send to or listen at (default 5001)
-s -t: source a pattern to network
-r: sink (discard) all data from network
-A align the start of buffers to this modulus (default 16384)
-O start buffers at this offset from the modulus (default 0)
-v verbose: print more statistics
-d set SO_DEBUG socket option
-b ## set socket buffer size (if supported)
-f X format for rate: k,K = kilo{bit,byte}; m,M = mega; g,G = giga
Options specific to -t:
-n## number of source bufs written to network (default 2048)
-D don't buffer TCP writes (sets TCP_NODELAY socket option)
Options specific to -r:
-B for -s, only output full blocks as specified by -l (for TAR)
-T "touch": access each byte as it's read
The first step is to start up a receiver process on the server machine:
Linux System and Networking Administration 219

# ttcp -rs
ttcp-r: buflen=8192, nbuf=2048, align=16384/0, port=5001 tcp
ttcp-r: socket
The –r flag denotes that the server machine will be the receiver. The –s flag, in
conjunction with the –r flag, tells ttcp that we want to ignore any received data.
The next step is to have someone outside of your data link, with a network link close to
the same speed as yours, set up a ttcp sending process:
# ttcp -ts server.example.com
ttcp-t: buflen=8192, nbuf=2048, align=16384/0, port=5001 tcp ->
server.example.com
ttcp-t: socket
ttcp-t: connect
Let the process run for a few minutes and then press Ctrl+C on the transmitting side to
stop the testing. The receiving side will then take a moment to calculate and present the
results:
# ttcp -rs
ttcp-r: buflen=8192, nbuf=2048, align=16384/0, port=5001 tcp
ttcp-r: socket
ttcp-r: accept from 64.223.17.21
ttcp-r: 2102496 bytes in 70.02 real seconds = 29.32 KB/sec +++
ttcp-r: 1226 I/O calls, msec/call = 58.49, calls/sec = 17.51
ttcp-r: 0.0user 0.0sys 1:10real 0% 0i+0d 0maxrss 0+2pf 0+0csw
In this example, the average bandwidth between the two hosts was 29.32 kilobytes per
second. On a link suffering from a DDOS, this number would be a mere fraction of the
actual bandwidth the data link is rated for.
If the data link is indeed saturated, the next step is to determine where the connections
are coming from. A very effective way of doing this is with the netstat command, which is
included as part of the base Red Hat Linux install. Type the following to see connection
information:
# netstat –tupn
The following table describes each of the netstat parameters used here.

Parameter Description

-t, --tcp Show TCP socket connections.

-u, --udp Show UDP socket connections.

-p, --program Show the PID and name of the program to which each
socket belongs.

-n, --numeric Show numerical address instead of trying to determine


symbolic host, port, or user names.

The following is an example of what the output might look like:


Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
220 Linux System and Networking Administration

tcp 0 0 65.213.7.96:22 13.29.132.19:12545 ESTABLISHED 32376/sshd


tcp 0 224 65.213.7.96:22 13.29.210.13:29250 ESTABLISHED 13858/sshd
tcp 0 0 65.213.7.96:6667 13.29.194.190:33452 ESTABLISHED 1870/ircd
tcp 0 0 65.213.7.96:6667 216.39.144.152:42709 ESTABLISHED 1870/ircd
tcp 0 0 65.213.7.96:42352 67.113.1.99:53 TIME_WAIT -
tcp 0 0 65.213.7.96:42354 83.152.6.9:113 TIME_WAIT -
tcp 0 0 65.213.7.96:42351 83.152.6.9:113 TIME_WAIT -
tcp 0 0 127.0.0.1:42355 127.0.0.1:783 TIME_WAIT -
tcp 0 0 127.0.0.1:783 127.0.0.1:42353 TIME_WAIT -
tcp 0 0 65.213.7.96:42348 19.15.11.1:25 TIME_WAIT -

The output is organized into columns defined as follows:


 Proto — Protocol used by the socket.
 Recv-Q — The number of bytes not yet copied by the user program attached to
this socket.
 Send-Q — The number of bytes not acknowledged by the host.

 Local Address — Address and port number of the local end of the socket.
 Foreign Address — Address and port number of the remote end of the socket.

 State — Current state of the socket. The following table provides a list of socket
states.

 PID/Program name — Process ID and program name of the process that owns
the socket.

State Description

ESTABLISHED Socket has an established connection.

SYN_SENT Socket actively trying to establish a connection.

SYN_RECV Connection request received from the network.

FIN_WAIT1 Socket closed and shutting down.

FIN_WAIT2 Socket is waiting for remote end to shut down.

TIME_WAIT Socket is waiting after closing to handle packets still in the


network.

CLOSED Socket is not being used.

CLOSE_WAIT The remote end has shutdown, waiting for the socket to close.

LAST_ACK The remote end has shut down, and the socket is closed, waiting
for acknowledgement.

LISTEN Socket is waiting for an incoming connection.


Linux System and Networking Administration 221

State Description

CLOSING Both sides of the connection are shut down but not all of our data
has been sent.

UNKNOWN The state of the socket is unknown.

During a DOS attack, the foreign address is usually the same for each connection. In this
case, it is a simple matter of typing the foreign IP address into the search form over at
http://www.arin.net/whois/ so you can alert your ISP.
During a DDOS, the foreign address will likely be different for each connection. In this
case, it is impossible to track down all of the offenders, as there will likely be thousands of
them. The best way to defend yourself is to contact your Internet provider and see if it can
filter the traffic at its border routers.

Protecting Against Intrusion Attacks


Crackers have a wide variety of tools and techniques to assist them in breaking into your
computer. Intrusion attacks focus on exploiting weaknesses in your security, so the
crackers can take more control of your system (and potentially do more damage) than
they could from the outside.
Fortunately, there are many tools and techniques for combating intrusion attacks. This
section discusses the most common break-in methods and the tools available to protect
your system. Though the examples shown are specific to Red Hat Linux systems, the tools
and techniques are generally applicable to any other Linux or UNIX-like operating system.

Cross-Reference The tripwire package, which was recently dropped from the Red Hat
Linux distribution, was a good tool for detecting whether intrusion
attacks have taken place. We removed the description of tripwire
from this edition.

Evaluating access to network services


Red Hat Linux and its UNIX kin provide many network services, and with them many
avenues for cracker attacks. You should know these services and how to limit access to
them.
So what do I mean by a network service? Basically, I am referring to any task that the
computer performs that requires it to send and receive information over the network using
some predefined set of rules. Routing e-mail is a network service. So is serving Web
pages. Your Linux box has the potential to provide thousands of services. Many of them
are listed in the /etc/services file. Look at a snippet of that file:
# /etc/services:
# service-name port/protocol [aliases ...] [# comment]
chargen 19/tcp ttytst source
chargen 19/udp ttytst source
ftp-data 20/tcp
ftp-data 20/udp
# 21 is registered to ftp, but also used by fsp
ftp 21/tcp
ftp 21/udp fsp fspd
ssh 22/tcp # SSH Remote Login Protocol
ssh 22/udp # SSH Remote Login Protocol
222 Linux System and Networking Administration

telnet 23/tcp
telnet 23/udp
# 24 - private mail system
smtp 25/tcp mail
After comment lines, you will notice three columns of information. The left column contains
the name of each service. The middle column defines the port number and protocol type
used for that service. The rightmost field contains an optional alias or list of aliases for the
service.
As an example, let us examine the last entry in the above file snippet. It describes the
SMTP (Simple Mail Transfer Protocol) service, which is the service used for delivering e-
mail over the Internet. The middle column contains the text 25/tcp, which tells us that the
SMTP protocol uses port 25 and uses the Transmission Control Protocol (TCP) as its
protocol type.
So, what exactly is a port number? It is a unique number that has been set aside for a
particular network service. It allows network connections to be properly routed to the
software that handles that service. For example, when an e-mail message is delivered
from some other computer to your Linux box, the remote system must first establish a
network connection with your system. Your computer receives the connection request,
examines it, sees it labeled for port 25, and thus knows that the connection should be
handed to the program that handles e-mail (which happens to be sendmail).

Note A program that stays quietly in the background handling service requests (such as
sendmail) is called a daemon. Usually, daemons are started automatically when your
system boots up, and they keep running until your system is shut down. Daemons
may also be started on an as-needed basis by xinetd, a special daemon that listens
on a large number of port numbers, then launches the requested process.

I mentioned that SMTP uses the TCP protocol. Some services use UDP, the User Datagram
Protocol. All you really need to know about TCP and UDP (for the purpose of this security
discussion) is that they provide different ways of packaging the information sent over a
network connection. A TCP connection provides error detection and retransmission of lost
data. UDP doesn't check to ensure that the data arrived complete and intact; it is meant as
a fast way to send non-critical information.

Disabling network services

Although there are hundreds of services (listed in /etc/services) that potentially could be
available and subject to attack on your Red Hat Linux system, in reality only a few dozen
services are installed and only a handful of those are on by default. Most network services
are started by either the xinetd process or by a start-up script in the /etc/init.d directory.
xinetd is a daemon that listens on a great number of network port numbers. When a
connection is made to a particular port number, xinetd automat ically starts the appropriate
program for that service and hands the connection to it.
The configuration file /etc/xinetd.conf is used to provide default settings for the xinetd
server. The directory /etc/xinetd.d contains files telling xinetd what ports to listen on and
what programs to start. Each file contains configuration information for a single service,
and the file is usually named after the service it configures. For example, to enable the
Post Office Protocol (POP) service, edit the ipop3 file and look for a section similar to the
following:
service pop3
{
socket_type = stream
wait = no
user = root
Linux System and Networking Administration 223

server = /usr/sbin/ipop3d
log_on_success += HOST DURATION
log_on_failure += HOST
disable = yes
}
Note that the first line of this example identifies the service as pop3. This exactly matches
the service name listed in the /etc/services file. You can see that the service is off by
default (disable = yes). To enable POP services, change the line to read disable = no
instead. Thus, the preceding example with POP services enabled would look like this:
service pop3
{
socket_type = stream
wait = no
user = root
server = /usr/sbin/ipop3d
log_on_success += HOST DURATION
log_on_failure += HOST
disable = no
}
Because most services are disabled by default, your computer is only as insecure as you
make it. You can double-check that insecure services, such as rlogin and rsh, are also
disabled by making sure that disabled = yes is set in the /etc/xinetd.d/rlogin and rsh files.

Tip:
You can make the remote login service active but disable the use of the /etc/host.equiv
and .rhosts files, requiring rlogin to always prompt for a password. Rather than disabling
the service, locate the server line in the rsh file (server = /usr/sbin/in.rshd) and add a
space followed by -L at the end.

You now need to send a signal to the xinetd process to tell it to reload its configuration file.
The quickest way to do that is to restart the xinetd service. As the root user, type the
following from a shell:
# service xinetd restart
Stopping xinetd: [ OK ]
Starting xinetd: [ OK ]
That's it — you have enabled the ipop3 service. Provided that you have properly
configured your mail server, clients should now be able to get their mail from your
computer.

Using TCP wrappers

Completely disabling an unused service is fine, but what about the services that you really
need? How can you selectively grant and deny access to these services? In previous
versions of Red Hat Linux, the TCP wrapper daemon (tcpd) was used to facilitate this sort
of selective access. In the current version of Red Hat Linux, TCP wrapper support has been
integrated into xinetd. xinetd will look at the files /etc/hosts.allow and /etc/hosts.deny to
determine when a particular connection should be granted or refused. It scans through the
hosts.allow and hosts.deny files and stops when it finds an entry that matches the IP
address of the connecting machine. These checks are made when connection attempts
occur:
224 Linux System and Networking Administration

 If the address is listed in the hosts.allow file, the connection is allowed and
hosts.deny is not checked.
 Otherwise, if the address is in hosts.deny, the connection is denied.
 Finally, if the address is in neither file, the connection is allowed.
It is not necessary (or even possible) to list every single address that may connect to your
computer. The hosts.allow and hosts.deny files enable you to specify entire subnets and
groups of addresses. You can even use the keyword ALL to specify all possible addresses.
You can also restrict specific entries in these files so they only apply to specific network
services. Let's look at an example of a typical pair of hosts.allow and hosts.deny files.

#
# hosts.allow This file describes the names of the hosts are
# allowed to use the local INET services, as decided
# by the '/usr/sbin/tcpd' server.
#

imapd, ipop3d: 199.170.177.


in.telnetd: 199.170.177., .glaci.com
ftpd: ALL
#
# hosts.deny This file describes the names of the hosts which are
# *not* allowed to use the local INET services, as
# decided by the '/usr/sbin/tcpd' server.
#

ALL: ALL
The preceding example is a rather restrictive configuration. It allows connections to the
imap, ipop3d, and telnet services from certain hosts, but then denies all other connections.
Let's examine the files in detail.
As usual, lines beginning with a # character are comments and are ignored by xinetd when
it parses the file. Each noncomment line consists of a comma-separated list of daemons
followed by a colon (:) character and then a comma-separated list of client addresses to
check. In this context, a client is any computer that attempts to access a network service
on your system.
A client entry can be a numeric IP address (such as 199.170.177.25) or a host name (such
as dexter.glaci.com) but is more often a wildcard variation that specifies an entire range of
addresses. A client entry can take four different forms. The online manual page for the
hosts.allow file describes them as follows:
 A string that begins with a dot (.) character. A host name i s matched if the last
components of its name match the specified pattern. For example, the pattern
.tue.nl matches the host name wzv.win.tue.nl.
 A string that ends with a dot (.) character. A host address is matched if its first
numeric fields match the given string. For example, the pattern 131.155.
matches the address of (almost) every host on the Eindhoven University
network (131.155.x.x).
 A string that begins with an at (@) sign is treated as an NIS (formerly YP)
netgroup name. A host name is matched if it is a host member of the specified
netgroup. Netgroup matches are not supported for daemon process names or
for client user names.
Linux System and Networking Administration 225

 An expression of the form n.n.n.n/m.m.m.m is interpreted as a net/mask pair.


A host address is matched if net is equal to the bitwise AND of the address and
the mask. For example, the net/mask pattern 131.155.72.0/255.255.254.0
matches every address in the range 131.155.72.0 through 131.155.73.255.
The example host.allow contains the first two types of client specification. The entry
199.170.177. will match any IP address that begins with that string, such as
199.170.177.25. The client entry .glaci.com will match host names such as
dexter.glaci.com or scooby.glaci.com.
Let's examine what happens when a host named daffy.glaci.com (with IP address
199.170.179.18) connects to your Red Hat Linux box using the Telnet protocol:
1. xinetd receives the connection request.
2. xinetd begins comparing the address and name of daffy.glaci.com to the rules
listed in /etc/hosts.allow. It starts at the top of the file and works its way down the
file until finding a match. Both the daemon (the program handling the network
service on your Red Hat Linux box) and the connecting client's IP address or name
must match the information in the hosts.allow file. In this case, the second rule
that is encountered matches the request:
in.telnetd: 199.170.177., .glaci.com
3. Daffy is not in the 199.170.177 subnet, but it is in the glaci.com domain. xinetd
stops searching the file as soon as it finds this match.
How about if Daffy connects to your box using the IMAP protocol? In this case, it matches
none of the rules in hosts.allow; the only line that refers to the imapd daemon does not
refer to the 199.170.179 subnet or to the glaci.com domain. xinetd continues on to the
hosts.deny file. The entry ALL: ALL matches anything, so tcpd denies the connection.
The ALL wildcard was also used in the hosts.allow file. In this case, we are telling xinetd to
permit absolutely any host to connect to the FTP service on the Linux box. This is
appropriate for running an anonymous FTP server that anyone on the Internet can access.
If you are not running an anonymous FTP site, you probably should not use the ALL flag.
A good rule of thumb is to make your hosts.allow and hosts.deny files as restrictive as
possible and then explicitly enable only those services that you really need. Also, grant
access only to those systems that really need access. Using the ALL flag to grant universal
access to a particular service may be easier than typing in a long list of subnets or
domains, but better a few minutes spent on proper security measures than many hours
recovering from a break-in.

Tip:
You can further restrict access to services using various options within the /etc/xinetd.conf
file, even to the point of limiting access to certain services to specific times of the day.
Read the manual page for xinetd (by typing man xinetd at a command prompt) to learn
more about these options.

Protecting Your Network with Firewalls

Introduction

What is a firewall? In the non-computer world, a firewall is a physical barrier that keeps a
fire from spreading. Computer firewalls serve a similar purpose, but the "fires" that they
attempt to block are attacks from crackers on the Internet. In this context, a firewall, also
known as a packet filter, is a physical piece of computer hardware that sits between your
network and the Internet, regulating and controlling the flow of information.
226 Linux System and Networking Administration

The most common types of firewalls used today are filtering firewalls. A filtering firewall
filters the traffic flowing between your network and the Internet, blocking certain things
that may put your network at risk. It can limit access to and from the Internet to only
specific computers on your network. It can also limit the type of communication,
selectively permitting or denying various Internet services.
For Linux to act as a filtering firewall, you can use either the ipchains or iptables features.
The iptables feature is the newer of the two and has replaced ipchains as the default Red
Hat Linux firewall. Although ipchains has been removed from Red Hat Enterprise Linux, it
is still in the Fedora Core distribution. Both ipchains and iptables are described in this
chapter.

Configuring a Simple Firewall

You want your computer to be safe from network intruders, but you may not aspire to be a
firewall expert. Instead of trying to understand all the ins and outs of iptables or ipchains,
Red Hat Linux offers the Configure Firewalling window (also refers to as Lokkit).
With Configure Firewalling, you don't need to know how to load rules or memorize port
numbers. All you need to do is choose what types of services you want your computer to
allow in and out over your network connections. It automatically builds an iptables firewall,
without requiring you to look at an iptables command.
To launch Configure Firewalling from the Red Hat menu, click System Tools More System
Tools Lokkit.
With Configure Firewalling open, you are ready to start. Two warnings before you begin:
The Configure Firewalling window overwrites rules created previously. Just to be safe, you
should back up your previous rules as follows:
# cp /etc/sysconfig/iptables /etc/sysconfig/iptables.old
Run this procedure from the console (not over the network) because if you make a mistake
setting up your firewall, you might block network access and not be able to reconnect to
your computer to fix the problem.
The following steps will help you answer questions about your firewall:
 Basic Configuration — Choose High Security if you mostly use the computer as a
client for Web browsing, but not as a server (no shared printers, file systems, and
so on). Low Security is best to begin with for a server computer. Only choose
Disable Firewall if no connections to outside networks exist.
 Local Hosts — If you are connected to a local network that does not access the
Internet, you can choose to trust your connection to that network (Yes). Say No,
for example, if the interface provides a connection to a cable modem or DSL line.
 DHCP — Choose Yes if your network addresses are assigned via DHCP (say No if
you are using static IP addresses you assign yourself).
 Services — Even as a mostly-client computer, you may want to share some
network services. If so, select Yes and you will be able to activate the following
services:
 Web Server — If you configure Apache, TUX, or other Web server for your
computer, click Yes to share that service on the network.
 Incoming Mail — If you configure Sendmail, Postfix, or other mail server on your
computer, click Yes to allow your mail server to receive mail.
 Secure Shell — To allow someone to log in to your computer using a secure shell
(ssh command), select Yes here.
 Telnet — To let someone log in to your computer over a telnet connection, click
Yes here. (Ways of securing telnet connections are described earlier in this
chapter.)
Linux System and Networking Administration 227

 Activate the Firewall — Click Finish to activate the new firewall rules.

At this point, your new firewall is in effect. If you want to see your current firewall, type
iptables -L | less. To see the rules used to build that firewall, open the
/etc/sysconfig/iptables file.

Configuring an ipchains firewall

Ipchains works by examining packets as they are sent and received on a network interface
and deciding which packets should be delivered and which should be stopped. It does this
by examining a list (also called a chain) of rules. It stops at the first rule that matches the
packet and examines that rule's target.

Note:
In Red Hat Linux 8, iptables replaced ipchains as the firewall created during installation. To
use ipchains, you must turn off iptables and create ipchains rules by hand. Then you must
start the ipchains service as described later in this chapter.

To use the ipchains feature, you must have installed the ipchains RPM. To check if ipchains
is installed, type rpm -q ipchains. To see if it's running on your system, type the
ipchains -L command. If ipchains is not configured, you will see the message ipchains:
Incompatible with this kernel. If ipchains is up and running, you will see output that looks
like the following:
# ipchains -L
Chain input (policy ACCEPT):
target prot opt source destination ports
ACCEPT all ------ anywhere anywhere n/a
ACCEPT udp ------ a.myisp.net anywhere domain - any
ACCEPT udp ------ b.myisp.net anywhere domain - any
DENY tcp -y---- anywhere anywhere any - any
DENY udp ------ anywhere anywhere any - any
Chain forward (policy ACCEPT):
Chain output (policy ACCEPT):
The preceding output represents a highly secure firewall. Notice that only input is
restricted. In other words, restrictions are on which services outside users can request.
The first ACCEPT line results from a rule that allows all requests made from users on the
local system (that is, it allows the loopback driver, as indicated by n/a under ports). With
that enabled, you can request any service from your local system without the packet being
denied.
The next two ACCEPT lines allow the computers I indicate as my DNS servers (from
/etc/resolv.conf) to request DNS services (domain) from my computer. The last two rules
(DENY) result in all tcp and udp requests to be denied that don't match previous rules.
This firewall configuration is set in the /etc/sysconfig/ipchains file. When the ipchains
service starts during system boot time (/etc/init.d/ipchains), the service reads the rules
from /etc/sysconfig/ipchains. Here is what the rules from that file look like to create the
preceding configuration:
:input ACCEPT
:forward ACCEPT
:output ACCEPT
-A input -s 0/0 -d 0/0 -i lo -j ACCEPT
228 Linux System and Networking Administration

-A input -s 192.160.0.253 53 -d 0/0 -p udp -j ACCEPT


-A input -s 192.160.0.254 53 -d 0/0 -p udp -j ACCEPT
-A input -s 0/0 -d 0/0 -p tcp -y -j DENY
-A input -s 0/0 -d 0/0 -p udp -j DENY
Because ipchains rules are cleared and reloaded based on the contents of this file, each
time you start your system, the /etc/sysconfig/ipchains file is a good place to set up your
firewall rules. With computer-cracker attacks on the rise, the current approach to security
the experts recommend is to be secure by default. This means you should start by
restricting most services and should then add only those services you want enabled. Put in
the rules that allow services first, and then have all other services denied in the last two
lines.

Understanding ipchains firewall rules

An ipchains target can be a simple command like ACCEPT or DENY, or it can be the name
of another rule chain to begin examining. There are three default rule chains that the
kernel will always examine. They are the input, output, an d forward chains. You can create
additional user-defined chains and call them from these original three, but for simple
firewall configurations, the standard three should be sufficient.

Tip ipchains stops examining a rule chain after finding a match, so pay attention to the
order of rules. Rules with specific conditions should go before those with similar but
broader conditions. If you accept all TCP connections but follow that with a rule to deny
telnet access, telnet (being a TCP service) will be allowed. Reverse the rules order
(deny telnet, then accept TCP) to have the right effect.

The general syntax is to invoke ipchains with a parameter specifying the action to take,
followed by the rule chain to take it on. A rule description and a rule target may follow
this. The following table shows action parameters you can use with ipchains.

Action Parameter Description

-A, --append Append a new rule to the end of the specified list.

-D, --delete Delete a rule from the specified list. You can specify the rule by
its numeric place in the list or by the rule parameters that
match it.

-R, --replace Replace a rule with a new one.

-I, --insert Insert a new rule into a specific position in the list.

-L, --list List all the rules in a chain. If the chain name is left off, list all
rules in all chains.

-F, --flush Flush all the rules out of a chain.

-Z, --zero Zero out the packet counters for all chains.

-N, --new-chain Create a new chain with the specified name.

-X, --delete-chain Delete the chain with the specified name.

-P, --policy Set the policy for the chain to the specified target. The policy of
a chain describes what action to take if no rule matches the
Linux System and Networking Administration 229

Action Parameter Description

packet. The default policy for all chains is ACCEPT.

-M, --masquerading Allows viewing of masqueraded connections.

-S, --set Set the timeouts for TCP, TCPFIN, and UDP packets.

-C, --check Check a supplied packet against the given chain. This is useful
mainly for debugging.

-h Print a Help message describing parameters to ipchains.

As you can see in the preceding table, the ipchains action parameters can be expressed in
two forms, either as a dash followed by a single capital letter, or two dashes followed by a
descriptive word. Both will work, so use whichever you prefer. In the examp le in this
chapter, I will use the abbreviated version.
Usually, we follow the action parameter with the rule chain to apply it to. Rules added to
the input chain will be examined only when filtering network packets being received by the
Linux box. Similarly, the output chain is examined only for packets being transmitted from
the Linux box. The forward chain is examined only for network packets that are received
by the Linux system but will be delivered to some other network system. Packet
forwarding only occurs when your system is configured as a router.
After specifying a chain to act on, you may specify some optional parameters to define a
rule. The following table lists the available optional parameters.

Parameter Description

-p, --protocol[!] protocol Specify the protocol that the rule should match against. This
should be TCP, UDP, or ICMP.

-s, --source [!] address Specify the source address to match against. This can be an
individual address, or you can specify an entire subnet by
following the address with a / and the number of 1 bits in
the left side of the subnet mask. Thus, the address
199.170.177.0/24 would have a subnet mask of
255.255.255.0.

--source-port [!]port The source TCP or UDP port number as specified in


/etc/services. You can also specify a range of ports by
listing the first and last port number separated by a ':' colon
character.

-d, --destination [!] address Specify the destination address to match against. This can
be an individual address, or you can specify an entire
subnet by following the address with a / and the number of
1 bits in the left side of the subnet mask. Thus, the address
199.170.177.0/24 would have a subnet mask of
255.255.255.0.

--destination-port [!] port The destination TCP or UDP port number as specified in
/etc/services. You can also specify a range of ports by
listing the first and last port number separated by a ':' colon
character.

--icmp-type [!] typename Set the type of ICMP packet to use.


230 Linux System and Networking Administration

Parameter Description

-j, --jump target The name of the target (action) to execute when the rule
matches. This could be the name of another ipchain or one
of several predefined targets.

-i, --interface [!] name The name of the network interface that this rule applies to.
If this option is not supplied, the rule will apply to all
interfaces.

[!] -f, --fragment The rule will apply only to fragmented packets, excluding
the first packet. In other words, it applies to all packet
fragments after the first one.

-b, --bidirectional The rule should apply to both incoming and outgoing
packets.

-v, --verbose Print debug messages when processing this ipchains


command.

-n, --numeric Use IP addresses instead of host names when printing


output to the screen.

-l, --log Turn on kernel logging of matching packets. This will slow
things down and fill up your hard drive. It is intended
mainly for debugging.

-o, --output [maxsize] Divert packets to a user space process. Another debugging
feature.

-m, --mark markvalue Mark the packet with a 32-bit signature. This is probably
only useful to you if you are a kernel hacker.

-t, --TOS andmask xormask Examine the TOS field of the packet using the supplied bit
masks. Read the ipchains man page for a complete
discussion of this option.

-x, --exact Display exact values of packet counters rather than


numbers rounded to the kilobyte.

[!] -y, --syn Examine the SYN bit in the TCP packet being looked at.
Useful for blocking TCP connection from being initiated in
one direction but not the other.

--line-numbers Show line numbers when listing rules. This is useful if you
plan to delete or modify rules by position number.

--no-warnings Disable all warning messages.

After specifying a rule for a particular type of packet, you must specify the target for it
using the -j or --jump option. This tells ipchains what to do with that packet when it finds a
rule that matches it. The target could be the name of another rule chain to traverse, but
more often it is one of the predefined actions described in the following table.
Linux System and Networking Administration 231

Target Description

ACCEPT Accept the packet and deliver it in the normal way.

DENY Drop the packet completely.

REJECT Drop the packet and then send an ICMP packet with an explanation to
the sending host. This is primarily useful for debugging.

MASQ Use IP Masquerading for this packet type.

REDIRECT Redirect the packet to a new location.

RETURN Return from this chain to the chain that called it. Continue examining
rules in the calling chain where you left off.

I've shown you the various components of an ipchains command. It is time to put them
together into some practical examples. It is possible to create some very sophisticated and
complicated rule lists with ipchains, but I will keep my examples rather simple. Keeping
things simple is generally a good policy, since large, complicated rule chains can impact
system performance. More time spent examining rules means less time delivering packets
and serving up information. The higher the traffic level on your Linux box, the greater the
performance impact of those complicated rule chains.

Changing ipchains firewall rules

Now let's try adding a rule. As an example, imagine we want to block ICMP packets to
disallow "pinging" of our Linux box. You may do that to avoid various denial-of-service
attacks that could be launched against your system. Block ICMP with a command like the
following:
# ipchains -A input -p icmp -j DENY
This specifies that we are adding a rule to the input chain. It will match any ICMP packet
and will drop it rather than allowing it through. Now if you are using the ping command
against your Linux box, you should receive no response. Type the ipchains -L command
again, and you'll see something like this:
Chain input (policy ACCEPT):
target prot opt source destination ports
DENY icmp ------ anywhere anywhere any -> any
Chain forward (policy ACCEPT):
Chain output (policy ACCEPT):
You can see your new rule listed. This rule will block all ICMP packets entering your
system, regardless of which computer sent those packets. If your Linux system is acting as
a router, it will also block ICMP packets that are being forwarded from the Internet to your
network, or vice versa. People on the Internet will be unable to ping anything on your
network. Likewise, you will be unable to ping anything on the Internet. Perhaps that is not
what you want. Assume then that you wish to block pinging of systems on your network by
people on the Internet, but allow pinging of the router and allow the router to ping hosts
on the Internet. First, we should flush the contents of the input chains using the -F
parameter; then we can add our new rule.
# ipchains -F input
# ipchains -A forward -p icmp -j DENY
232 Linux System and Networking Administration

Now we can ping the Linux system and the Linux system can ping other boxes, but ping
requests will not be passed through the Linux system. If you wish, use the ipchains -L
command to verify that the rule has now been added to the forward chain rather than the
input chain.
You may also wish to block the telnet protocol when coming from the Internet. For this
example, let us assume that our Linux router is connected to the Internet via a dial-up
connection called ppp0 and is connected to our internal LAN via an Ethernet connection
called eth0. In that case, you could block telnet with a command like the following:
# ipchains -A input -i ppp0 -p tcp --dport 23 -j DENY
This rule basically says that any TCP packet with a destination port of 23 (the telnet port
as specified in /etc/services) that is arriving on the ppp0 interface should be dropped. This
does not prevent you from telneting to your Linux box from your internal network, but it
does block telnet access from the Internet.
I'm going to finish up with one more useful example. Imagine you want to allow any type
of outbound TCP connection to the Internet, but want to block any inbound TCP
connection. Every TCP connection sends packets in both directions, so at first glance it
would seem impossible. Block all inbound TCP packets, and the reply packets to your
outbound connections will also be blocked. The trick is to block only the initial TCP packet
that is used to start an inbound connection. We can do this because all TCP connection
requests start with a packet that has something called the SYN bit set. We can use the --
syn option to tell ipchains to look for that bit. Try the following command:
# ipchains -A input -i ppp0 -p tcp --syn -j DENY
There are many useful ways to filter traffic using ipchains. I encourage you to read the
ipchains man page (type man ipchains) and the ipchains HOWTO document to learn more
about it.

Saving ipchains Firewall Rules

After you have created the ipchains rules you want, it is important to save them to a file;
otherwise, they will be lost when you reboot the server. Fortunately, a pair of useful scripts
(ipchains-save and ipchains-restore) is provided for exactly this purpose. Essentially,
ipchains-save will echo the current ipchains rule list to the screen. The ipchains-restore
script reads in the specially formatted rule list and makes it active. After customizing
ipchains, save the new rules to a file by running ipchains-save and directing the output to
a file such as:
# /sbin/ipchains-save > /tmp/ipchains.rules
Next, you can add the rules you have created to the /etc/sysconfig/ipchains file. As root
user, open the file in any text editor. Then read in the ipchains.rules file you have created
in the preceding example.

Configuring an iptables Firewall

The iptables firewall feature (also referred to as netfilter) is the default firewall software
when you install Red Hat Linux. Today, both ipchains and iptables are available with Red
Hat Linux, although only one can be active at a time. iptables is the better supported
firewall tool these days.
If you currently use ipchains on your Red Hat Linux system and you wish to convert to
iptables, you need to disable ipchains before you can use iptables. In fact, if you try to use
the iptables script (/etc/init.d/iptables) to start iptables while the ipchains module is
loaded, the iptables startup script silently exits.
While iptables is generally considered to be more complex than ipchains to work with, it is
also considered to be more powerful and flexible. Because development is not continuing
for ipchains, the few broken ipchains features that exist will probably stay broken.
Linux System and Networking Administration 233

This section describes how to turn on iptables and set up firewall rules for several different
types of situations. It also tells how to turn on features related to firewalls that allow your
iptables firewall to do Network Address Translation (NAT), IP masquerading, port
forwarding, and transparent proxies.

Note The Red Hat Linux startup scripts will "punch a hole" through your firewall if you use
certain services, and will therefore work even if they are not explicitly enabled in your
iptables configuration. For example, NTP (which sets your system time from a
network time server) and DNS resolution (which lets you contact a DNS server to
resolve addresses) both open the ports they need in your firewall.

Turning on iptables

To turn on iptables, you might have to turn off ipchains. (This might be the case if you just
upgraded from a release prior to Red Hat Linux 8, where ipchains was the default.) Then
you can add the modules and create the rules you need for your iptables firewall. The
following procedure describes how to get iptables going on your Red Hat Linux system.

Tip:
During the time that you turn off ipchains, turn on iptables, and configure the filtering
rules for iptables, your computer may be unprotected from the network. You should test
your firewall rules on non-critical computers, and then perform the switch on critical
computers either quickly or by temporarily shutting down your network interfaces.

Stop the ipchains script from starting automatically at boot time:


# chkconfig ipchains off
Set the iptables script to start automatically at boot time:
# chkconfig iptables on
Now you can either reboot Red Hat Linux, or stop ipchains and unload the ipchains
module, as follows:
# service ipchains stop
# modprobe -r ipchains
Before you can start iptables you must have a working set of rules that have been placed
in your /etc/sysconfig/iptables file. To create those rules, refer to the examples in the
following sections. (Without the configuration file in place, iptables fails silently.)
If you are doing NAT or IP Masquerading, turn on IP packet forwarding. One way to do this
is to change the value of net.ipv4.ip_forward to 1 in the /etc/sysctl.conf file. Open that file
as root user with any text editor and change the line to appear as follows:
net.ipv4.ip_forward = 1
Restart your network interfaces to have IP packet forwarding take effect.
# /etc/init.d/network restart
Once the rules file is in place, start up iptables:
# /etc/init.d/iptables start
At this point, iptables is installed as your firewall. You can check to see that the modules
used by iptables are loaded by using the lsmod command, as follows:
# lsmod |grep ip
ipt_REJECT 3928 6 (autoclean)
iptable_filter 2412 1 (autoclean)
ip_tables 15096 2 [ipt_REJECT iptable_filter]
234 Linux System and Networking Administration

If you want to allow passive FTP or IRC connections from computers on your LAN, you may
need to load those modules by adding them to the /etc/modules.conf file. (See the
description of passive FTP and IRC after the firewall-example sections.)
If your iptables service didn't start, make sure that:
An ipchains module is not loaded. (Unload it with modprobe -r as shown previously.)
The /etc/sysconfig/iptables file exists. (You need to create one if one was not already
created for you when you installed Red Hat Linux.)

Tip As you add iptables rules, more modules will have to be loaded. Appropriate
modules should be loaded automatically when a new rule is entered. Run lsmod
| grep ip again after you have added a few rules to see which modules were
added. Note that these modules will not be unloaded if you decide to stop
iptables. They will stay loaded until the next reboot or until you remove them
(modprobe -r).

The following sections contain examples of iptables firewall rules.

Creating iptables Firewall Rules

One way to configure iptables is to start by adding and deleting rules to your kernel from
the command line. Then when you get a set of rules that you like, you save the rules that
are currently running on your system. The tools you use to create your firewall rules and
then make them permanent are as follows:
iptables — Use this command to append (-A), delete (-D), replace (-R) or insert (-I) a
rule. Use the -L option to list all current rules.
iptables-save -c — Use this command to save the rules from the kernel and install them
in the configuration file.
/etc/sysconfig/iptables — This is the configuration file that contains the rules that were
saved from the iptables-save command.
/etc/init.d/iptables — This is the iptables start-up script that must run automatically
each time Red Hat Linux reboots. When it starts, it clears all iptables rules and counters
and installs the new rules from the /etc/sysconfig/iptables file. You can also use this script
with different options from the command line to check the status of iptables (status) or to
run iptables-save for you to save the current rules (save).
To get you started with iptables, I'm providing a sample set of iptables rules along with
descriptions of how you might change those rules for different situations. Here's how you
could load and save any of the sets of rules described in the following example:
If you are currently running ipchains, complete the procedure in the previous " Turning on
iptables" section.
Stop iptables and clear all existing rules:
# /etc/init.d/iptables stop
Add the rules shown in the following example to a file, using any text editor. Modify the
rules to suit your situation and save the file.
As root user, run the file as a shell script. For example, if you named the file firescript, you
could run it as follows:
# sh firescript
See how the rules were loaded into the kernel:
# iptables -L
If everything looks okay, save the rules that are now in the kernel into the
/etc/sysconfig/iptables file:
# iptables-save > /etc/sysconfig/iptables
Linux System and Networking Administration 235

From now on the rules will be read each time you reboot or restart iptables. Save a copy of
the script you used to create the rules, in case you ever need it again.
Example 1: Firewall for shared Internet connection (plus servers)
This example features a home or small-office LAN with a Red Hat Linux system acting as
an iptables firewall between the LAN and the Internet. The firewall computer also acts as a
Web server, FTP server, and DNS server.
If you want to use the sample firewall script that follows, you must change the following
information to match your configuration:
 Firewall computer — The firewall computer is set up as follows:
 Local host — 127.0.0.1 (IP address) and lo (interface). You shouldn't need to
change these.
 Connection to the Internet — 123.45.67.89 (IP address) and eth0 (interface).
Replace them with the static IP address and interface name associated with your
connection to the Internet, respectively.
 Connection to the LAN — 10.0.0.1 (IP address) and eth1 (interface). Replace
10.0.0.1 and eth1 with the static IP address and interface name associated with
your connection to your LAN, respectively.
 Computers on the LAN — Each computer on the LAN in the example has an IP
address between 10.0.0.2 to 10.0.0.254. Change 10.0.0.255 to a number that
matches your LAN's range of addresses.
Here is an example of a script to load firewall rules:

# (1) Policies (default)


iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# (2) User-defined chain for ACCEPTed TCP packets


iptables -N okay
iptables -A okay -p TCP --syn -j ACCEPT
iptables -A okay -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A okay -p TCP -j DROP

# (3) INPUT chain rules

# Rules for incoming packets from LAN


iptables -A INPUT -p ALL -i eth1 -s 10.0.0.0/8 -j ACCEPT
iptables -A INPUT -p ALL -i lo -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -p ALL -i lo -s 10.0.0.1 -j ACCEPT
iptables -A INPUT -p ALL -i lo -s 123.45.67.89 -j ACCEPT
iptables -A INPUT -p ALL -i eth1 -d 10.0.0.255 -j ACCEPT

# Rules for incoming packets from the Internet

# Packets for established connections


236 Linux System and Networking Administration

iptables -A INPUT -p ALL -d 123.45.67.89 -m state --state


ESTABLISHED,RELATED -j ACCEPT

# TCP rules
iptables -A INPUT -p TCP -i eth0 -s 0/0 --destination-port 21 -j okay
iptables -A INPUT -p TCP -i eth0 -s 0/0 --destination-port 22 -j okay
iptables -A INPUT -p TCP -i eth0 -s 0/0 --destination-port 80 -j okay
iptables -A INPUT -p TCP -i eth0 -s 0/0 --destination-port 113 -j okay

# UDP rules
iptables -A INPUT -p UDP -i eth0 -s 0/0 --destination-port 53 -j ACCEPT
iptables -A INPUT -p UDP -i eth0 -s 0/0 --destination-port 2074 -j ACCEPT
iptables -A INPUT -p UDP -i eth0 -s 0/0 --destination-port 4000 -j ACCEPT

# ICMP rules
iptables -A INPUT -p ICMP -i eth0 -s 0/0 --icmp-type 8 -j ACCEPT
iptables -A INPUT -p ICMP -i eth0 -s 0/0 --icmp-type 11 -j ACCEPT

# (4) FORWARD chain rules


# Accept the packets we want to forward
iptables -A FORWARD -i eth1 -j ACCEPT
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

# (5) OUTPUT chain rules


# Only output packets with local addresses (no spoofing)
iptables -A OUTPUT -p ALL -s 127.0.0.1 -j ACCEPT
iptables -A OUTPUT -p ALL -s 10.0.0.1 -j ACCEPT
iptables -A OUTPUT -p ALL -s 123.45.67.89 -j ACCEPT

# (6) POSTROUTING chain rules


iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 123.45.67.89

I divided the commands in the preceding script into six sections. The following text
describes each of those sections.
(1) Policies — The iptables -P commands set the default policies for INPUT, OUTPUT, and
FORWARD chains. By assigning each of those policies to DROP, any packet that isn't
matched is discarded. In other words, for a packet to get through, it has to be specifically
matched and ACCEPTed by one of the other rules in the script.
(2) User-defined chain — A user-defined chain I call okay is created to do a few more
checks on packets requesting certain TCP services that I'm going to allow through (Web,
FTP, and DNS services). The -N okay option creates the okay chain. The next line says that
a SYN packet (--syn), which requests a new connection, is fine to let through. The next
line allows through packets associated with an ESTABLISHED connection (one that has
already had traffic pass through the interface) or a RELATED connection (one that is
Linux System and Networking Administration 237

starting a new connection related to an already-established connection). The final line in


this set tells iptables to DROP packets that don't meet one of those checks.
(3) INPUT chain rules — The bulk of the packet filtering is done in the INPUT chain. The
first sets of input rules indicates to iptables when to always accept packets from the
Internet and from the LAN. The next three sets determine which requests for specific
protocols (TCP, UDP, and ICMP) are accepted.
Packets from LAN — Because you want the users on your LAN and the firewall computer
itself to be able to use the Internet, this set of rules lets through packets that are initiated
from those computers. The first line tells iptables to accept packets for ALL protocols for
which the source is an acceptable addresses on your LAN (-s 10.0.0.0/8, which represents
IP numbers 10.0.0.1 through 10.0.0.254). The next three lines allow packets that come
from all valid IP addresses on the firewall computer itself (-s 127.0.0.1, 10.0.0.1, and
123.45.67.89). The last line accepts broadcast packets (-d 10.0.0.255) on the LAN.
Packets from Internet (already connected) — This line is split in two (I just used the
backslash to join the lines because the page wasn't wide enough to sh ow it as one line). It
ACCEPTs packets that are both associated with connections that are already established (--
state ESTABLISHED,RELATED) and are requested directly to the firewall's IP address
(123.45.67.89).
TCP rules (new connections) — Here is where you open up the ports for the TCP
services you want to provide to anyone from the Internet. In these lines you open ports for
FTP service (--destination-port 21), secure shell service (22), Web service (80), and
IDENTD authentication (113), the last of which might be necessary for protocols such as
IRC. Instead of accepting these requests immediately, you jump to the okay chain you
defined to further check that the packets was formed properly.

Caution:
You want to ensure that the services on the ports to which you are allowing access are
properly configured before you allow packets to be accepted to them.

UDP rules (new connections) — These lines define the ports where connection packets
are accepted from the Internet for UDP services. In this example I chose to accept
requests for DNS service (--destination-port 53) because the computer is set up as a DNS
server. The example also illustrates lines that accept requests for a couple of other
optional ports. Port 2074 is needed by some multimedia applications the users on your
LAN might want to use, and port 4000 is used by the ICQ protocol (for online chats).
ICMP rules — ICMP messages are really more for reporting conditions of the server than
for actually providing services. Packets from the Internet that are accepted for ICMP
protocol requests are those for ICMP types 8 and 11. Type 8 service, which allows your
computer to accept echo reply messages, makes it possible for people to ping your
computer to see if it is available. Type 11 service relates to packets whose time to live
(TTL) was exceeded in transit, and for which you are accepting a Time Exceeded message
that is being returned to us. (You need to accept Type 11 messages to use the traceroute
command to find broken routes to hosts you want to reach.)
(4) FORWARD chain rules — Because this firewall is also acting as a router, FORWARD
rules are needed to limit what the firewall will and will not pass between the two networks
(Internet and local LAN). The first line forwards everything from the local LAN (-A
FORWARD -i eth1). The second line forwards anything from the Internet that is associated
with an established connection (--state ESTABLISHED, RELATED).
(5) OUTPUT chain rules — These rules basically exist to prevent anyone from your local
computer from spoofing IP addresses (that is, from saying packets are coming from
somewhere that they are not). According to these three rules, each packet output from
your firewall must have as its source address one of the addresses from the firewall
computer's interfaces (127.0.0.1, 10.0.0.0.1, or 123.45.67.89).
238 Linux System and Networking Administration

(6) POSTROUTING chain rules — The POSTROUTING chain defines rules for packets
that have been accepted, but need additional processing. This is where the actual network-
address translation (NAT) work takes place. For the NAT table (-t nat), in the
POSTROUTING chain, all packets that go out to the Internet have their addresses
translated to that of the firewall's external interface (--to-source 123.45.67.89). In this
case I used the Source Network Address Translation (SNAT) chain because I have a static
IP address (123.45.67.89) associated with my Internet connection. If I were using a
dynamic IP address (via DHCP), I would use MASQUERADE instead of SNAT. I would also
have to change any references to -d 123.45.67.89 to -i eth0. (Of course, you would be
using a different IP address and possibly a different Ethernet interface.)

Example 2: Firewall for shared Internet connection (no servers)


In this scenario, the firewall is protecting a Linux system (firewall) and several systems on
the LAN that only want to connect to the Internet. No servers are behind this firewall, so
you want to prevent people from the Internet from requesting services.
You could use the same script shown in Example 1, but not use lines that request TCP
services. So you could drop the user-defined chain in section 2 and drop the TCP rules
from section 3. You could also remove the ICMP rules, if you don't want your firewall to be
invisible to ping requests (Type 8) and if you don't care about receiving messages when
your packets exceed their time to live values (Type 11), such as when a packet runs into a
broken router.

Example 3: Firewall for single Linux system with Internet connection


In this example, there is one network interface, connecting your Red Hat Linux system to
the Internet. You are not sharing that connection with other computers and you are not
offering any services from your computer.
In this case, you could cut sections 2, 4, and 6. From section 3, you could cut all rules
relating to incoming requests from the LAN and all TCP services. As I mentioned in
Example 2, you could also remove the Type 8 ICMP rule to make your firewall invisible to
ping requests from the Internet and the Type 11 ICMP rule to not accept messages about
failed time-to-live packets.

Understanding iptables

Now that you've seen something about what iptables rules look like and how you can get
them going, step back a bit and see how iptables works.
The iptables feature works by having IP packets (that is, network data) that enter or leave
the firewall computer, traverse a set of chains that define what is done with the packet.
Each rule that you add essentially does the following:
 Checks if a particular criterion is met (such as that a packet requests a particular
service or comes from a particular address) and
 Takes an action (such as dropping, accepting, or further processing a packet).
Different sets of rules are implemented for different types of tables. For example, tables
exist for filtering (filter), network address translation (nat), and changing packet headers
(mangle). Depending on the packet's source and destination, it traverses different chains.
Most of the rules you create will relate to the filter table (which is implied if no other table
is given).
The chains associated with the filter table are INPUT, OUTPUT, and FORWARD. You can
add user-defined chains as well. You will probably be most interested in adding or
removing particular TCP and UDP services using the basic rules shown in the previous
example. Assign ACCEPT to packets you want to go through and DROP to those you want
to discard. You can also assign REJECT to drop a packet but return a message to the
sender, or LOG to neither drop nor accept the message, but to log information about the
packet.
Linux System and Networking Administration 239

A lot of great features are built into iptables. The following descriptions tell you about
some cool things you can do with iptables and give you some tips on using it.
Allowing FTP and IRC services through an iptables firewall
With passive FTP, the FTP client sends its IP address and the port number on which it will
listen for data to the server. If that client is on a computer that is behind your firewall, for
which you are doing NAT, that information must be translated as well or the FTP server will
not be able to communicate with the client.
iptables uses connection-tracking modules to track connections. Using this feature, it can
look inside the FTP data themselves (that is, not in the IP packet header), to get the
information it needs to do NAT (remember that computers from the Internet can't talk
directly to your private IP addresses). To do FTP connection tracking (to allow passive FTP
connections to the clients on your LAN), you need to have the following modules loaded:
ip_conntrack
ip_conntrack_ftp
ip_nat_ftp
The same is true for chats (IRC) and DCC sends. Addresses and port numbers are stored
within the IRC protocol packets, so those packets must be translated too. To allow clients
on your LAN to use IRC services, you need to load the following modules:
ip_conntrack_irc
ip_nat_irc
The default port for IRC connections is 6667. If you don't want to use the default you can
add different port numbers when you load the connection-tracking modules:
insmod ip_conntrack_irc.o ports=6668,6669
Using iptables to do NAT or IP Masquerading
As noted in the iptables example, you can use Source Network Address Translation (SNAT)
or IP Masquerading (MASQUERADE) to allow computers on your LAN with private IP
addresses to access the Internet through your iptables firewall. Choose SNAT if you have a
static IP address for your Internet connection and MASQUERADE if the IP address is
assigned dynamically.
When you create the MASQUERADE or SNAT rule, it is added to the NAT table and the
POSTROUTING chain. For MASQUERADE you must provide the name of the interface (such
as eth0, ppp0, or slip0) to identify the route to the Internet or other outside network. For
SNAT you must also identify the actual IP address of the interface. Here is an example of a
MASQUERADE rule:
# iptables –t nat –A POSTROUTING –o eth0 –j MASQUERADE

Here is an example of a SNAT rule:


# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 12.12.12.12
You can add several source addresses if you have multiple addresses that provide a route
to the Internet (for example, --to-source 12.12.12.12.1-12.12.12.12.254). Although
MASQUERADE uses some additional overhead, you probably need to use it instead of SNAT
if you have a dial-up connection to the Internet for which the IP address changes on each
connection.
Remember that you need to make sure that IP forwarding is turned on in the kernel. (It is
off by default.) To turn it on temporarily, you can do the following:
# echo 1 > /proc/sys/net/ipv4/ip_forward
If you require dynamic IP addressing, turn on that service:
# echo 1 > /proc/sys/net/ipv4/ip_dynaddr
Using iptables as a transparent proxy
240 Linux System and Networking Administration

With the REDIRECT target you can cause traffic for a specific port on the firewall computer
to be directed to a different one. Using this feature you can direct host computers on your
local LAN to a proxy service on your firewall computer without those hosts knowing it.
The following is an example of a set of command-line options to the iptables command
that causes a request for Web service (port 80) to be directed to a proxy service (port
3128):
-t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 3128
You can only use REDIRECT targets in PREROUTING and OUTPUT chains within a nat table.
You can also give a range of port numbers to spread the redirection across multiple port
numbers.

Using iptables to do Port Forwarding

What if you have only one static IP address, but you want to use a computer other than
your firewall computer to provide Web, FTP, DNS, or some other service? You can use the
Dynamic Network Address Translation (DNAT) feature to direct traffic for a particular port
on your firewall to another computer.
For example, if you wanted all requests for Web service (port 80) that were directed to the
firewall computer (-d 15.15.15.15) to be directed to another computer on your LAN (such
as 10.0.0.25), you could use the following iptables command:
# iptables -t nat -A PREROUTING -p tcp -d 15.15.15.15 -dport 80 \
-j DNAT --to-destination 10.0.0.25
(Note that the preceding example should actually appear on one line. The backslash
indicates continuation on the next line.)
You can also spread the load for the service you are forwarding by providing a range of IP
addresses (for example, --to-destination 10.0.0.1-10.0.0.25). Likewise, you can direct the
request to a range of ports as well.

Using Logging with iptables

Using the LOG target you can log information about packets that meet the criteria you
choose. In particular you might want to use this feature to log packets that seem like they
might be improper in some way. In other words, if you don't want to drop a packet for
some reason, you can just log its activity and decide later if something needs to be
corrected.
The LOG target directs log information to the standard tools used to do logging in Red Hat
Linux: dmesg and syslogd. Here is an example of a rule using a LOG target:
-A FORWARD -p tcp -j LOG --log-level info
Instead of info, you could use any of the following log levels available with syslog: emerg,
alert, crit, err, warning, notice, info, or debug. Using the --log prefix option as follows, you
could also add information to the front of all messages produced from this logging action:
-A FORWARD -p tcp -j LOG --log-level info --log-prefix "Forward INFO "

Enhancing your iptables firewall

You can modify or expand on the iptables examples given in this chapter in many ways.
iptables is tremendously flexible.
When you actually create your own iptables firewall, you should refer to the iptables man
page (type man iptables) for detailed descriptions of options, ways of matching, ways of
entering addresses, and other details.
Linux System and Networking Administration 241

Here are a few tips for using iptables features:


 Reduce rules — Try to improve performance by reducing the number of rules.
Using subchains can keep a packet from seeing rules that don't apply to it.
 Deal with fragments — Use the -f option to refer to the second and subsequent
packets of a packet that was split into fragments. In general, it is safe to not drop
second and third fragments for which you don't have a first packet fragment
because they won't be reassembled. If you use NAT the fragments are assembled
before filtering, so you shouldn't have problems with unfiltered fragments being
sent through.
 Opposite — To make a rule its opposite, use an exclamation mark (!).
 All interfaces — To match all interfaces of a type, use a plus sign (+), as in eth+.
 Blocking connections — Use the --syn option to block SYN packets (that is,
those packets requesting connections). This option only applies to TCP packets.
 Limiting — Use the --limit option to restrict the rate of matches that result in log
messages. This option allows matches to only produce messages a limited number
of times per second (the default is three per hour with burst of five).
 DOS Attacks — You can use the --limit option to reduce the impact of DOS
attacks, but it still won't stop them altogether. As long as the traffic is directed at
your server, your network bandwidth is being leeched away, and the machine still
utilizes resources to ignore the data.
 Table types — The default table type is filter. The other types of tables are nat
(for IP Masquerading) and mangle (for altering packets). To use a table other than
filter you must add a –t table_type option, where table_tape is either nat or
mangle.

Detecting Intrusions from Log Files


Preparing your system for a cracker attack is only part of the battle. You must also
recognize a cracker attack when it is occurring. Understanding the various log files in
which Red Hat Linux records important events is critical to this goal. The log files for your
Red Hat Linux system can be found in the /var/log directory.
Red Hat Linux comes with a System Logs window (redhat-logview command) that you can
use to view and search critical system log files from the GUI. To open the System Logs
window, from the main desktop menu, click System Tools ® System Logs. Figure below
shows an example of the System Logs window.
242 Linux System and Networking Administration

Fig - Display system log files in the System Logs window


To view a particular log file, click the log name in the left column. If you are looking for a
particular message or problem, type a keyword into the "Filter for" box, and click Filter.
Only lines containing that word are displayed. Case matters, so searching for "Mem" won't
find "mem" when you use the filter. Click Reset to display the whole file again.
The table below contains a listing of log files displayed on the System Logs window, along
with other files in the /var/log directory that may interest you. (* Indicates a log file that is
not contained in the System Logs window. Access these files directly from /var/log.)

System Logs Filename Description


Name

Boot Log boot.log Contains messages indicating which systems


services have started and shut down successfully
and which (if any) have failed to start or stop.

Cron Log cron Contains status messages from the crond, a


daemon that periodically runs scheduled jobs,
such as backups and log file rotation.

Kernel Startup Log dmesg A recording of messages printed by the kernel


when the system boots.

FTP Log xferlog Information about files transferred using the wu -


ftpd FTP service.

Apache Access Log httpd/access_log Logs requests for information from your Apache
Web server.
Linux System and Networking Administration 243

System Logs Filename Description


Name

Apache Error Log httpd/error_log Logs errors encountered from clients trying to
access data on your Apache Web server.

Mail Log maillog Contains information about addresses to which


and from which e-mail was sent. Useful for
detecting spamming.

MySQL Server Log mysqld.log Includes information related to activities of the


MySQL database server (mysqld).

News Log spooler Directory containing logs of messages from the


Usenet News server, if you are running one.

RPM Packages rpmpkgs Contains a listing of RPM packages that are


installed on your system.

Security Log secure Records the date, time, and duration of login
attempts and sessions.

System Log messages A general-purpose log file to which many


programs record messages.

Update Agent Log up2date Contains messages resulting from actions by the
Red Hat Update Agent.

XFree86 Log XFree86.0.log Includes messages output by the Xfree86 server.

* gdm/:0.log Holds messages related to the login screen


(GNOME display manager).

* samba/log.smbd Messages from the Samba SMB file service


daemon.

* squid/access.log Contains messages related to the squid


proxy/caching server.

* vsftpd.log Contains messages relating to transfers made


using the vsFTPd daemon (FTP server).

* sendmail Error messages recorded by the sendmail


daemon.

* uucp Status messages from the Unix to Unix Copy


Protocol daemon.

The Role of syslogd

Most of the files in the /var/log directory are maintained by the syslogd service. The
syslogd daemon is the System Logging Daemon. It accepts log messages from a variety of
other programs and writes them to the appropriate log files. This is better than having
every program write directly to its own log file because it allows you to centrally manage
244 Linux System and Networking Administration

how log files are handled. It is possible to configure syslogd to record varying levels of
detail in the log files. It can be told to ignore all but the most critical message, or it can
record every detail.
The syslogd daemon can even accept messages from other computers on your network.
This is particularly handy because it enables you to centralize the management and
reviewing of the log files from many systems on your network. There is also a major
security benefit to this practice. If a system on your network is broken into, the cracker
cannot delete or modify the log files because those files are stored on a separate
computer. It is important to remember, though, that those log messages are not, by
default, encrypted. Anyone tapping into your local network will be able to eavesdrop on
those messages as they pass from one machine to another. Also, though the cracker may
not be able to change old log messages, he will be able to affect the system such that any
new log messages should not be trusted.
It is not uncommon to run a dedicated loghost, a computer that serves no other purpose
than to record log messages from other computers on the network. Because this system
runs no other services, it is unlikely that it will be broken into. This makes it nearly
impossible for a cracker to erase his or her tracks. It does not, however, mean that all of
the log messages are accurate after a cracker has broken into a machine on your network.

Redirecting Logs to a loghost with syslogd

To redirect your computer's log files to another computer's syslogd, you must make some
changes to your local syslogd's configuration file. The file that you need to work with is
/etc/syslog.conf. Become root using the su command and then load the /etc/syslog.conf
file in a text editor (such as vi). You should see something similar to this:
# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.* /dev/console

# Log anything (except mail) of level info or higher.


# Don't log private authentication messages!
*.info;mail.none;news.none;authpriv.none;cron.none /var/log/messages

# The authpriv file has restricted access.


authpriv.* /var/log/secure

# Log all the mail messages in one place.


mail.* /var/log/maillog

# Log cron stuff


cron.* /var/log/cron

# Everybody gets emergency messages


*.emerg *

# Save news errors of level crit and higher in a special file.


uucp,news.crit /var/log/spooler
Linux System and Networking Administration 245

# Save boot messages also to boot.log


local7.* /var/log/boot.log

#
# INN
#
news.=crit /var/log/news/news.crit
news.=err /var/log/news/news.err
news.notice /var/log/news/news.notice
The lines beginning with a # character are comments. Other lines contain two columns of
information, separated by colons (spaces won't work). The left field is a semicolon-
separated list of message types and message priorities. The right field is the log file to
which those messages should be written. To send the messages to another computer (the
loghost) instead of a file, simply replace the log file name with the @ character followed by
the name of the loghost. For example, to redirect the output normally sent to the
messages, secure, and maillog log files, make these changes to the above file:
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;news.none;authpriv.none;cron.none @loghost

# The authpriv file has restricted access.


authpriv.* @loghost

# Log all the mail messages in one place.


mail.* @loghost
The messages will now be sent to the syslogd running on the computer named loghost.
The name loghost was not an arbitrary choice. It is customary to create such a host name
and make it an alias to the actual system acting as the loghost. That way, if you ever need
to switch the loghost duties to a different machine, you only need to change the loghost
alias; you do not need to reedit the syslog.conf file on every computer.

Understanding the Messages logfile

Because of the many programs and services that record information to the messages
logfile, it is important that you understand the format of this file. Examining this file will
often give you a good early warning of problems developing on your system. Each line in
the file is a single message recorded by some program or service. Here is a snippet of an
actual messages log file:
Feb 25 11:04:32 toys network: Bringing up loopback interface: succeeded
Feb 25 11:04:35 toys network: Bringing up interface eth0: succeeded
Feb 25 13:01:14 toys vsftpd(pam_unix)[10565]: authentication failure;
logname= uid=0 euid=0 tty= ruser= rhost=10.0.0.5 user=chris
Feb 25 14:44:24 toys su(pam_unix)[11439]: session opened for
user root by chris(uid=500)
246 Linux System and Networking Administration

This is really very simple when you know what to look for. Each message is divided into
five main parts. From left to right they are:

 The date and time that the message was logged


 The name of the computer that the message came from

 The program or service name that the message pertains to


 The process number (enclosed in square brackets) of the program sending the
message

 The actual text message itself


Let's examine the file snippet above. In the first two lines, you can see that I restarted the
network. The next line shows that I tried to log in as the user named chris to get to the
FTP server on this system from a computer at address 10.0.0.5 (I typed the wrong
password and authentication failed). The last line shows that I used the su command to
become root user.
By occasionally reviewing the messages file and the secure file, it is possible to catch a
cracking attempt before it is successful. If you see an excessive number of connection
attempts for a particular service, especially if they are coming from systems on the
Internet, you may be under attack.

Monitoring Log Files with LogSentry

Red Hat Linux has the ability to monitor and log nearly every activity that can occur on
your computer. On a busy system, massive amounts of informational and error messages
are produced and placed in log files. For the administrator, the hard part of monitoring log
files isn't detecting or logging security problems; the hard part is remembering to check
the log files and sift out those messages that pose a threat from all the other stuff that
gets logged. This section describes how to monitor log files with the LogSentry package.
The LogSentry package (formerly called LogCheck) is a handy tool that you can use to
easily manage your system log files. Because you're more likely to glance through an e-
mail than you are to remember to check log files, LogSentry puts information in front of
you that may otherwise go unnoticed.
LogSentry checks log files produced by the standard Linux syslog facility, attempts to filter
out messages that don't represent any security threat, and then categorizes messages that
could represent a threat and e-mails those messages to the system administrator. By
default, LogSentry will check messages in the messages, secure, and mail log files in the
/var/log directory. By changing the LogSentry configuration files, you can change which
log files are checked, how messages are filtered, and how often log-summary e-mail
messages are sent. You may also want to change which features the syslog facility
monitors and the level of syslog monitoring if you are interested in debugging a particular
system feature.

Note Recently, Red Hat added the logwatch package to the distribution. Logwatch is
configured to run once each day to monitor your log files. While logwatch is not as
comprehensive a tool as LogSentry, you can expect to see a logwatch e-mail
message produced daily that highlights any dangerous system activity that it detects.
That e-mail is sent to your computer's system administrator.

Downloading and Installing LogSentry

You can find the logsentry package at rpmfind.net and several FTP sites on the Internet.
After logsentry is downloaded, to install the package, simply run the following command
from the directory you downloaded it to:
# rpm -Uhv logsentry*
Linux System and Networking Administration 247

The LogSentry package consists of four configuration files (in the /etc/logsentry directory),
the cron file that runs logcheck.sh (in /etc/cron.d/logsentry.cron), and the logcheck.sh and
logtail commands (in /usr/sbin). There are also README files in the
/usr/share/doc/logcheck* directory.
Because there are different versions of LogSentry floating around on the Web, including
older versions named logcheck, the locations of commands and instructions for using
LogSentry may be different from what I describe here. For example, the original logcheck
package may include a logcheck.sh script in /usr/bin for running logcheck. The logsentry
package used here is logsentry-1.1.1-1.i686.rpm.

Setting up LogSentry

You don't have to do anything to get LogSentry working. After LogSentry is installed, it
runs once a day at midnight. The results are then e-mailed to the root user on the local
host computer. There are several things you can do, however, to tailor LogSentry to suit
your particular needs.

Running LogSentry

When you install the logsentry package, a script named logsentry.cron is placed in the
/etc/cron.d directory. In this case, the /etc/cron.d/logsentry.cron script simply runs the
/usr/sbin/logcheck.sh script.
Because the logsentry.cron script runs hourly, this means that you (or the administrator)
will receive 24 e-mail messages each day, each containing the filtered log messages. You
can create your own cron script to have the logcheck.sh launched on any schedule you
like.

Note The /usr/sbin/logcheck.sh script uses the /usr/sbin/logtail command to gather only
those log messages that you haven't already seen. The logtail command does this by
creating a .offset file for each log file that Logcheck monitors. The next time Logcheck
is run, only log messages that have arrived since the previous run are checked.

Using LogSentry

After LogSentry has been set up and run, to begin using LogSentry you start by simply
reading the e-mail that LogSentry sends you. By default, the root user on your Red Hat
Linux system will receive an e-mail message from LogSentry each hour. Log messages
that are matched, and not excluded, are sorted under one of the following three headings
in each e-mail message:

 Active System Attack Alerts: Represents messages that may represent an


attack on your system.

 Security Violations: Includes failures and violations that may indicate a


problem, but not necessarily an attack on your system.
 Unusual System Events: Includes all log messages that are neither matched
nor excluded.
The following is an example of a LogSentry e-mail message.
Return-Path: <root@localhost.localdomain>Received: (from root@localhost)
Subject: maple 11/06/03:19.01 ACTIVE SYSTEM ATTACK!
Status: R

Active System Attack Alerts


=-=-=-=-=-=-=-=-=-=-=-=-=-=
248 Linux System and Networking Administration

Nov 6 18:02:28 maple portsentry[1102]: attackalert: Possible stealth


scan from unknown host to TCP port: 111 (accept failed)
Nov 6 18:33:26 maple sendmail[1863]: f371XJw01863: "wiz" command from
duck.handsonhistory.com [10.0.0.28] (127.0.0.1)
Nov 6 18:33:29 maple sendmail[1863]: f371XJw01863: "debug" command from
duck.handsonhistory.com [10.0.0.28] (127.0.0.1)

Security Violations
=-=-=-=-=-=-=-=-=-=
Nov 6 18:02:28 maple portsentry[1102]: attackalert: Possible stealth
scan from unknown host to TCP port: 111 (accept failed)
Nov 6 18:39:14 maple -- root[1121]: ROOT LOGIN ON tty1

Unusual System Events


=-=-=-=-=-=-=-=-=-=-=
Nov 6 18:01:35 maple last message repeated 291877 times
Nov 6 18:14:10 maple last message repeated 297510 times
Nov 6 18:20:58 maple kernel: SB 4.16 detected OK (220)
Nov 6 18:20:58 maple kernel: SB16: Bad or missing 16 bit DMA channel
Nov 6 18:20:58 maple kernel: sb: 1 Soundblaster PnP card(s) found.
Nov 6 18:38:37 maple syslog: syslogd startup succeeded
Nov 6 18:38:37 maple kernel: klogd 1.4-0, log source = /proc/kmsg
started.
Nov 6 18:38:37 maple kernel: Inspecting /boot/System.map-2.4.2-0.1.49
In the preceding e-mail, under the Active System Attack Alerts heading, you can see that a
scan of port 111 (portmapper service) was detected by the PortSentry service. The next
two messages indicate that a user from the host duck.handsonhistory.com tried to scan
sendmail to see if debug and wiz services could be accessed. Under the Security Violations
heading, the possible stealth scan appeared again. A normal login by the root user was
also detected (although it represented no particular threat in this case).
Under the Unusual System Events heading, as noted earlier, are included all messages not
matched (specifically added to another category) or excluded (specifically ignored) by any
of the filter files. A lot of normal system-activity messages appear here. Over time, you
may want to explicitly include or exclude messages that you see all the time or that catch
your eye as a potential problem you need to watch. For example, the preceding lines that
say last message repeated 291877 times indicate a potential denial-of-service attack. You
may want to add the keywords "message repeated" to your logcheck.hacking list.
Likewise, the words "Soundblaster PnP card(s) found" could be added to the
logcheck.ignore file, because that message reflects normal processing.
In general, you want to react to attacks that you detect by preventing an attacker from
gaining access to your system. If an attacker does get in, you want to get that attacker
out of your system and clean up the damage as best you can. An excellent tool for
detecting, logging, and denying access to your system by attackers is the PortSentry
package discussed later in this chapter.
Linux System and Networking Administration 249

Configuring LogSentry to Suit Your Needs


After LogSentry is installed, it will run without requiring any configuration. However, to
better suit your needs, there are several configuration files you can modify. The following
section describes those files.
Editing the logcheck script
The /usr/sbin/logcheck.sh script scans your log files and sorts the log messages that are e -
mailed. You can change much of the behavior of the logcheck.sh script by changing the
values of the variables within the script. To change the behavior of the logcheck.sh script,
follow these steps:
1. Make a copy of the /usr/sbin/logcheck.sh file. For example:
2. # cp /usr/sbin/logcheck.sh /usr/sbin/logcheck.sh.old
3. Open the script in any text editor while logged in as the root user and make any
changes to the script. The following bullet list describes values that you may want
to change.
o SYSADMIN: This variable defines the root user as the one to receive the
e-mail messages resulting from running Logcheck. You can change root to
anyone you want to receive the LogSentry messages. This can be either
local users or users on other computers (that is, user@hostname).
SYSADMIN=root
o TMPDIR: Sets where LogSentry writes its temporary files during
processing. The directory is created when LogSentry starts and is removed
before Logcheck finishes. You can change the location by modifying the
following entry:
TMPDIR=/tmp/logcheck$$-$RANDOM
o GREP: The logcheck.sh script relies on a grep command that supports the
-i, -v, and -f options to search the log files. By default, the egrep command
is used for this purpose. You could change the value to grep or another
command by modifying the following variable:
GREP=egrep
o MAIL: E-mail is sent by LogSentry using the mail command. To have
LogSentry use a command other than the mail command to send e-mail
messages to the administrator, change the following mail variable:
MAIL=mail
o Filter files: There are four filter files defined by LogSentry. The files each
contain keywords that are either used to find messages or exclude
messages that contain those keywords. The following variables are set to
indicate the location of the four LogSentry filter files:
o HACKING_FILE=/etc/logsentry/logcheck.hacking
o VIOLATIONS_FILE=/etc/logsentry/logcheck.violations
o VIOLATIONS_IGNORE_FILE=/etc/logsentry/logcheck.violations.ignore
IGNORE_FILE=/etc/logsentry/logcheck.ignore
For more information on filter files, see the "Changing LogSentry filter files" section, later
in this chapter.
o Log files: The last entries in the /usr/sbin/logcheck.sh script that you may
want to change designate which log files are monitored by the logcheck.sh
script. By default, the script runs the logtail command to check the
messages, secure, and maillog files (in /var/log). The following lines define
which log files are checked and determine where the output of logtail is
temporarily written.
250 Linux System and Networking Administration

o $LOGTAIL /var/log/messages > $TMPDIR/check.$$


o $LOGTAIL /var/log/secure >> $TMPDIR/check.$$
$LOGTAIL /var/log/maillog >> $TMPDIR/check.$$

Tip If you like, you can have more log files checked by adding more lines like the
preceding ones. Just make sure that the first line includes a single arrow (to
overwrite a previous check file) and that all subsequent lines contain double
arrows (to append to the current check file).

Changing LogSentry Filter Files

The /etc/logsentry directory contains four filter files that define which messages are
matched and e-mailed to the administrator. The contents of these files are simply
keywords. Log files are searched (or grepped) for these keywords and sorted or discarded
based on the results of the search.
Some keyword filter files are intended to uncover words or phrases that would appear in a
log message in the event of a system break-in or misuse. Other keyword files are intended
to find messages that pose no security threat (so that the messages can be excluded from
the e-mailed log messages). Messages that match neither the included or excluded
keywords are appended to the Unusual System Events heading of the e-mail summary
output.
You can use filter files as they are. However, over time, you may want to modify these
files for several reasons. If you are receiving repetitive, non-threatening messages in the
LogSentry e-mails, you can add keywords that can filter out those messages. Also, you can
add keywords later as you learn about new types of security breaches that you may want
to look for.
Besides including alphanumeric characters, keywords can also include wildcard characters.
For example, you could use an asterisk (*) to match any string of characters, a question
mark (?) to match any single character, or a dollar sign ($) to match a keyword that
appears at the end of a line.

Caution Use wildcards carefully. A mistaken wildcard character can result in too many or
too few messages being included or excluded.

The four LogSentry filter files in the /etc/logsentry directory are:

 logcheck.hacking: Contains keywords that appear in log messages that


represent known hacking attacks.

 logcheck.ignore: Contains keywords that represent messages that should


always be ignored.
 logcheck.violations: Contains keywords that represent negative activities that
may or may not represent real intrusions on your system.

 logcheck.violations.ignore: Contains keywords that represent messages that


should be ignored from those found as part of the violations check.
Each of these files is described in the following sections.

Note It is important to note that messages that are neither explicitly matched (from
logcheck.hacking and logcheck.violations) nor explicitly excluded (from
logcheck.ignore and logcheck.violations.ignore) are included in the e-mail sent by
Logcheck to the administrator. Those messages are displayed under the catchall
heading Unusual System Events.
Linux System and Networking Administration 251

logcheck.hacking

Keywords from the /etc/logsentry/logcheck.hacking file are meant to uncover log


messages representing attacks on your system. Log messages that are matched by
keywords in this file are output in e-mail messages to your system administrator under the
logcheck.hacking heading.
Messages that appear under this heading are the first messages to appear in the e-mail
message. You can add other keywords to this file as you learn about messages that
represent different types of attacks on your system.
Following are some examples of keywords that appear in the logcheck.hacking file:

"wiz"
"WIZ"
"debug"
"DEBUG"
ATTACK
nested
VRFY bbs
VRFY decode
VRFY uudecode
rlogind.*: Connection from .* on illegal port
rshd.*: Connection from .* on illegal port
sendmail.*: user .* attempted to run daemon
uucico.*: refused connect from .*
tftpd.*: refused connect from .*
login.*: .*LOGIN FAILURE.* FROM .*root
login.*: .*LOGIN FAILURE.* FROM .*guest

Most of the messages in this file are used to match log messages that result from someone
probing your system with the Internet Security Scanner (ISS). ISS is a tool that can scan a
set of IP addresses for potential security weaknesses. Though most of the security holes
ISS checks for have been plugged over time, these log messages alert you to the fact that
someone is checking the security of your system.
The debug and wiz keywords shown in the above file will catch attempts by ISS to access
wiz and debug services from the sendmail service. Likewise, VRFY is a command that ISS
sends to requests of the sendmail service to ask for different user names. Other keyword
phrases shown in the previous example match failed attempts to connect using different
Linux network services (such as rlogind, rshd, sendmail, uucico, and so on).

logcheck.ignore

Keywords in the /etc/logsentry/logcheck.ignore file are used to find log messages that
should be excluded (that is, ignored) by LogSentry and will therefore not appear in e-mail
summaries. The keywords in this file reduce the number of log messages that are e -mailed
to the administrator, making it easier to find the real problems. The following are some
examples of keywords from the logcheck.ignore file.
cron.*CMD
cron.*RELOAD
cron.*STARTUP
252 Linux System and Networking Administration

ftp-gw.*: exit host


ftp-gw.*: permit host
ftpd.*ANONYMOUS FTP LOGIN
http-gw.*: exit host
http-gw.*: permit host
identd.*Successful lookup
identd.*from:
named.*Response from
Most of the entries in this file are used to match messages that represent the normal
operation of various system services. The keywords shown in the previous example
represent normal processing of cron, ftp, http, identd, and named features.
Notice that all of the keyword phrases shown in the preceding example include an asterisk
(*) wildcard. If you add your own keywords to this file, using asterisks and other wildcards
can help you be specific about the log messages you exclude.

logcheck.violations

There are certain words that imply negative behavior occurring on your computer. Though
these words may not be associated with any particular attack, LogSentry notes messages
containing these words and displays them under the following heading and e-mails them to
the system administrator:
Security Violations
=-=-=-=-=-=-=-=-=-=

The following is an example of some of the keywords that appear in the logcheck.violations
file:
 ATTACK
 BAD
 DEBUG
 FAILURE
 ILLEGAL
 REFUSED
 denied
 failed
 unapproved
 attackalert
Adding your own keywords to the file can help flag log messages that may be of particular
concern for your computer. For example, you can add keywords that represent improper
use of services that are not standard Linux features but can be accessed from the network.
logcheck.violations.ignore
Use the logcheck.violations.ignore file to exclude messages that were matched from the
logcheck.violations file, but are known to not represent security problems. By default, only
the following entry is contained in this file:
stat=Deferred
Linux System and Networking Administration 253

The previous keyword causes LogSentry to ignore log messages from sendmail that
represent e-mail messages that haven't been sent because the receiving server was
temporarily unavailable. As you use LogSentry, you are likely to repeatedly encounter
certain log messages that represent no security threat. Add keywords here (specifically as
possible) to exclude those messages from appearing continuously in e-mail messages from
LogSentry.
Modifying syslog
The syslog service gathers the log messages of system activity that are used by
LogSentry. Red Hat Linux, as well as most other Linux and UNIX systems, comes with
syslog installed and operational by default. You can modify the /etc/syslog.conf file to
tailor the behavior of syslog to best suit the way you use your system.
The syslog service is part of the sysklogd software package. To make sure that sysklogd is
installed, type the following at a shell prompt:
# rpm -q sysklogd
The syslogd service is started automatically from the /etc/init.d/syslog start-up script.
After that script has been run on your system, two daemon processes should be active on
your system: syslogd and klogd. To see if they are running, type the following:
# ps -ax | grep log
The /etc/syslog.conf file contains information that defines which activities are logged, and
from which system. LogSentry monitors three of the log files created by syslog (in the
/var/log directory): messages, secure, and maillog. The following lines in the
/etc/syslog.conf file instruct syslog to create those log files:
*.info;mail.none;news.none;authpriv.none;cron.none /var/log/messages
authpriv.* /var/log/secure
mail.* /var/log/maillog
Services on your Red Hat Linux system produce messages of different levels. Message
levels, from most critical to least critical, are listed in the following table.

Level What it Means

alert immediate action needed

crit Critical

debug detailed processing information

emerg system unusable

err error condition

info purely informational

notice important, but not an error

warning potential error

The line shown in the example indicates that all messages from the info level (*.info) and
above are logged to the /var/log/messages file. However, messages of types mail, news,
authpriv, and cron are excluded because they are sent to other log files. All authpriv
(authpriv.*) messages are logged to the /var/log/secure file. mail messages (mail.*) are
all logged to the /var/log/maillog file.
254 Linux System and Networking Administration

With this default configuration of syslog, LogSentry should catch all major security related
activities. There are a few situations, however, where you may want to modify the
/etc/syslog.conf file. For example, if you are receiving a lot of log messages for a particular
type of service (such as ppp if you are having trouble with a dial-up connection), you may
consider directing messages for that service to its own log file. Then, if LogSentry uncovers
a problem, it's easier to go through only that log file for those messages relating to the
problem service.
Another temporary change you may consider is if you need to debug a problem with your
system. Changing *.info to *.debug temporarily can give you more details on a problem.
(Make sure to change it back later, or syslog will chew up too much system resources.)

Using Password Protection


Passwords are the most fundamental security tool of any modern operating system and
consequently, the most commonly attacked security feature. It is natural to want to
choose a password that is easy to remember, but very often this means cho osing a
password that is also easy to guess. Crackers know that on any system with more than a
few users, at least one person is likely to have an easily guessed password.
By using the "brute force" method of attempting to log in to every account on the s ystem
and trying the most common passwords on each of these accounts, a persistent cracker
has a good shot of finding a way in. Remember that a cracker will automate this attack, so
thousands of login attempts are not out of the question. Obviously, choosing good
passwords is the first and most important step to having a secure system.
Here are some things to avoid when choosing a password:
 Do not use any variation of your login name or your full name. Even if you use
varied case, append or prepend numbers or punctuation, or type it backwards, this
will still be an easily guessed password.
 Do not use a dictionary word, even if you add numbers or punctuation to it.
 Do not use proper names of any kind.
 Do not use any contiguous line of letters or numbers on the keyboard (such as
"qwerty" or "asdfg").
Choosing good passwords
A good way to choose a strong password is to take the first letter from each word of an
easily remembered sentence. The password can be made even better by adding numbers,
punctuation, and varied case. The sentence you choose should have meaning only to you,
and should not be publicly available (choosing a sentence on your personal Web page is a
bad idea). The following table lists examples of strong passwords and the tricks used to
remember them.

Password How to Remember it

Mrci7yo! My rusty car is 7 years old!

2emBp1ib 2 elephants make BAD pets, 1 is better

ItMc?Gib Is that MY coat? Give it back

The passwords look like gibberish, but are actually rather easy to remember. As you can
see, I can place emphasis on words that stand for capital letters in the password. You set
your password using the passwd command. Type the passwd command within a command
shell, and it will enable you to change your password. First, it will prompt you to enter
Linux System and Networking Administration 255

your old password. To protect against someone "shoulder surfing" and learning your
password, the password will not be displayed as you type.
Assuming you type your old password correctly, the passwd command will prompt you for
the new password. Once you type in your new password, the passwd command checks the
password against cracklib to determine if it is a good or bad password. Non-root users will
be required to try a different password if the one they have chosen is not a good
password. The root user is the only user who is permitted to assign bad passwords. Once
the password has been accepted by cracklib, the passwd command will ask you to enter
the new password a second time to make sure there are no typos (which are hard to
detect when you can't see what you are typing). When running as root, it is possible to
change a user's password by supplying that user's login name as a parameter to the
passwd command. Typing this:
# passwd joe
results in the passwd command prompting you for joe's new password. It does not prompt
you for his old password in this case. This allows root to reset a user's password when that
user has forgotten it (an event that happens all too often).

Using a Shadow Password File

In early versions of UNIX, all user account and password information was stored in a file
that all users could read (although only root could write to it). This was generally not a
problem because the password information was encrypted. The password was encrypted
using a trapdoor algorithm, meaning the non-encoded password could be encoded into a
scrambled string of characters, but the string could not be translated back to the non-
encoded password.
How does the system check your password in this case? When you log in, the system
encodes the password you entered, compares the resulting scrambled string with the
scrambled string that is stored in the password file, and grants you access only if the two
match. Have you ever asked a system administrator what the password on your account is
only to hear, "I don't know" in response? If so, this is why: The administrator really
doesn't have the password, only the encrypted version. The non -encoded password exists
only at the moment you type it.
Breaking encrypted passwords
There is a problem with people being able to see encrypted passwords, however. Although
it may be difficult (or even impossible) to reverse the encryption of a trapdoor algorithm, it
is very easy to encode a large number of password guesses and compare them to the
encoded passwords in the password file. This is, in orders of magnitude, more efficient
than trying actual login attempts for each user name and password. If a cracker can get a
copy of your password file, the cracker has a much better chance of breaking into your
system.
Fortunately, Linux and all modern UNIX systems support a shadow password file by
default. The shadow file is a special version of the passwd file that only root can read. It
contains the encrypted password information, so passwords can be left out of the passwd
file, which any user on the system can read. Linux supports both the older, single
password file method as well as the newer shadow password file. You should always use
the shadow password file (it is used by default).
Checking for the shadow password file
The password file is named passwd and can be found in the /etc directory. The shadow
password file is named shadow and is also located in /etc. If your /etc/shadow file is
missing, then it is likely that your Linux system is storing the password information in the
/etc/passwd file instead. Verify this by displaying the file with the less command.
# less /etc/passwd
Something similar to the following should be displayed:

root:DkkS6Uke799fQ:0:0:root:/root:/bin/bash
256 Linux System and Networking Administration

bin:*:1:1:bin:/bin:
daemon:*:2:2:daemon:/sbin:
.
.
.
mary:KpRUp2ozmY5TA:500:100:Mary Smith:/home/mary:/bin/sh
joe:0sXrzvKnQaksI:501:100:Joe Johnson:/home/joe:/bin/sh
jane:ptNoiueYEjwX.:502:100:Jane Anderson:/home/jane:/bin/sh
bob:Ju2vY7A0X6Kzw:503:100:Bob Renolds:/home/bob:/bin/sh

Each line in this listing corresponds to a single user account on the Linux system. Each line
is made up of seven fields separated by colon (:) characters. From left to right the fields
are the login name, the encrypted password, the user ID, the group ID, the description,
the home directory, and the default shell. Looking at the first line, you see that it is for the
root account and has an encrypted password of DkkS6Uke799fQ. We can also see that root
has a user ID of zero, a group ID of zero, and a home directory of /root, and root's default
shell is /bin/sh.
All of these values are quite normal for a root account, but seeing that encrypted password
should set off alarm bells in your head. It confirms that your system is not using the
shadow password file. At this point, you should immediately convert your password file so
that it uses /etc/shadow to store the password information. You do this by using the
pwconv command. Simply log in as root (or use the su command to become root) and
enter the pwconv command at a prompt. It will print no messages, but when your shell
prompt returns, you should have a /etc/shadow file and your /etc/passwd file should now
look like this:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:
daemon:x:2:2:daemon:/sbin:
.
.
.
mary:x:500:100:Mary Smith:/home/mary:/bin/sh
joe:x:501:100:Joe Johnson:/home/joe:/bin/sh
jane:x:502:100:Jane Anderson:/home/jane:/bin/sh
bob:x:503:100:Bob Renolds:/home/bob:/bin/sh
Encrypted password data is replaced with an x. Password data moved to /etc/shadow.

There is also a screen-oriented command called authconfig that you can use to manage
shadow passwords and other system authentication information. This tool also has
features that let you work with MD5 passwords, LDAP authentication, or Kerberos 5
authentication as well. Type authconfig and step through the screens to use it.
To work with passwords for groups, you can use the grpconv command to convert
passwords in /etc/groups to shadowed group passwords in /etc/gshadow. If you change
passwd or group passwords and something breaks (you are unable to log in to the
accounts), you can use the pwunconv and grpunconv commands, respectively, to reverse
password conversion.
So, now you are using the shadow password file and picking good passwords. You have
made a great start toward securing your system. You may also have noticed by now that
security is not just a one-time job. It is an ongoing process, as much about policies as
programs. Keep reading to learn more.
Linux System and Networking Administration 257

Using Encryption Techniques


The previous sections told you how to lock the doors to your Red Hat Linux system to deny
access to crackers. The best dead bolt lock, however, is useless if you are mugged in your
own driveway and have your keys stolen. Likewise, the best computer security can be for
naught if you are sending passwords and other critical data unprotected across the
Internet.
A savvy cracker can use a tool called a protocol analyzer or a network sniffer to peek at
the data flowing across a network and pick out passwords, credit card data, and other juicy
bits of information. The cracker does this by breaking into a poorly protected system on
the same network and running software, or by gaining physical access to the same
network and plugging in his or her own equipment.
You can combat this sort of theft by using encryption. The two main types of encryption in
use today are symmetric cryptography and public-key cryptography.

Symmetric Cryptography

Symmetric cryptography, also called private-key cryptography, uses a single key to both
encrypt and decrypt a message. This method is generally inappropriate for securing data
that is expected to be utilized by a third party, due to the complexity of secure key
exchange. Symmetric cryptography is generally useful for encrypting data for one's own
purposes.
A classic use of symmetric cryptography is for a personal password vault. Anyone who has
been using the Internet for any amount of time has accumulated a quantity of user names
and passwords for accessing various sites and resources. A personal password vault lets
you store this access information in an encrypted form. The end result is that you only
have to remember one password to unlock all of your access information.
Until recently, the United States government was standardized on a symmetric encryption
algorithm called DES (Data Encryption Standard) to secure important information. Because
there is no direct way to crack DES encrypted data, to decrypt DES encrypted data without
a password you would have to use an unimaginable amount of computing power to try to
guess the password. This is also known as the brute force method of decryption.
As personal computing power has increased nearly exponentially, the DES algorithm has
had to be retired. In its place, after a very long and interesting search, the United States.
government has accepted the Rijndael algorithm as what it calls the AES (Advanced
Encryption Standard). Although the AES algorithm is also subject to brute force attacks, it
requires significantly more computing power to crack than the DES algorithm does.

Public-key Cryptography

Public-key cryptography does not suffer from key distribution problems, and that is why it
is the preferred encryption method for secure Internet communication. This method uses
two keys, one to encrypt the message and another to decrypt the message. The key used
to encrypt the message is called the public key because it is made available for all to see.
The key used to decrypt the message is the private key and is kept hidden. The entire
process works like this:
Imagine that you want to send me a secure message using public-key encryption. Here is
what we need:
1. I must have a public and private key pair. Depending on the circumstances, I may
generate the keys myself (using special software) or obtain the keys from a key
authority.
2. You wish to send me a message, so you first look up my public key (or more
accurately, the software you are using looks it up).
258 Linux System and Networking Administration

3. You encrypt the message with the public key. At this point, the message can only
be decrypted with the private key (the public key cannot be used to decrypt the
message).
4. I receive the message and use my private key to decrypt it.

Secure Socket Layer

A classic implementation of public-key cryptography is with SSL (secure socket layer)


communication. This is the technology that enables you to securely submit your credit card
information to an online merchant. The elements of an SSL encrypted session are as
follows:
 SSL Enabled Web Browser (Mozilla, Internet Explorer, Opera, Konquerer, etc.)

 SSL Enabled Web Server (Apache)


 SSL Certificate
To initiate an SSL session, a Web browser first makes contact with a Web server on port
443, also known as the HTTPS port (Hypertext Transport Protocol Secure). Once a socket
connection has been established between the two machines, the following occurs:
1. Server sends SSL certificate to browser.
2. Browser verifies identity of server through SSL certificate.
3. Browser generates symmetric encryption key.
4. Browser uses SSL certificate to encrypt symmetric encryption key.
5. Browser sends encrypted key to the server.
6. Server decrypts the symmetric key with its private key counterpart of the public
SSL certificate.
7. Browser and server can now encrypt and decrypt traffic based on a common
knowledge of the symmetric key.
Secure data interchange can now occur.

Creating SSL Certificates

In order to create your own SSL certificate for secure HTTP data interchange, you must
first have an SSL-capable Web server. The Apache Web server (httpd package), which
comes with Red Hat Linux, is SSL-capable. Once you have a server ready to go, you should
familiarize yourself with the important server-side components of an SSL certificate:

# ls -l /etc/httpd/conf
drwxr-xr-x 7 root root 4096 Aug 12 23:45 .
drwxr-xr-x 4 root root 4096 Aug 13 00:23 ..
-rw-r--r-- 1 root root 35918 Jul 14 15:45 httpd.conf
lrwxrwxrwx 1 root root 37 Aug 12 23:45 Makefile ->
../../../usr/share/ssl/certs/Makefile
drwx------ 2 root root 4096 Aug 12 23:45 ssl.crl
drwx------ 2 root root 4096 Aug 12 23:45 ssl.crt
drwx------ 2 root root 4096 Jul 14 15:45 ssl.csr
drwx------ 2 root root 4096 Aug 12 23:45 ssl.key
drwx------ 2 root root 4096 Jul 14 15:45 ssl.prm
Linux System and Networking Administration 259

# ls -l /etc/httpd/conf.d/ssl.conf
-rw-r--r-- 1 root root 11140 Jul 14 15:45 ssl.conf
The /etc/httpd/conf and /etc/httpd/conf.d directories contains all of the components
necessary to create your SSL certificate. Each component is defined as follows:

 httpd.conf — Web server configuration file.


 Makefile — Certificate building script.

 ssl.crl — Certificate revocation list directory.

 ssl.crt — SSL certificate directory.


 ssl.csr — Certificate service request directory.

 ssl.key — SSL certificate private key directory.


 ssl.prm — SSL certificate parameters.
 ssl.conf — Primary Web server SSL configuration file.
Now that you're familiar with the basic components, take a look at the tools used to create
SSL certificates:
# cd /etc/httpd/conf
# make
This makefile allows you to create:
o public/private key pairs
o SSL certificate signing requests (CSRs)
o self-signed SSL test certificates

To create a key pair, run "make SOMETHING.key".


To create a CSR, run "make SOMETHING.csr".
To create a test certificate, run "make SOMETHING.crt".
To create a key and a test certificate in one file, run "make
SOMETHING.pem".

To create a key for use with Apache, run "make genkey".


To create a CSR for use with Apache, run "make certreq".
To create a test certificate for use with Apache, run "make testcert".

Examples:
make server.key
make server.csr
make server.crt
make stunnel.pem
make genkey
make certreq
make testcert
260 Linux System and Networking Administration

The make command utilizes the Makefile to create SSL certificates. Without any arguments
the make command simply prints the information listed above. The following defines each
argument you can give to make:

 make server.key — Creates generic public/private key pairs.


 make server.csr — Generates a generic SSL certificate service request.

 make server.crt — Generates a generic SSL test certificate.


 make stunnel.pem — Generates a generic SSL test certificate, but puts the
private key in the same file as the SSL test certificate.
 make genkey — Same as make server.key except it places the key in the ssl.key
directory.

 make certreq — Same as make server.csr except it places the certificate service
request in the ssl.csr directory.
 make testcert — Same as make server.crt except it places the test certificate in
the ssl.crt directory.

Using third-party certificate signers

In the real world, I know who you are because I recognize your face, your voice and your
mannerisms. On the Internet, I cannot see these things and must rely on a trusted third
party to vouch for your identity. To ensure that a certificate is immutable, it has to be
signed by a trusted third party when the certificate is issued and validated every time an
end user taking advantage of your secure site loads it. The following is a list of the trusted
third-party certificate signers:

 GlobalSign — https://www.globalsign.net/
 Baltimore — https://www.baltimore.com/

 GeoTrust — https://www.geotrust.com/
 VeriSign — https://www.verisign.com/

 FreeSSL — http://www.freessl.com/
 Thawte — http://www.thawte.com/

 EnTrust — http://www.entrust.com/

 ipsCA — http://www.ipsca.com/
 COMODO Group — http://www.comodogroup.com/
Each of these certificate authorities has gotten a chunk of cryptographic code embedded
into nearly every Web browser in the world. This chunk of cryptographic code allows a Web
browser to determine whether or not an SSL certificate is authentic. Without this
validation, it would be trivial for crackers to generate their own certificates and dupe
people into thinking they are giving sensitive information to a reputable source.
Certificates that are not validated are called self-signed certificates. If you come across a
site that has not had its identity authenticated by a trusted third party, your Web browser
will display a message similar to the one shown in the following figure.
Linux System and Networking Administration 261

Fig - A pop-up window alerts you when a site is not authenticated.


This does not necessarily mean that you are encountering anything illegal, immoral or
fattening. Many sites opt to go with self-signed certificates, not because they are trying to
pull a fast one on you, but because there may not be any reason to validate the true
owner of the certificate and they do not wish to pay the cost of getting a certificate
validated. Some reasons for a using a self-signed certificate include:
 The Web site accepts no input. In this case, you as the end user, have nothing
to worry about. There is no one trying to steal your information because you aren't
giving out any information. Most of the time this is done simply to secure the Web
transmission from the server to you. The data in and of itself may not be sensitive,
but, being a good netizen, the site has enabled you to secure the transmission to
keep third parties from sniffing the traffic.
 The Web site caters to a small clientele. If you run a Web site that has a very
limited set of customers, such as an Application Service Provider, you can simply
inform your users that you have no certificate signer and that they can browse the
certificate information and validate it with you over the phone or in person.
 Testing. It makes no sense to pay for an SSL certificate if you are only testing a
new Web site or Web-based application. Use a self-signed certificate until you are
ready to go live.

Creating a Certificate Service Request

To create a third party validated SSL certificate, you must first start with a CSR (Certificate
Service Request). To create a CSR, do the following on your Web server:
# cd /etc/httpd/conf
# make certreq
umask 77 ; \
/usr/bin/openssl genrsa -des3 1024 > /etc/httpd/conf/ssl.key/server.key
.
.
.
You will now be asked to enter a password to secure your private key. This password
should be at least eight characters long, and should not be a dictionary word or contain
numbers or punctuation. The characters you type will not appear on the screen, in order to
prevent someone from shoulder surfing your password.
262 Linux System and Networking Administration

Enter pass phrase:


Enter the password once again to verify.
Verifying - Enter pass phrase:
The certificate generation process now begins.
At this point, it is time to start adding some identifying information to the certificate that
the third party source will later validate. Before you can do this, you must unlock the
private key you just created. Do so by typing the password you typed above. Then enter
information as you are prompted. An example of a session for adding information for your
certificate is shown below:
Enter pass phrase for /etc/httpd/conf/ssl.key/server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called
a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:US
State or Province Name (full name) [Berkshire]: Connecticut
Locality Name (eg, city) [Newbury]: Mystic
Organization Name (eg, company) [My Company Ltd]:Acme Marina, Inc.
Organizational Unit Name (eg, section) []:InfoTech
Common Name (eg, your name or your server's hostname)
[]:www.acmemarina.com
Email Address []: webmaster@acmemarina.com
To complete the process, you will be asked if you want to add any extra attributes to your
certificate. Unless you have a reason to provide more information, you should simply hit
enter at each of the following prompts to leave them blank.
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Getting the CSR Signed

Once your CSR has been created, you now need to send it to a signing authority for
validation. The first step in this process is to select a signing authority. Each signing
authority has different deals, prices and products.
The following are areas where signing authorities differ:
 Credibility and stability
 Pricing

 Browser recognition
Linux System and Networking Administration 263

 Warranties

 Support
 Certificate strength
Once you have selected your certificate signer, you will have to go through some validation
steps. Each signer has a different method of validating identity and certificate information.
Some require that you fax articles of incorporation, while others require a company officer
be made available to talk to a validation operator. At some point in the process you will be
asked to copy and paste the contents of the CSR you created into the signer's Web form.
# cd /etc/httpd/conf/ssl.csr
# cat server.csr
-----BEGIN CERTIFICATE REQUEST-----
MIIB6jCCAVMCAQAwgakxCzAJBgNVBAYTAlVTMRQwEgYDVQQIEwtDb25uZWN0aWN1
dDEPMA0GA1UEBxMGTXlzdGljMRowGAYDVQQKExFBY21lIE1hcmluYSwgSW5jLjER
MA8GA1UECxMISW5mb1RlY2gxGzAZBgNVBAMTEnd3dy5hY21lbWFyaW5hLmNvbTEn
MCUGCSqGSIb3DQEJARYYd2VibWFzdGVyQGFjbWVtYXJpbmEuY29tMIGfMA0GCSqG
SIb3DQEBAQUAA4GNADCBiQKBgQDcYH4pjMxKMldyXRmcoz8uBVOvwlNZHyRWw8ZG
u2eCbvgi6w4wXuHwaDuxbuDBmw//Y9DMI2MXg4wDq4xmPi35EsO1Ofw4ytZJn1yW
aU6cJVQro46OnXyaqXZOPiRCxUSnGRU+0nsqKGjf7LPpXv29S3QvMIBTYWzCkNnc
gWBwwwIDAQABoAAwDQYJKoZIhvcNAQEEBQADgYEANv6eJOaJZGzopNR5h2YkR9Wg
l8oBl3mgoPH60Sccw3pWsoW4qbOWq7on8dS/++QOCZWZI1gefgaSQMInKZ1II7Fs
YIwYBgpoPTMC4bp0ZZtURCyQWrKIDXQBXw7BlU/3A25nvkRY7vgNL9Nq+7681EJ8
W9AJ3PX4vb2+ynttcBI=
-----END CERTIFICATE REQUEST-----
You can use your mouse to copy and paste the CSR into the signer's Web form.
Once you have completed the information validation, paid for the signing and answered all
of the questions, you have completed most of the process. Within 48 to 72 hours you
should receive an e-mail with your shiny new SSL certificate in it. The certificate will look
similar to the following:
-----BEGIN CERTIFICATE-----
MIIEFjCCA3+gAwIBAgIQMI262Zd6njZgN97tJAVFODANBgkqhkiG9w0BAQQFADCB
ujEfMB0GA1UEChMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazEXMBUGA1UECxMOVmVy
aVNpZ24sIEluXy4xMzAxBgNVBAsTKlZlcmlTaWduIEludGVybmF0aW9uYWwgU2Vy
dmVyIENBIC0gZ2xhc3MgMzFJMEcG10rY2g0Dd3d3LnZlcmlzaWduLmNvbS9DUFMg
SW5jb3JwLmJ51FJlZi4gTElBQklMSVRZIExURC4oYyk5NyBWZXJpU2lnbjAeFw0w
MzAxMTUwMDAwMDBaFw0wNDAxMTUyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzETMBEG
A1UECBMKV2FzaG1uZ3RvHiThErE371UEBxQLRmVkZXJhbCBXYXkxGzAZBgNVBAoU
EklETSBTZXJ2aWMlcywgSW5jLjEMMAoGA1UECxQDd3d3MTMwMQYDVQQLFCpUZXJt
cyBvZiB1c2UgYXQgd3d3LnZlcmlzawduLmNvbS9ycGEgKGMpMDAxFDASBgNVBAMU
C2lkbXNlcnYuY29tMIGfMA0GCSqGS1b3DQEBAQUAA4GNADCBiQKBgQDaHSk+uzOf
7jjDFEnqT8UBa1L3yFILXFjhj3XpMXLGWzLmkDmdJjXsa4x7AhEpr1ubuVNhJVI0
FnLDopsx4pyr4n+P8FyS4M5grbcQzy2YnkM2jyqVF/7yOW2pDl30t4eacYYaz4Qg
q9pTxhUzjEG4twvKCAFWfuhEoGu1CMV2qQ1DAQABo4IBJTCCASEwCQYDVR0TBAIw
264 Linux System and Networking Administration

ADBEBgNVHSAEPTA7MDkGC2CGSAGG+EUBBxcDMCOwKAYIKwYBBQUHAgEWHGh0dHBz
Oi8vd3d3LnZlcmlzaWduLmNvbS9ycGEwCwYDVRRPBAQDAgWgMCgGA1UdJQQhMB8G
CWCGSAGG+EIEM00c0wIYBQUHAwEGCCsGAQUFBwmCMDQGCCsGAQUFBwEBBCgwJjAk
BggrBgEFBQcwAYYYaHR0cDovL29jc2AudmVyaXNpZ24uY29tMEYGA1UdHwQ/MD0w
O6A5oDeGNWh0dHA6Ly9jcmwudmVyaxNpZ24uY29tL0NsYXNzM0ludGVybmF0aW9u
YWxTZXJ2ZXIuY3JsMBkGCmCGSAgG+E+f4Nfc3zYJODA5NzMwMTEyMA0GCSqGSIb3
DQEBBAUAA4GBAJ/PsVttmlDkQai5nLeudLceb1F4isXP17B68wXLkIeRu4Novu13
8lLZXnaR+acHuCkW01b3rQPjgv2y1mwjkPmC1WjoeYfdxH7+Mbg/6fomnK9auWAT
WF0iFW/+a8OWRYQJLMA2VQOVhX4znjpGcVNY9AQSHm1UiESJy7vtd1iX
-----END CERTIFICATE-----
Copy and paste this certificate into an empty file called server.crt, which must reside in the
/etc/httpd/conf/ssl.crt directory, and restart your Web server:
# service httpd restart
Assuming your Web site was previously working fine, you can now view it in a secure
fashion by placing an "s" after the http in the Web address. So if you previously viewed
your Web site at http://www.acmemarina.com, you can now view it in a secure fashion by
going to https://www.acmemarina.com.

Creating Self-Signed Certificates

Generating and running a self-signed SSL certificate is much easier than having a signed
certificate. To generate a self-signed SSL certificate, do the following:
1. Remove the key and certificate that currently exist:
2. # cd /etc/httpd/conf
3. # rm ssl.key/server.key ssl.crt/server.crt
4. Create your own server key:
5. # /usr/bin/openssl genrsa 1024 > ssl.key/server.key
6. Make the server.key file readable and writable only by root:
7. # chmod 600 ssl.key/server.key
8. Create the self-signed certificate by typing the following:
9. # make testcert
10. umask 77 ; \
11. /usr/bin/openssl req -new -key /etc/httpd/conf/ssl.key/server.key
12. -x509 -days 365 -out /etc/httpd/conf/ssl.key/server.crt
13. .
14. .
.
At this point, it is time to start adding some identifying information to the certificate that
the third party source will later validate. Before you can do this, you must unlock the
private key you just created. Do so by typing the password you typed above. Then follow
the sample procedure that follows:
You are about to be asked to enter information that will be incorporated into your
certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
Linux System and Networking Administration 265

There are quite a few fields but you can leave some blank For some fields there will be a
default value, If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:US
State or Province Name (full name) [Berkshire]: Ohio
Locality Name (eg, city) [Newbury]: Cincinnati
Organization Name (eg, company) [My Company Ltd]:Industrial Press, Inc.
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname)
[]:www.industrialpressinc.com
Email Address []: webmaster@industrialpressinc.com
The generation process above places all files in the proper place. All you need to do is
restart your Web server and add https instead of http in front of your URL. Don't forget,
you'll get a certificate validation message from your Web browser, which you can safely
ignore.

Restarting your Web server

By now you've probably noticed that your Web server requires you to enter your certificate
password every time it is started. This is to prevent someone from breaking into your
server and stealing your private key. Should this happen, you are safe in the knowledge
that the private key is a jumbled mess. The cracker will not be able to make use of it.
Without such protection, a cracker could get your private key and easily masquerade as
you, appearing to be legitimate in all cases.
If you just cannot stand having to enter a password every time your Web server starts,
and are willing to accept the increased risk, you can remove the password encryption on
your private key. Simply do the following:
# cd /etc/httpd/conf/ssl.key
# /usr/bin/openssl rsa -in server.key -out server.key

Troubleshooting your certificates

The following tips should help if you are having problems with your SSL certificate.
 Only one SSL certificate per IP address is allowed. If you want to add more than
one SSL enabled Web site to your server, you must bind another IP address to the
network interface.

 Make sure the permission mask on the /etc/httpd/conf/ssl.* directories and their
contents is 700 (rwx------).

 Make sure you aren't blocking port 443 on your Web server. All https requests
come in on port 443. If you are blocking it, you will not be able to get secure
pages.
 The certificate only lasts for one year. When that year is up, you have to renew
your certificate with your certificate authority. Each certificate authority has a
different procedure for doing this; check the authority's Web site for more details.
 Make sure you have the mod_ssl package installed. If it is not installed, you will
not be able to serve any SSL enabled traffic.
266 Linux System and Networking Administration

Exporting Encryption Technology

Before describing how to use the various encryption tools, I need to warn you about an
unusual policy of the United States government. For many years, the United States
government treated encryption technology like munitions. As a result, anyone wishing to
export encryption technology had to get an export license from the Commerce
Department. This applied not only to encryption software developed within the United
States, but also to software obtained from other countries and then re -exported to another
country (or even to the same country you got it from). Thus, if you installed encryption
technology on your Linux system and then transported it out of the country, you were
violating federal law! Furthermore, if you e-mailed encryption software to a friend in
another country or let him or her download it from your server, you violated the law.
In January 2000, U.S. export laws relating to encryption software were relaxed
considerably. However, often the U.S. Commerce Department's Bureau of Export
Administration requires a review of encryption products before they can be exported. U.S.
companies are also still not allowed to export encryption technology to countries classified
as supporting terrorism.

Using The Secure Shell Package

The Secure Shell package (SSH) is a package that provides shell services similar to the
rsh, rcp, and rlogin commands, but encrypts the network traffic. It uses Private-Key
Cryptography, so it is ideal for use with Internet connected computers. The Red Hat Linux
distribution contains the following client and server software packages for SSH: openssh,
openssh-client, and openssh-server packages.
Starting the SSH service
If you have installed the openssh-server software package, the SSH server is automatically
configured to start. The SSH daemon is started from the /etc/init .d/sshd start-up script. To
make sure the service is set up to start automatically, type the following (as root user):
# chkconfig --list sshd
sshd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
This shows that the sshd service is set to run in system states 2, 3, 4, and 5 (normal
bootup states) and set to be off in all other states. You can turn on the SSH service, if it is
off, for your default run state, by typing the following as root user:
# chkconfig sshd on
This line turns on the SSH service when you enter run levels 2, 3, 4, or 5. To start the
service immediately, type the following:
# /etc/init.d/sshd start

Using the ssh, sftp, and scp commands

Three commands you can use with the SSH service are ssh, sftp, and scp. Remote users
use the ssh command to login to your system securely. The scp command lets remote
users copy files to and from a system. The sftp command provides a safe way to access
FTP sites.
Like the normal remote shell services, secure shell looks in the /etc/hosts.equiv file and in
a user's .rhost file to determine whether it should allow a connection. It also looks in the
ssh-specific files /etc/shosts.equiv and .shosts. Using the shosts.equiv and the .shosts files
is preferable because it avoids granting access to the nonencrypted remote shell services.
The /etc/shosts.equiv and .shosts files are functionally equivalent to the traditional
hosts.equiv and .rhosts, so the same instructions and rules apply.
Now you are ready to test the SSH service. From another computer on which SSH has
been installed (or even from the same computer if another is not available), type the ssh
Linux System and Networking Administration 267

command followed by a space and the name of the system you are connecting to. For
example, to connect to the system ratbert.glaci.com, type:
# ssh ratbert.glaci.com
If this is the first time you have ever logged in to that system using ssh, it will ask you to
confirm that you really want to connect. Type yes and press Enter when it asks this:
Host key not found from the list of known hosts.
Are you sure you want to continue connecting (yes/no)?
It should then prompt you for a user name and password in the normal way. The
connection will then function like a normal telnet connection. The only difference is that
the information is encrypted as it travels over the network. You should now also be able to
use the ssh command to run remote commands.
The scp command is similar to the rcp command for copying files to and from Linux
systems. Here is an example of using the scp command to copy a file called memo from
the home directory of the user named jake to the /tmp directory on a computer called
maple:
$ scp /home/jake/memo maple:/tmp
passwd: ********
memo 100%|****************| 153 0:00
Enter the password for your user name (if a password is requested). If the password is
accepted, the remote system indicates that the file has been copied successfully.
Similarly, the sftp command starts an interactive FTP session with an FTP server that
supports SSH connections. Many security-conscious people prefer sftp to other ftp clients
because it provides a secure connection between you and the remote host. Here's an
example:
$ sftp ftp.handsonhistory.com
Connecting to ftp.handsonhistory.com
passwd: ********
sftp>
At this point you can begin an interactive FTP session. You can use get and put commands
on files as you would using any FTP client, but with the comfort of knowing that you are
working on a secure connection.

Tip The sftp command, as with ssh and scp, requires that the SSH service be running on
the server. If you can't connect to a FTP server using sftp, the SSH service may not be
available.

Using ssh, scp and sftp without Passwords

For machines that you use a great deal, it is often helpful to set them up so that you do
not have to use a password to log in. The following procedure shows you how to do that.
These steps will take you through setting up password-less authentication from one
machine to another. In this example, the local user is named chuckw on a computer
named host1. The remote user is also chuckw on a computer named host2.
1. Log in to the local computer (in this example, I log in as chuckw to host1).

Note Only run step 2 once as local user on your local workstation. Do not run it
again unless you lose your ssh keys. When configuring subsequent remote
servers, skip right to step 3.

2. Type the following to generate the ssh key:


268 Linux System and Networking Administration

3. $ ssh-keygen -t dsa
4. Accept the defaults by pressing Enter at each request.
5. Type the following to copy the key to the remote server (replace chuckw with the
remote user name and host2 with the remote host name):
6. $ cd ~/.ssh
7. $ scp id_dsa.pub chuckw@host2:/tmp
8. chuckw@host2's password: *******
9. Type the following to add the ssh key to the remote-user's authorization keys:
$ ssh chuck2@host2 'cat /tmp/id_dsa.pub >>
/home/chuckw/.ssh/authorized_keys2'

Note Steps 3 and 4 will ask for passwords. This is okay.

10. Type the following to remove the key from the temporary directory:
11. $ ssh chuckw@host2 /bin/rm /tmp/id_dsa.pub

Note Step 5 should not ask for a password.

It is important to note that once you have this working, it will work regardless of how
many times the IP address changes on your local computer. IP address has nothing to do
with this form of authentication.

Guarding Your Computer with PortSentry

Introduction

While LogSentry gathers and sorts log messages that may represent attempts to break
into your computer system, the PortSentry takes a more active approach to protecting
your system from network intrusions. PortSentry can be installed and configured on a Red
Hat Linux system to monitor selected TCP and UDP ports, and can then react to attempts
to access these ports (presumably by people trying to break in) in ways that you choose.
PortSentry acts as a nice complement to LogSentry by actively looking for intrusion
behavior on network ports. When PortSentry perceives an attack, it reacts to the attack (in
ways that you choose) and produces log messages about the activity that can be
forwarded to the system administrator by LogSentry.
PortSentry operates in several different modes. Each of these modes can be applied to
monitoring of TCP and UDP ports. The PortSentry modes include:

 Basic: This is the mode PortSentry uses by default. Selected UDP and TCP ports
in this mode are bound by PortSentry, giving the monitored ports the appearance
of offering a service to the network.
 Stealth: In this mode, PortSentry listens to the ports at the socket level instead
of binding the ports. This mode can detect a variety of scan techniques (strobe-
style, SYN, FIN, NULL, XMAS and UDP scans), but because it is more sensitive than
basic mode, it is likely to produce more false alarms.
 Advanced Stealth: This mode offers the same detection method as the regular
stealth mode, but instead of monitoring only the selected ports, it monitors all
ports below a selected number (port number 1023, by default). You can then
exclude monitoring of particular ports. This mode is even more sensitive than
Stealth mode and is, therefore, more likely to cause false alarms than regular
stealth mode.
Linux System and Networking Administration 269

Note When a port is "bound" by PortSentry or any other network service daemon
process, all requests that come to that port from the network are handled by
the binding process. For example, when the httpd daemon binds to port 80,
requests for Web services from the network are processed by httpd.

Besides selecting the PortSentry mode and the ports that are monitored, you can also
choose the response to your computer being scanned. By default, PortSentry can log
intrusion attempts and block access to the intruder. PortSentry also offers ways of using
other tools to respond to intrusions, including firewall rules, route changes, and host denial
configuration.

Downloading and installing PortSentry

The portsentry package is not included in the Red Hat Linux distribu tion. You can download
the package from any Red Hat Linux FTP mirror site or from the rpmfind.net site. The
portsentry package used in this chapter is portsentry-1.0-11.i386.rpm (the last version
published by Red Hat as part of the 7.1 PowerTools). After PortSentry is downloaded, run
the following command from the directory you downloaded it to:
# rpm -i portsentry*
The installed portsentry package consists of several configuration files (in the
/etc/portsentry directory), the portsentry start-up script (/etc/init.d/portsentry), and the
portsentry command (in /usr/sbin). There are also README files of interest in the
/usr/share/doc/portsentry* directory.

Using PortSentry as is

As with LogSentry, you don't need to do anything to get PortSentry to work after it is
installed. By default, here is what PortSentry does when you install the portsentry
package:

 The /etc/init.d/portsentry start-up script runs automatically when you boot to run
levels 3, 4, or 5 (levels 3 and 5 are most commonly used).
 The following port numbers are configured to be monitored by PortSentry in basic
mode:
TCP: 1, 11, 15, 143, 540, 635, 1080, 1524, 2000, 5742, 6667, 12345, 12346, 20034,
31337, 32771, 32772, 32773, 32774, 40421, 49724, 54320
UDP: 1, 513, 635, 640, 641, 700, 32770, 32771, 32772, 32773, 32774, 31337, 54321
 In response to attacks (represented by scans of the ports being monitored), all
further attempts to connect to any services for the protocol (TCP or UDP) will be
blocked.
The computers that are blocked from accessing your system are listed in either the
portsentry.blocked.tcp or portsentry.blocked.udp files (in the /var/portsentry directory),
depending on which protocol was scanned (TCP or UPD). Removing entries from these files
to restore access to blocked computers.

Configuring PortSentry

Chances are that you will want to make some changes to the way that PortSentry runs. To
change how PortSentry behaves, modify the /etc/portsentry/portsentry.conf file. In that
file, you can choose which ports to monitor, the mode in which to monitor, and the
responses to take when a scan is detected. The responses can include:
 Blocking access by the remote computer

 Rerouting messages from the remote computer to a dead host


270 Linux System and Networking Administration

 Adding a firewall rule to drop packets from the remote computer


The other file you may want to change is the /etc/portsentry/portsentry.modes. The
portsentry.modes file simply contains the modes that PortSentry can be run in.

Changing the portsentry.conf file

To edit the portsentry.conf file, as root user, open the /etc/portsentry/portsentry.conf file
using any text editor. The following sections describe the information that can be changed
in that file.

Selecting ports

The portsentry.conf file defines which ports are monitored in basic and stealth modes. By
default, only basic TCP and UDP modes are active, so only those ports are monitored
(unless you change to one of the stealth modes). The TCP_PORTS and UDP_PORTS options
define which ports are monitored. Here is how they appear in the portsentry.conf file:
TCP_PORTS="1,11,15,143,540,635,1080,1524,2000,5742,6667,12345,12346,200
34,31337,32771,32772,32773,32774,40421,49724,54320"
UDP_PORTS="1,513,635,640,641,700,32770,32771,32772,32773,32774,31337,
54321"
Unless you are a TCP/IP expert, you're probably wondering what services these ports
represent. The Internet Assigned Numbers Authority (IANA) assigns services to UDP and
TCP ports. You can see these assignments at the following Web address:
www.iana.org/assignments/port-numbers
Network services in Red Hat Linux (as well as other Linux/UNIX systems) obtain port
number assignments from the /etc/services file. So, in general, you can simply check the
/etc/services file to find out most of the services that are assigned to ports being scanned.
Ports assigned for monitoring are chosen based on a couple of different criteria. Lower port
numbers (1, 11, 15, etc.) are chosen to catch port scanners that begin at port 1 and scan
through a few hundred ports. If the scanner is blocked after accessing port 1, it won't be
able to get information about any other ports that may be open on your computer. Another
criterion is to include ports that are checked specifically by intruders because those
services may be vulnerable to attack. They include the systat (port 11) and netstat (port
15) services.
You will want to remove ports from the list in the portsentry.conf file if you are actually
running the service assigned to that port. On the other hand, you may want to add ports
to the list if you are paranoid about attacks and you want a bit more coverage. The
portsentry.conf file contains some examples that you can uncomment (remove the # sign)
so that more ports are monitored.
If you change from basic to stealth scans (as described in the "Changing the
portsentry.modes file" section, later in this chapter), the ports that are monitored are
those defined by the ADVANCED_PORTS_TCP and ADVANCED_PORTS_UDP options. Here
is how those two options are set by default:
ADVANCED_PORTS_TCP="1023"
ADVANCED_PORTS_UDP="1023"
The two preceding entries indicate that all ports from 1 to 1023 are monitored. Monitoring
higher port numbers can result in many more false alarms, so this practice is not
recommended. If you find that PortSentry is being tripped accidentally, you may want to
exclude the ports being tripped by using the ADVANCED_EXCLUDE_TCP and
ADVANCED_EXCLUDE_UDP options. The following example shows how these two values
are set by default:
ADVANCED_EXCLUDE_TCP="111,113,139"
Linux System and Networking Administration 271

ADVANCED_EXCLUDE_UDP="520,138,137,67"
By default, ident and NetBIOS services for TCP (ports 111, 113, and 139) and route,
NetBIOS, and Bootp broadcasts for UDP (ports 520, 138, 127, and 67) are excluded from
the advanced scan. (The exclusion is because a remote computer may hit these ports
without representing any misuse.) If you are running in stealth mode, you should likewise
exclude any services that you are running on your system by adding their port numbers to
this list.

Identifying configuration files

Besides the portsentry.conf file, there are several other configuration files used by
PortSentry. You can identify the locations of these other files within the portsentry.conf
file. Here are how those files are defined:
# Hosts to ignore
IGNORE_FILE="/etc/portsentry/portsentry.ignore"
# Hosts that have been denied (running history)
HISTORY_FILE="/var/portsentry/portsentry.history"
# Hosts denied this session only (temporary until next restart)
BLOCKED_FILE="/var/portsentry/portsentry.blocked"
Chances are that you will not want to move the location of these configuration files. Here
are some descriptions of what these files are used for:

 The portsentry.ignore file contains a list of all IP addresses that you do not want
blocked (even if they improperly try to access ports on your computer). By default,
all IP addresses assigned to the local computer are added to this file. You can add
IP addresses of trusted computers, if you like.

 The portsentry.history file contains a list of IP addresses for computers that have
been blocked from accessing your computer.

 The portsentry.blocked.* files contain a list of computers that have been blocked
from accessing your computer during the current session. The
portsentry.blocked.tcp file contains IP addresses of computers that have
improperly scanned TCP ports on your computer. Addresses of computers that
have been blocked after scanning UDP ports are contained in the
portsentry.blocked.udp file.
Access to ports on your computer is only blocked during the current session (that is, until
the next reboot or restart of PortSentry). So, to more permanently exclude remote
computers, you should impose other restrictions (such as by using the /etc/hosts.deny file,
a firewall command, or a reroute to a dead host). These methods are described later in
this chapter.

Choosing responses

Someone scanning a port is like them checking a door in your house to see if it is locked.
In most cases, it indicates that someone is checking your system for weaknesses. That is
why, when another computer scans your ports, the default response from PortSentry is to
block further access from the other computer to your computer for the duration of the
current session. No action is taken to permanently block access from that computer. The
BLOCK_UDP and BLOCK_TCP options in the portsentry.conf file set which type of automatic
response is taken when ports are scanned. Here is how these options are set by default:
BLOCK_UDP="2"
BLOCK_TCP="2"
272 Linux System and Networking Administration

The value in quotation marks determines how PortSentry reacts to a scan of your ports by
another computer. The following list describes each of these values.

 A value of "2" (the default value) causes access to be temporarily blocked to


services for the scanned protocol (TCP or UDP) and for the action to be logged.
Also, if any commands were defined to be run by a KILL_RUN_CMD option, that
command is then run. (This option is not configured by default.)

 A value of "0" causes port scans to be logged, but not blocked.


 A value of "1" causes the KILL_ROUTE and KILL_HOSTS_DENY options to be run.
(See the following list for descriptions of these options.) By default, further
requests from the remote computer will be rerouted to a dead host, and the
remote host's IP address will be added to the /etc/hosts.deny file, thereby denying
access to network services.
Following are some suggestions on options you can use to can change the responses to
your ports being scanned:
 KILL_ROUTE: This option runs the /sbin/route command to reroute requests
from the remote computer to a dead host. By default, this option is set to the
following value, which effectively drops the request from the remote computer:
KILL_ROUTE="/sbin/route add -host $TARGET$ gw 127.0.0.1"

Note Instead of rerouting IP packets from the remote host, you can use firewall
rules to deny access. If you use ipchains firewalls, uncomment the following
line to deny access from the remote host. If you are using iptables, change
ipchains to iptables and create an appropriate iptables response.

KILL_ROUTE="/sbin/ipchains -I input -s $TARGET$ -j DENY -l"


This ipchains rule would deny (in other words, drop) all packets from the remote
computer. To make this action permanent, you could add the ipchains options (from the -I
to the end of the line) to the /etc/sysconfig/ipchains file, replacing the $TARGET$ with the
actual IP address of the computer you want to deny access to.

 KILL_HOSTS_DENY: This option is used to deny requests for any network


services that are protected by TCP wrappers. This option is set by default as
follows:
KILL_HOSTS_DENY="ALL: $TARGET$"
With the preceding option set, $TARGET$ is replaced by the IP address of the intruding
remote computer and the line in quotes is added to the /etc/hosts.deny file. For example,
if the remote computer's IP address were 10.0.0.59, the line that appears in
/etc/hosts.deny would be:
ALL: 10.0.0.59
 KILL_RUN_CMD: Instead of using firewalls, rerouting, or TCP wrappers to deny
an intruding computer from accessing your computer, you can choose any
command you like in response. With the BLOCK_TCP and BLOCK_UDP options set
to "2", the value of KILL_RUN_CMD is run in response to a scan of your monitored
ports.
The value of KILL_RUN_CMD should be the full path to the script you want to run, plus any
options. To include the IP address of the remote computer or the port number that was
scanned, you could include the $TARGET$ or $PORT$ variables, respectively. Here is how
the example appears that you would want to modify:
KILL_RUN_CMD="/some/path/here/script $TARGET$ $PORT$"

Caution Do not use any KILL_RUN_CMD to retaliate against the intruding remote
host. Firstly, it is quite possible that the computer that is scanning your
ports has itself been cracked and is thus not a valid target for retaliations,
and secondly, retaliation may simply incite the cracker into further attacks
Linux System and Networking Administration 273

on you.

 PORT_BANNER: You can send a message to the person who sets off the
PortSentry monitor by setting the PORT_BANNER option. By default, no message is
defined. However, you can uncomment the following line to use that message. (An
abusive message is not recommended.)

 PORT_BANNER="** UNAUTHORIZED ACCESS PROHIBITED ***


YOUR CONNECTION ATTEMPT HAS BEEN LOGGED. GO AWAY."
The number of scans from an intruding computer that PortSentry will accept before setting
off the responses described above can be set by using the SCAN_TRIGGER option. By
default, that option is set as follows:
SCAN_TRIGGER="0"
The "0" value means that you won't accept any scans from an intruding system. In other
words, the first scan will trip the PortSentry monitor. You can increase this value to be
tolerant of one or more errant scans (though you probably won't want to).

Changing the portsentry.modes file

The /etc/portsentry/portsentry.modes file defines the modes in which the PortSentry


command is run at boot time. Here is how that file appears by default:
tcp
udp
#stcp
#sudp
#atcp
#audp
The tcp and udp options are the basic PortSentry modes for the TCP and UDP services,
respectively. Your other choices of options include stealth TCP (stcp) and advanced stealth
TCP (atcp) and stealth UDP (sudp) and advanced stealth UDP (audp). Only run one TCP
service and one UDP service. So, if you uncomment a stealth or advanced stealth service,
be sure to add a comment in front of the appropriate basic service.
To activate the new services, you would then execute the following command:
# /etc/init.d/portsentry restart
The new PortSentry modes will take effect immediately. Those new modes will also be in
effect when your computer reboots.

Testing PortSentry

You can test that your ports are properly protected in different ways. What you want to do
is run a program that a potential intruder would run and see if it trips the appropriate
response from PortSentry. For example, you could use a port scanner to see how your
ports appear to the outside world. You could also use a command, such as telnet, to try
and set off a particular port to see if PortSentry catches it.
nmap is a popular tool for scanning TCP and UDP ports. You can give the nmap command
a host name or IP address, and it will scan about 1500 ports on computer to see which
ports are open (and presumably offering services that could potentially be cracked).
An RPM of nmap is also available. You can download the nmap-frontend package, which
contains a simple graphical interface to nmap called xnmap. I suggest that you install the
packages on the system running PortSentry as well as on another system on your LAN (if
one is available). Then run the following procedure on the PortSentry system to test it:
274 Linux System and Networking Administration

1. If PortSentry is running, shut it down by typing the following:


2. # /etc/init.d/portsentry stop
3. Type the following nmap commands to see which ports are open on the local
system:
4. # nmap -sS -O 127.0.0.1
5. # nmap -sU -O 127.0.0.1
The output shows you which ports are currently offering services on your computer for TCP
and UDP protocols, respectively.
6. If there are any services that you don't want open, you should turn off those
services by using chkconfig service off (replacing service with the service name),
by editing the configuration file in the /etc/xinetd.d directory that represents the
service and changing disable = no to disable = yes, or by changing your firewall
setup.
7. If there are services that you want to be available from your computer, make sure
that the port numbers representing those services are not being monitored by
PortSentry. Remove the port number from the TCP_PORTS and/or UDP_PORTS
options in the /etc/portsentry/portsentry.conf file, or PortSentry will report that
there is a possible stealth scan on the port.
8. Restart PortSentry as follows:
9. # /etc/init.d/portsentry start
10. Run nmap again, as described previously. The ports offering legitimate services, as
well as the ports being monitored by PortSentry, should all appear to be open.
11. Check the /var/log/messages file to make sure that PortSentry is not trying to
monitor any ports on which you are offering services.
When you have determined that PortSentry is set up the way you would like it to be, run
the nmap command from another computer on your network. This time, replace 127.0.0.1
with the name or IP address of the PortSentry computer. If everything is working, the first
port that the remote computer scans on your PortSentry computer should block all
subsequent scans.

Tracking PortSentry intrusions

Besides taking action against intruders, PortSentry logs its activities using the syslog
utility. PortSentry's start-up, shutdown, and scan-detection activities are logged to your
/var/log/messages file. The following are examples of PortSentry output in that file.
portsentry[13259]: adminalert: Psionic PortSentry 1.0 is starting.
portsentry[13260]: adminalert: Going into listen mode on TCP port: 1
portsentry[13260]: adminalert: Going into listen mode on TCP port: 11
.
.
.
portsentry[13260]: adminalert: PortSentry is active and listening.
portsentry[]: attackalert:Connect from host:10.0.0.4 to TCP port: 31337
portsentry[]: attackalert: Connect from host: 10.0.0.4 to TCP port: 11
portsentry[]: attackalert: Host: 10.0.0.4 is already blocked. Ignoring
.
.
Linux System and Networking Administration 275

.
portsentry[13371]: securityalert: Psionic PortSentry is shutting down
portsentry[13371]: adminalert: Psionic PortSentry is shutting down
The first part of the output shows PortSentry starting up. As PortSentry begins listening to
each port, that port is noted in a separate log message. The next messages show the
computer being scanned. Someone from host 10.0.0.4 ran nmap to scan the ports on the
computer. PortSentry caught the scan of port 31337 and blocked attempts to scan other
ports.
Finally, the last set of messages shows PortSentry being shut down. This is a security alert
because someone besides you could shut down PortSentry to hide that they had broken in.

Note If you have been running the LogSentry package (described earlier), these messages
show up in the e-mail messages you receive each hour from Logcheck.

Restoring Access

If access was cut off to a computer that you wanted to have access, there are several
things you can check to correct that problem:

 /etc/hosts.deny: See if the computer's IP address was mistakenly added to this


file. This would cause network services to be denied to the host at that IP address.

 /var/portsentry/portsentry.blocked: Check that an entry for the computer's


IP address wasn't added to the portsentry.blocked.udp or portsentry.blocked.tcp
files.
 route: Run the /sbin/route command to see if messages from the computer are
being rerouted to a dead host (probably the localhost).
 ipchains: Run the ipchains -L command to see if a new firewall was created to
block access from the computer. (If you had created an iptables rule instead, type
iptables -L to see the new firewall entry.)

Tip To make sure that access isn't cut off again, you can add the IP address of the
remote computer to the /etc/portsentry/portsentry.ignore file. Future improper
scans or requests for services won't cause the remote computer to be blocked.
276 Linux System and Networking Administration
Linux System and Networking Administration 277

CHAPTER 11: VIRTUALIZATION WITH XEN

What is Virtualization?
Virtualization enables enterprises to consolidate multiple servers without sacrificing
application isolation, scale their infrastructure as their needs grow, and increase availability
through dynamic provisioning and relocation of critical systems. Combining the open
source Xen hypervisor in Red Hat Enterprise Linux 5 enables enterprises to create a
dynamic data center that can scale easily to meet enterprise requirements.

Xen Architecture
The virtualization layer, often called the hypervisor or virtual machine (VM) monitor,
abstracts underlying physical hardware to present a uniform set of hardware resources—
such as processors, memory, networks, and storage blocks—to VMs. VMs running on a
single system share available physical resources, with the hypervisor multiplexing key
resources and maintaining isolation among different VMs. The following figure shows the
architecture of the Xen hypervisor.

Fig – Xen Architecture


How the hypervisor abstracts the underlying physical resources defines key characteristics
of the virtualization architecture. Two popular approaches are full virtualization and
paravirtualization. Full virtualization presents emulated resources to VMs that mimic a
standard PC architecture and standard peripheral devices. Using this approach allows
278 Linux System and Networking Administration

operating systems to run inside a VM without modification, but may require overhead that
can reduce performance.
Paravirtualization—the approach used by Xen—modifies guest operating systems to run in
a virtualized environment. The VMs interface with the Xen hypervisor using hypercalls,
rather than the system calls used by full virtualization.
As shown in the pereceding figure, the real device drivers run in a special VM, or domain,
called Domain 0 (Dom0). Rather than abstracting standard devices for the VMs, Dom0
exposes a set of class devices, such as networks and storage blocks, to the VMs. I/O data
transfers to and from each VM through Xen use the XenBus memory-mapped
communication channel. The VMs use paravirtualized device drivers and a paravirtualized
kernel to interoperate with Dom0 and the Xen hypervisor.
Paravirtualization requires modifying guest operating systems, which is not possible for all
popular OS distributions.
However, Xen can take advantage of Intel Virtualization Technology (Intel VT) and AMD
Virtualization (AMD-V) technology to run unmodified operating systems as well. The
virtualization capabilities of Red Hat Enterprise Linux 5 coupled with ninth-generation Dell
PowerEdge servers can create a flexible, powerful virtualized environment that
accommodates both modified and unmodified guest operating systems.
When Red Hat Enterprise Linux 5 is installed with virtualization capabilities, the integrated
Xen hypervisor takes control of the system hardware and launches the installed Red Hat
Enterprise Linux 5 distribution as Dom0. In addition to serving as the main driver domain
for VMs, Dom0 also runs a set of control and management serv ices that administrators can
access through command-line interface (CLI) tools such as xm and virsh or graphical user
interface (GUI) tools such as Virtual Machine Manager (virt-manager).

Virtualization Support And Requirements In Red Hat


Enterprise Linux 5
Before creating a virtualized environment with the Xen technology in Red Hat Enterprise
Linux 5, administrators should be sure they understand the support and system
requirements for elements such as virtual resources, host servers and operating systems,
processors, storage, packages, and the Security-Enhanced Linux (SELinux) security policy.
Red Hat virtualization with Xen technology can host multiple guest operating systems,
each of which runs in its own domain. Each VM handles its own applications and can only
access the resources assigned to it. Assigned resources include the following:
 Processors: Administrators can configure a VM with multiple virtual processors, but
the total number of virtual processors assigned to a VM must be less than or equal
to the total number of logical processors in the host system. Virtual Machine
Manager can schedule virtual processors according to the physical processor
workload to help optimize available resources.
 Memory: Each VM is assigned a part of the host system’s physical memory.
Administrators should typically assign the same amount of memory to a VM as
they would for the same configuration in a nonvirtualized environment.
Administrators can define the initial and maximum memory size when creating
VMs, then increase or decrease the memory allocation at runtime without
exceeding the specified maximum. The minimum amount of memory
recommended for a VM is 256 MB.
 Disk space: Each VM is assigned a part of the host system’s disk space. This disk
space is unique and cannot be shared between VMs. The disk space made available
to VMs can be either an image file or a disk partition.
 Network interfaces: Virtual network interface cards are configured with a persistent
virtual Media Access Control (MAC) address. When a new VM is created, this
address is selected at random from a reserved pool of over 16 million addresses,
Linux System and Networking Administration 279

making it unlikely that any two VMs will be assigned the same one. Administrators
for complex sites with a large number of VMs can allocate MAC addresses manually
to help ensure that they remain unique on the network. Red Hat virtualization
supports 10/100/1,000 Mbps Ethernet and 10 Gigabit Ethernet, Fibre Channel, and
InfiniBand networks.
Each VM also has a virtual text console that connects to the host system. Administrators
can redirect guest logins and console output to the text console, or configure VMs to use a
virtual GUI console that corresponds to the physical host’s standard video console. This
GUI employs standard graphic adapter features such as boot messaging, graphical
booting, and multiple virtual terminals, and can launch the X Window System.
VMs can be identified in any of three ways:
 Domain name: Text string that corresponds to a VM configuration file, used to
launch, identify, and control VMs
 Domain ID: Unique, nonpersistent number assigned to an active domain, used to
identify and control VMs
 Universally unique identifier: Identifier controlled from the VM configuration file
that helps ensure that VMs are uniquely identified by systems management tools

Packages for Xen Virtualization


To run a virtualized environment, the kernel-xen kernel must be installed and running on
the host system. Administrators can determine which kernel is running using the command

uname –r

if this command does not return a kernel with the word “xen” in it, then kernel-xen is not
running. If it is not running, administrators can determine whether it is installed using the
command

rpm -qa | grep kernel-xen

If this command returns no output, they must install the kernel from the installation media
with the command rpm -ivh kernel-xen.
Next, administrators should make kernelxen the default boot kernel, which they can do by
changing the default parameter in /boot/grub/grub.conf to the correct number (typically
0). They should also verify that the xen, xen-libs, bridge-utils, gnome-python2-
gnomekeyring, libvirt, libvirt-python, python-virtinst, virtmanager, and vnc Red Hat
Package Manager (RPM) files are installed, or install them from the installation media if
necessary.
Because of the interdependencies between these RPM packages, administrators should
typically update them using the yum (Yellowdog Updater, Modified) package installer. They
must first define the yum repository in /etc/yum.conf, then use the command

yum install rpm_name

to install the necessary packages.


For example:

yum install xen


yum install virt-manager
yum install vnc

After installing the necessary packages, administrators should reboot the system.
Finally, they should verify that the xend and xendomains daemons are running using the
commands service xend status and service xendomains status. The xend daemon provides
280 Linux System and Networking Administration

virtualization services, while the xendomains daemon allows VMs to start and stop
automatically when the host system boots or shuts down. Both daemons must be running
to create VMs. If they are not running, administrators should start them using the
commands service xend start and service xendomains start.

Virtual Machine Creation In Red Hat Enterprise


Linux 5

Introduction

Administrators can take advantage of two primary tools when creating VMs: the Virtual
Machine Manager GUI tool and the virt-install CLI tool.

Creating A Virtual Machine with Virtual Machine Manager

Virtual Machine Manager is a GUI tool provided in Red Hat Enterprise Linux 5 that
administrators can use to create, pause, resume, stop, and monitor VMs. For example,
administrators can use it to create a paravirtualized 32-bit Red Hat Enterprise Linux 5
guest OS on a 32-bit Red Hat Enterprise Linux 5 host OS by performing the following
steps:
1. Run Virtual Machine Manager using the command virt-manager and connect to the
local Xen host. At this point, the only domain running is Dom0.
2. To create a new VM, select File > New Machine, then click the Forward button.
3. Provide a name for the VM—for example, vm_rhel5_i386—then click the Forward
button.
4. Select “Paravirtualized” as the virtualization method, then click the Forward
button.

5. Provide the location of the extracted installation media files for the guest OS and, if
desired, the location of a kickstart file with the system parameters already defined,
then click the Forward button.

6. Specify how to assign the VM disk space—a partition on the host system or an
image file—and how much space to allocate, then click the Forward button. If
allocating the entire virtual disk now, be sure to verify that the host system has
enough disk space to accommodate the specified amount.

7. Allocate the amount of memory and number of virtual processors, then click the
Forward button.
8. Review the specified parameters and click the Finish button to begin the VM
creation.
The OS installation process is the same as a non-virtual OS installation. If
allocating the entire virtual disk now, then the systemtypically takes several
minutes to create the disk space before it begins installation.
When the OS installation process ends, the virtual window closes and the VM is
ready to start.

9. To start the VM, enter the command xm create vm_name. Virtual Machine
Manager should now show both Dom0 and the VM running. To open a Virtual
Network Computing (VNC) display window for this VM, select the VM and click the
Open button.
Linux System and Networking Administration 281

Creating A Virtual Machine With virt-install

Administrators can also use the virt-install CLI tool to create a paravirtualized VM.
Specifying parameters in this way enables administrators to automate VM creation using
shell scripts. The syntax is as follows:

virt-install --name=vm_name
--ram=memory --vcpus=no_of_
vcpus --file=vm_image_file
--file-size=vm_disk_size
--vnc --paravirt
--location=OS_source_location

In this command, vm_name is the name of the VM, memory is the amount of memory to
allocate to the VM (in megabytes), no_of_vcpus is the number of virtual processors to
allocate to the VM, vm_image_file is the file to use as the disk image, vm_disk_size is the
amount of VM disk space to allocate to the VM (in gigabytes), --vnc sets the VM to use
VNC for graphics support, --paravirt denotes that the VM should be paravirtualized, and
OS_source_location is the location of the extracted installation media files for the guest
OS. This command also launches a VNC display window.
For example, administrators could create the VM as shown below:

virt-install --name=vm_rhel5_
i386 --ram=1000 --vcpus=2
--file=/var/lib/xen/images/
vm_rhel5_i386 --filesize=
10 --vnc --paravirt
--location=http://webserver/
pub/RHEL5/i386

Red Hat Enterprise Linux 5 Xen Configuration And


Log Files
The Red Hat Enterprise Linux 5 Xen configuration files are located in the /etc/xen
directory. Each VM has a corresponding configuration file in /etc/xen, which is created
automatically when the VMs are created and has the same name as its corresponding VM..
For more information on available configuration items, see the xmdomain.cfg man page.
The Red Hat Enterprise Linux 5 Xen log files are located in the /var/log/xen directory. The
xend daemon and qemu-dm process, for example, write to multiple log files:
 xend-debug.log: Contains logs of event errors from xend and the virtualization
subsystems (such as the frame buffer and Python scripts)
 xend.log: Contains data collected by the xend daemon, including system events,
administrator actions, and VM operations such as create, shutdown, and destroy;
this log is typically the first place administrators should look when troubleshooting
event- or performance-related problems
 xen-hotplug.log: Contains data from hot-plug events, including events when a
device or network script does not come online
282 Linux System and Networking Administration

 qemu-dm.pid.log: Created by the qemu-dm process for each fully virtualized guest
(where pid is the process identifier)

Virtual Machine Management Commands


Administrators can use the xm and virsh command-line interface tools to create, manage,
and troubleshoot VMs (see the table below). Some commands require additional
arguments; for more information, see the xm and virsh man pages.

Starting and stopping VMs

xm create Creates a domain based on a configuration


file

xm destroy Terminates a domain

xm pause Pauses execution of a domain

xm reboot Reboots a domain

xm shutdown Shuts down a domain

xm save Saves a domain state to restore later

xm restore Restores a domain from a saved state

Status monitoring

xm uptime Displays uptime for a domain

xm top Monitors a host and its domains in real time

xm list Displays domain information

xm info Displays host information

xm vcpu-list Lists domain virtual processors

xm network-list Lists domain virtual network interfaces

virsh nodeinfo Displays node information

virsh vcpuinfo Displays domain virtual processor


information

Troubleshooting

xm console Attaches to a domain console

xm dump-core Displays a core dump for a specific domain

xm dmesg Reads and/or clears the xend daemon’s


message buffer

xm log Displays the xend log

virsh dominfo Displays domain information


Linux System and Networking Administration 283

Performance tuning

xm mem-max Sets the maximum amount of memory for a


domain

xm mem-set Sets the current memory usage for a


domain

xm vcpu-set Sets the number of active processors for a


domain

virsh dumpxml Displays domain information in XML

virsh dump Saves a core dump for a specific domain to


a file

Other

xm rename Renames a domain

xm sysrq Sends a system request to a domain

xm block-attach Creates a new virtual block device

xm block-detach Destroys a domain’s virtual block device

xm block-list Lists virtual block devices for a domain

xm network-attach Creates a new network device

xm network-detach Destroys a network device

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy