Vous êtes sur la page 1sur 108

AL

riz
ho
ut
na

EV
U

ed

GL275

t
uc

od

AT

pr
re

ENTERPRISE
LINUX NETWORK
SERVICES

or

IO

n
io

RHEL6

No part of this publication may be stored in a retrieval system, transmitted or reproduced in any
way, including, but not limited to, photocopy, photograph, magnetic, electronic or other record,
without the prior written permission of Guru Labs.

O
ite

PY

ib

d.

Version: GL275S-R6-H00

oh

Guru Labs L.C. accepts no liability for any claims, demands, losses, damages, costs or expenses
suffered or incurred howsoever arising from or in connection with the use of this courseware. All
trademarks are the property of their respective owners.

pr

Photocopying any part of this manual without prior written consent of Guru Labs L.C. is a violation
of federal law. This manual should not appear to be a photocopy. If you believe that Guru Labs
training materials are being photocopied without permission, please email Alert@gurulabs.com or
call 1-801-298-5227.

is

This instructional program, including all material provided herein, is supplied without any guarantees
from Guru Labs L.C. Guru Labs L.C. assumes no liability for damages or legal action arising from
the use or misuse of contents or details contained herein.

This curriculum contains proprietary information which is for the exclusive use of customers of Guru
Labs L.C., and is not to be shared with personnel other than those in attendance at this course.

tio
bu

ri
st

di

The contents of this course and all its modules and related materials, including handouts to
audience members, are copyright 2012 Guru Labs L.C.

Table of Contents
1
2
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
20
21
22
23
25
26
29
32
36
41
45

Testing Resolution
Lab Tasks
1. Configuring a Slave Name Server

14
16
17

Chapter 3
CONFIGURING BIND
BIND Configuration Files
named.conf Syntax
named.conf Options Block
Creating a Site-Wide Cache
rndc Key Configuration
Zones In named.conf
Zone Database File Syntax
SOA Start of Authority
A & PTR Address & Pointer Records
NS Name Server
CNAME & MX Alias & Mail Host
Abbreviations and Gotchas
$ORIGIN and $GENERATE
Lab Tasks
1. Use rndc to Control named
2. Configuring BIND Zone Files

1
2
3
5
7
8
10
12
13
15
16
17
18
20
21
22
24

Chapter 4
CREATING DNS HIERARCHIES
Subdomains and Delegation
Subdomains
Delegating Zones
in-addr.arpa. Delegation
Issues with in-addr.arpa.
RFC2317 & in-addr.arpa.
Lab Tasks
1. Create a Subdomain in an Existing Domain
2. Subdomain Delegation

1
2
3
4
5
6
7
8
9
13

t
uc

od

n
io

or

IO

AT

pr
re

ed

AL

riz
ho
ut
na

EV

tio
bu

ri
st

di

Chapter 1
SECURING SERVICES
Xinetd
Xinetd Connection Limiting and Access Control
Xinetd: Resource limits, redirection, logging
TCP Wrappers
The /etc/hosts.allow & /etc/hosts.deny Files
/etc/hosts.{allow,deny} Shortcuts
Advanced TCP Wrappers
Basic Firewall Activation
Netfilter: Stateful Packet Filter Firewall
Netfilter Concepts
Using the iptables Command
Netfilter Rule Syntax
Targets
Common match_specs
Connection Tracking
SELinux Security Framework
Choosing an SELinux Policy
SELinux Commands
SELinux Booleans
Graphical SELinux Policy Tools
Lab Tasks
1. Securing xinetd Services
2. Enforcing Security Policy with xinetd
3. Securing Services with TCP Wrappers
4. Securing Services with Netfilter
5. Troubleshooting Practice
6. SELinux File Contexts

PY

ib

oh

pr

Chapter 5
ADVANCED BIND DNS FEATURES
Address Match Lists & ACLs
Split Namespace with Views
Restricting Queries
Restricting Zone Transfers

ite

d.

ii

1
2
3
4
6
7
8
10
12
13

is

Chapter 2
DNS CONCEPTS
Naming Services
DNS A Better Way
The Domain Name Space
Delegation and Zones
Server Roles
Resolving Names
Resolving IP Addresses
Basic BIND Administration
Configuring the Resolver

1
2
3
4
5

6
7
8
9
10
11
12
14
15
18

Chapter 6
LDAP CONCEPTS AND CLIENTS
LDAP: History and Uses
LDAP: Data Model Basics
LDAP: Protocol Basics
LDAP: Applications
LDAP: Search Filters
LDIF: LDAP Data Interchange Format
OpenLDAP Client Tools
Alternative LDAP Tools
Lab Tasks
1. Querying LDAP

1
2
3
5
6
7
8
10
12
13
14

Chapter 8
USING APACHE
HTTP Operation
Apache Architecture
Dynamic Shared Objects
Adding Modules to Apache
Apache Configuration Files
httpd.conf Server Settings
httpd.conf Main Configuration
HTTP Virtual Servers
Virtual Hosting DNS Implications
httpd.conf VirtualHost Configuration
Port and IP based Virtual Hosts
Name-based Virtual Host
Apache Logging
Log Analysis
The Webalizer
Lab Tasks
1. Apache Architecture
2. Apache Content
3. Configuring Virtual Hosts

1
2
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
23
25

Chapter 9
APACHE SECURITY
Virtual Hosting Security Implications
Delegating Administration
Directory Protection
Directory Protection with AllowOverride
Common Uses for .htaccess
Symmetric Encryption Algorithms
Asymmetric Encryption Algorithms
Digital Certificates
SSL Using mod_ssl.so
Lab Tasks
1. Using .htaccess Files
2. Using SSL Certificates with Apache

1
2
3
4
6
7
8
9
10
11
12
13
17

or

IO

n
io

tio
bu

ri
st

is

oh

pr

PY

ib

Chapter 10
APACHE SERVER-SIDE SCRIPTING ADMINISTRATION
Dynamic HTTP Content
PHP: Hypertext Preprocessor
Developer Tools for PHP
Installing PHP

ite

1
2
3
4
5

d.

1
2
3
4
5
6
7
8
10
12
13
15
17
18
23
26

di

Chapter 7
OPENLDAP SERVERS
Popular LDAP Server Implementations
OpenLDAP: Server Architecture
OpenLDAP: Backends
OpenLDAP: Replication
OpenLDAP: Configuration Options
OpenLDAP: Configuration Sections
OpenLDAP: Global Parameters
OpenLDAP: Database Parameters
OpenLDAP Server Tools
Enabling LDAP-based Login
System Security Services Daemon (SSSD)
Lab Tasks
1. Building An OpenLDAP Server
2. Enabling TLS For An OpenLDAP Server
3. Enabling LDAP-based Logins

t
uc

od

AT

pr
re

ed

AL

riz
ho
ut
na

EV

Running BIND in a chroot jail


Dynamic DNS Concepts
Allowing Dynamic DNS Updates
DDNS Administration with nsupdate
Common Problems
Common Problems
Securing DNS With TSIG
Lab Tasks
1. Configuring Dynamic DNS
2. Securing BIND DNS

iii

6
7
8
9
10
11
12
13
14
15
20
22
26

or

IO

n
io

Chapter 14
SMTP THEORY
SMTP
SMTP Terminology
SMTP Architecture
SMTP Commands
SMTP Extensions
SMTP AUTH
SMTP STARTTLS
SMTP Session

tio
bu

is

1
2
3
4
5
6
8
9
10
11
12
13
14
15
16
17
18
19
21
22
23
28
32
36
39

1
2
3
4
5
6
7
8
9

ite

PY

ib

oh

pr

Chapter 15
POSTFIX
Postfix Features
Postfix Architecture
Postfix Components

d.

1
2
3
4
5
7
8
9
10
12
13
16
18
20

ri
st

di

iv

t
uc

od

Chapter 12
THE SQUID PROXY SERVER
Squid Overview
Squid File Layout
Squid Access Control Lists
Applying Squid ACLs
Tuning Squid & Configuring Cache Hierarchies
Bandwidth Metering
Monitoring Squid
Proxy Client Configuration
Lab Tasks
1. Installing and Configuring Squid
2. Squid Cache Manager CGI
3. Proxy Auto Configuration
4. Configure a Squid Proxy Cluster

1
2
3
4
6
7
8
9
11
12
13

Chapter 13
SAMBA CONCEPTS AND CONFIGURATION
Introducing Samba
Samba Daemons
NetBIOS and NetBEUI
Accessing Windows/Samba Shares from Linux
Samba Utilities
Samba Configuration Files
The smb.conf File
Mapping Permissions and ACLs
Mapping Linux Concepts
Mapping Case Sensitivity
Mapping Users
Sharing Home Directories
Sharing Printers
Share Authentication
Share-Level Access
User-Level Access
Samba Account Database
User Share Restrictions
Lab Tasks
1. Samba Share-Level Access
2. Samba User-Level Access
3. Samba Group Shares
4. Configuring Samba
5. Samba Home Directory Shares

AT

pr
re

Chapter 11
IMPLEMENTING AN FTP SERVER
The FTP Protocol
Active Mode FTP
Passive Mode FTP
ProFTPD
Pure-FTPd
vsftpd
Configuring vsftpd
Anonymous FTP with vsftpd
Lab Tasks
1. Configuring vsftpd

ed

AL

riz
ho
ut
na

EV

Configuring PHP
Securing PHP
Security Related php.ini Configuration
Java Servlets and JSP
Apache's Tomcat
Installing Java SDK
Installing Tomcat Manually
Using Tomcat with Apache
Lab Tasks
1. CGI Scripts in Apache
2. Apache's Tomcat
3. Using Tomcat with Apache
4. Installing Applications with Apache and Tomcat

1
2
3
4

t
uc

od

GNU Mailman
Mailman Configuration
Lab Tasks
1. Configuring Procmail & SpamAssassin
2. Configuring Cyrus IMAP
3. Dovecot TLS Configuration
4. Configuring SquirrelMail
5. Base Mailman Configuration
6. Basic Mailing List
7. Private Mailing List

20
21
23
24
31
38
43
47
50
56

Appendix A
SENDMAIL
Sendmail Architecture
Sendmail Components
Sendmail Configuration
Sendmail Remote Configuration
Controlling Access
Sendmail Mail Filter (milter)
Configuring Sendmail SMTP AUTH
Configuring SMTP STARTTLS
Lab Tasks
1. Configuring Sendmail
2. Sendmail Network Configuration
3. Sendmail Virtual Host Configuration
4. Sendmail SMTP AUTH Configuration
5. Sendmail STARTTLS Configuration

1
2
3
4
6
8
9
10
11
12
13
18
20
24
28

or

IO

n
io

tio
bu

ri
st

di

Appendix B
NIS
NIS Overview
NIS Limitations and Advantages
NIS Client Configuration
NIS Server Configuration
NIS Troubleshooting Aids
Lab Tasks
1. Configuring NIS
2. NIS Slave Server

1
2
3
4
5
7
8
9
13

is

O
ite

PY

ib

oh

pr

d.

1
2
3
5
7
9
10
11
13
14
16
17
18
19

Chapter 16
MAIL SERVICES AND RETRIEVAL
Filtering Email
Procmail
SpamAssassin
Bogofilter
Accessing Email
The IMAP4 Protocol
Dovecot POP3/IMAP Server
Cyrus IMAP/POP3 Server
Cyrus IMAP MTA Integration
Cyrus Mailbox Administration
Fetchmail
SquirrelMail
Mailing Lists

5
7
8
9
10
11
12
13
14
15
16
17
18
19
21
22
23
24
25
26
27
28
29
34
38
42
47

AT

pr
re

ed

AL

riz
ho
ut
na

EV

Postfix Configuration
master.cf
main.cf
Postfix Map Types
Postfix Pattern Matching
Advanced Postfix Options
Virtual Domains
Postfix Mail Filtering
Configuration Commands
Management Commands
Postfix Logging
Logfile Analysis
chrooting Postfix
Postfix, Relaying and SMTP AUTH
SMTP AUTH Server and Relay Control
SMTP AUTH Clients
Postfix / TLS
TLS Server Configuration
Postfix Client Configuration for TLS
Other TLS Clients
Ensuring TLS Security
Lab Tasks
1. Configuring Postfix
2. Postfix Network Configuration
3. Postfix Virtual Host Configuration
4. Postfix SMTP AUTH Configuration
5. Postfix STARTTLS Configuration

Typographic Conventions

0O
1l

EV

The fonts, layout, and typographic conventions of this book have been
carefully chosen to increase readability. Please take a moment to
familiarize yourself with them.
A Warning and Solution

riz
ho
ut
na

AL

A common problem with computer training and reference materials is


the confusion of the numbers "zero" and "one" with the letters "oh" and
"ell". To avoid this confusion, this book uses a fixed-width font that makes
each letter and number distinct.

ed

Typefaces Used and Their Meanings

AT

pr
re

The following typeface conventions have been followed in this book:

od

fixed-width normal Used to denote file names and directories. For


example, the /etc/passwd file or /etc/sysconfig/directory. Also

t
uc

used for computer text, particularily command line output.

The number
"zero".

The letter
"oh".

The number
"one".

The letter
"ell".

or

IO

n
io

fixed-width italic Indicates that a substitution is required. For


example, the string stationX is commonly used to indicate that the
student is expected to replace X with his or her own station number,
such as station3.

di

C
O
ite

PY

ib

oh

d.

vi

pr

Occasional variations from these conventions occur to increase clarity.


This is most apparent in the labs where bold text is only used to indicate
commands the student must enter or actions the student must perform.

is

variable-width bold Used within labs to indicate a required student


action that is not typed on the command line.

fixed-width underlined Used to denote URLs. For example,


http://www.gurulabs.com/.

tio
bu

fixed-width bold italic Used when a substitution is required


within a command or user input. For example, ssh -X stationX.

ri
st

fixed-width bold Used to set apart commands. For example, the


sed command. Also used to indicate input a user might type on the
command line. For example, ssh -X station3.

Typographic Conventions
Line Wrapping

Terms and Definitions

EV

Occasionally content that should be on a single line, such as command


line input or URLs, must be broken across multiple lines in order to fit
deprecate To indicate that something is considered obsolete, with on the page. When this is the case, a special symbol is used to indicate
to the reader what has happened. When copying the content, the line
the intent of future removal.
frob To manipulate or adjust, typically for fun, as opposed to tweak. breaks should not be included. For example, the following hypothetical
grok To understand. Connotes intimate and exhaustive knowledge. PAM configuration should only take two actual lines:
hork To break, generally beyond hope of repair.
hosed A metaphor referring to a Cray that crashed after the password required /lib/security/pam_cracklib.so retry=3a
type= minlen=12 dcredit=2 ucredit=2 lcredit=0 ocredit=2
disconnection of coolant hoses. Upon correction, users were assured
password required /lib/security/pam_unix.so use_authtok
the system was rehosed.
mung (or munge) Mash Until No Good: to modify a file, often
Representing File Edits
irreversibly.
troll To bait, or provoke, an argument, often targeted towards the
File edits are represented using a consistent layout similar to the unified
newbie. Also used to refer to a person that regularly trolls.
diff format. When a line should be added, it is shown in bold with a
twiddle To make small, often aimless, changes. Similar to frob.
plus sign to the left. When a line should be deleted, it is shown struck
out with a minus sign to the left. When a line should be modified, it
When discussing a command, this same format is also used to show and
is shown twice. The old version of the line is shown struck out with a
describe a list of common or important command options. For example,
minus sign to the left. The new version of the line is shown below the
the following ssh options:
old version, bold and with a plus sign to the left. Unmodified lines are
often included to provide context for the edit. For example, the following
-X Enables X11 forwarding. In older versions of OpenSSH that do
describes modification of an existing line and addition of a new line to
not include -Y, this enables trusted X11 forwarding. In newer versions
the OpenSSH server configuration file:
of OpenSSH, this enables a more secure, limited type of forwarding.
-Y Enables trusted X11 forwarding. Although less secure, trusted
File: /etc/ssh/sshd_config
forwarding may be required for compatibility with certain programs.
The following format is used to introduce and define a series of terms:

t
uc

od

AT

pr
re

ed

AL

riz
ho
ut
na

or

IO

n
io

tio
bu

ri
st

di

is

oh

pr

When it is necessary to press a series of keys, the series of keystrokes


will be represented without a space between each key. For example, the
following means to press the "j" key three times: jjj

#LoginGraceTime 2m
#PermitRootLogin yes
PermitRootLogin no
AllowUsers sjansen
#StrictModes yes

Representing Keyboard Keystrokes

+
+

ite

PY

ib

Note that the standard file edit representation may not be used when it
When it is necessary to press keys at the same time, the combination will is important that the edit be performed using a specific editor or method.
be represented with a plus between each key. For example, the following In these rare cases, the editor specific actions will be given instead.
means to press the "ctrl," "alt," and "backspace" keys at the same time:
. Uppercase letters are treated the same: A

d.

vii

Lab Conventions
Variable Data Substitutions

Lab Task Headers

EV

Every lab task begins with three standard informational headers: In some lab tasks, students are required to replace portions of commands
"Objectives," "Requirements," and "Relevance". Some tasks also include a with variable data. Variable substitution are represented using italic fonts.
For example, X and Y.
"Notices" section. Each section has a distinct purpose.

Objectives An outline of what will be accomplished in the lab task.


Requirements A list of requirements for the task. For example,
whether it must be performed in the graphical environment, or
whether multiple computers are needed for the lab task.
Relevance A brief example of how concepts presented in the lab
task might be applied in the real world.
Notices Special information or warnings needed to successfully
complete the lab task. For example, unusual prerequisites or common
sources of difficulty.

AL

riz
ho
ut
na

Substitutions are used most often in lab tasks requiring more than one
computer. For example, if a student on station4 were working with a
student on station2, the lab task would refer to stationX and stationY

stationX$ ssh root@stationY

ed

and each would be responsible for interpreting the X and Y as 4 and 2.

od

Command Prompts

AT

pr
re

station4$ ssh root@station2


Truncated Command Examples

t
uc

or

IO

n
io

Though different distributions and shells have different prompts, all Command output is occasionally omitted or truncated in examples. There
examples will use a $ prompt for commands to be run as an unprivileged are two type of omissions: complete or partial.
user (guru or visitor), and commands with a # prompt should be run as
Sometimes the existence of a commands output, and not its content, is
the root user. For example:
all that matters. Other times, a commands output is too variable to
$ whoami
reliably represent. In both cases, when a command should produce
guru
output, but an example of that output is not provided, the following
$ su format is used:

tio
bu

ri
st

di

$ cat /etc/passwd
. . . output omitted . . .

Password: makeitso
# whoami
root

is

Occasionally the prompt will contain additional information. For example, In general, at least a partial output example is included after commands.
when portions of a lab task should be performed on two different stations When example output has been trimmed to include only certain lines,
the following format is used:
(always of the same distribution), the prompt will be expanded to:

O
ite

PY

$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
. . . snip . . .
clints:x:500:500:Clint Savage:/home/clints:/bin/zsh
. . . snip . . .

ib

d.

viii

oh

pr

stationX$ whoami
guru
stationX$ ssh visitor@stationY
root@stationY's password: work
stationY# whoami
visitor

Lab Conventions
Action Lists

Distribution Specific Information

EV

AL

riz
ho
ut
na

This courseware is designed to support multiple Linux distributions. Some lab steps consist of a list of conceptually related actions. A
When there are differences between supported distributions, each description of each action and its effect is shown to the right or under
the action. Alternating actions are shaded to aid readability. For example,
version is labeled with the appropriate base strings:
the following action list describes one possible way to launch and use
xkill to kill a graphical application:
R Red Hat Enterprise Linux (RHEL)
S SUSE Linux Enterprise Server (SLES)
U Ubuntu

Open the "Run Application" dialog.

xkill

The specific supported version is appended to the base distribution


strings, so for Red Hat Enterprise Linux version 6 the complete string
is: R6.

pr
re

ed

Launch xkill. The cursor should change,


usually to a skull and crossbones.
Click on a window of the application to kill.
Indicate which process to kill by clicking on
it. All of the applications windows should
disappear.

t
uc

od

AT

Certain lab tasks are designed to be completed on only a sub-set of


the supported Linux distributions. If the distribution you are using is not
shown in the list of supported distributions for the lab task, then you
should skip that task.

n
io

or

IO

Certain lab steps are only to be performed on a sub-set of the supported


Linux distributions. In this case, the step will start with a standardized
string that indicates which distributions the step should be performed on.
When completing lab tasks, skip any steps that do not list your chosen
distribution. For example:

[S10]

$ sux Password: password


# xclock

is

On SLES10, the sux command


copies the MIT-MAGIC-COOKIE-1
so that graphical applications
can be run after switching
to another user account. The
SLES10 su command did not
do this.

ite

PY

ib

oh

pr

[S11]

$ grep -i linux /etc/*-release | cut -d: -f2


Red Hat Enterprise Linux Server release 6.0 (Santiago)
SUSE Linux Enterprise Server 11 (i586)

Sometimes commands or command output is distribution specific. In


these cases, the matching distribution string will be shown to the left of
the command or output. For example:
[R6]

tio
bu

Because of a bug in RHEL4's Japanese fonts...

Occasionally lab steps will feature a shaded line that extends to a note
in the right margin. This note, referred to as a "callout," is used to provide
additional commentary. This commentary is never necessary to complete
the lab succesfully and could in theory be ignored. However, callouts
do provide valuable information such as insight into why a particular
command or option is being used, the meaning of less obvious command
output, and tips or tricks such as alternate ways of accomplishing the task
at hand.

ri
st

di

1) [R4] This step should only be performed on RHEL4.

Callouts

d.

ix

or

N
is

ite

d.

PY

ib

oh

pr

C
n

tio
bu

ri
st

di

IO

n
io

AT
t
uc

od

pr
re

ed

AL

riz
ho
ut
na

EV

AL

riz
ho
ut
na

EV

Content
Xinetd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Xinetd Connection Limiting and Access Control . . . . . . . . 4
Xinetd: Resource limits, redirection, logging . . . . . . . . . . . 5
TCP Wrappers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
The /etc/hosts.allow & /etc/hosts.deny Files . . . . . . . . . . . . 7
/etc/hosts.{allow,deny} Shortcuts . . . . . . . . . . . . . . . . . . . . 8
Advanced TCP Wrappers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Basic Firewall Activation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Netfilter: Stateful Packet Filter Firewall . . . . . . . . . . . . . . . 11
Netfilter Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Using the iptables Command . . . . . . . . . . . . . . . . . . . . . . . 13
Netfilter Rule Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Common match_specs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Connection Tracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
SELinux Security Framework . . . . . . . . . . . . . . . . . . . . . . . . 18
Choosing an SELinux Policy . . . . . . . . . . . . . . . . . . . . . . . . . 20
SELinux Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
SELinux Booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Graphical SELinux Policy Tools . . . . . . . . . . . . . . . . . . . . . . 23
Lab Tasks
25
1. Securing xinetd Services . . . . . . . . . . . . . . . . . . . . . . . . . 26
2. Enforcing Security Policy with xinetd . . . . . . . . . . . . . . 29
3. Securing Services with TCP Wrappers . . . . . . . . . . . . . 32
4. Securing Services with Netfilter . . . . . . . . . . . . . . . . . . . 36
5. Troubleshooting Practice . . . . . . . . . . . . . . . . . . . . . . . . . 41
6. SELinux File Contexts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

ed

Chapter

t
uc

od

AT

pr
re

or

IO

n
io

di

tio
bu

ri
st

SECURING
SERVICES

is

O
ite

PY

ib

oh

pr

d.

Xinetd

Efficient Resource Utilization

ed

AL

riz
ho
ut
na

EV

The Super Daemon


Small, efficient transient-daemon launcher
Listens on ports, launches transient daemons as needed
Built-in TCP Wrappers for daemons not linked against libwrap
IPv6 support
Modern Replacement for inetd
/etc/xinetd.conf
/etc/xinetd.d/

pr
re

3120

23

AT

Originally, inetd was created to be a small, low memory usage


network daemon. It would launch other daemons on demand, thereby
not requiring transient daemons to be always running, consuming
CPU time and memory. This was especially important in the early
days of Unix when memory and CPU cycles were in short supply and
extremely expensive.

Client

69

od

inetd
79

t
uc

IO

n
io

3120

23
69

79
110

3120

tio
bu
Client

in.telnetd

23

is

in.telnetd

23

inetd

ri
st

While the original inetd is (still) widely used on most Unix systems,
most Linux distributions typically use xinetd in place of inetd.
Some of the benefits of xinetd over the older inetd include:

Client

di

A positive side effect of the inetd setup is that it allows for


centralized enforcement of policy. Policy decisions include the
number of simultaneous connections, rate limiting, and logging.

23
69

inetd

ite

79

PY

ib

oh

pr

y Greater configuration control & flexibility


y TCP Wrappers built into the super-daemon
y Has security and access control features

or

The xinetd Daemon

110

d.

110

1-2

Xinetd Configuration

EV

The main configuration file for Xinetd is /etc/xinetd.conf, which


references the /etc/xinetd.d/ directory. In this directory, the
configuration for each transient service is typically isolated in an
individual configuration file.
Example Service Configuration Files in /etc/xinetd.d

AL

riz
ho
ut
na

The following table includes several of the service files:


Filename

Description

amanda

AMANDA backup system server

gssftp

Kerberized FTP server

pr
re

ed

krb5-telnet Kerberized telnet server

rsync file synchronization server

talk

Internet Talk Protocol server

telnet

Standard telnet server

tftp

Trivial File Transfer Protocol (TFTP) server

t
uc

od

or

IO

n
io

Example Service Configuration File telnet

di

File: /etc/xinetd.d/telnet

AT

rsync

tio
bu

ri
st

# default: on
# description: The telnet server serves telnet sessions;
# it uses unencrypted authentication.
service telnet
{
flags
= REUSE
socket_type
= stream
wait
= no
user
= root
server
= /usr/sbin/in.telnetd
log_on_failure
+= USERID
disable
= no
}

is

O
ite

PY

ib

oh

pr

d.

1-3

Xinetd Connection Limiting and Access Control

EV

The extended Internet services daemon


Built-in access control

only_from
no_access
Sophisticated connection limiting

AL

riz
ho
ut
na

instances
cps
per_source
max_load
Time of day restrictions

access_times

ed

Remote Access Control

Additional Connection Limiting Attributes

pr
re

cps Limits the rate of incoming connections. It takes two values.

od

AT

Xinetd provides access control through two attributes: only_from and


no_access. Both attributes take a value of an IP address in CIDR

t
uc

form: 1.2.3.4/32. Multiple values can be supplied space separated. If


both attributes are defined, then the most specific match wins.

or

di

Connection Limiting to Mitigate DoS Attacks

IO

n
io

Generally these attributes are not used. Centralized, system-wide TCP


Wrappers (built-in to Xinetd) and packet-filter firewalling is more
common for access control.

The first defines the number of connections per second. If this


value is exceeded, then the service is temporarily disabled for the
number of seconds defined in the second value.
per_source Limits the number of connections per source IP
address. This is useful to keep a single client from monopolizing
server resources.
max_load Monitor the one minute load average (an indication of
how busy a server is), and only allow connections when the load
average is below the defined value.

File: /etc/xinetd.d/service_config
+ access_times
= 2:00-8:59 12:00-23:59

d.

0
50 10
50
10

ite

=
=
=
=

PY

ib

oh

pr

1-4

max_load
cps
instances
per_source

is

File: /etc/xinetd.conf

Using the access_times attribute, the administrator can limit access


to Xinetd controlled services based on the time of day when the
connection is established. The value is an interval specified in the
hour:min-hour:min format. For example:

The main configuration file /etc/xinetd.conf specifies a default of


50 connections per service using the instances attribute. Such
defaults can be overridden in per-service configuration files.

Limiting New Connections to a Certain Time of Day

tio
bu

Xinetd Connection Limiting Features

ri
st

One of the major reasons for using Xinetd in place of Inetd are the
connection limiting features. With legacy inetd, there are no limits,
besides exhausting system resources, on the number of connections
to a service. This creates the probability of DoS attack.

Xinetd: Resource limits, redirection, logging

EV

The extended Internet services daemon


System resource limiting

rlimit_as
rlimit_cpu
nice

Extensive logging features

AL

riz
ho
ut
na

log_type
log_on_success
log_on_failure
Redirection of TCP connections

redirect

ed

Logging Features of xinetd

Configuration Attributes for Enforcing Resource Limits

pr
re

t
uc

od

rlimit_as sets the maximum amount of address space that a

n
io

launched service can use.

Each service can log one or more of these items: the PID, the remote
HOST address, the remote USERID (obtained via the ident protocol),
the EXIT event (and status) and / or the DURATION. These values are
used with the log_on_success and log_on_failure attributes.

or

service can use.

IO

rlimit_cpu sets the maximum number of CPU seconds that a

Redirection of TCP Connections

ri
st

di

For example:

File: /etc/xinetd.d/telnet

File: /etc/xinetd.d/service_config
+ redirect = 172.23.52.18 23

ib

oh

pr

PY

With Xinetd running on Linux, this is not often used because Netfilter
has more powerful redirection.

ite

d.

Additionally, services can be launched with a different priority to give


higher or lower multi-tasking preference. This is configured using the
nice attribute.

is

stream
no
root
/usr/etc/in.telnetd
8M
20

=
=
=
=
=
=

An often unused feature of Xinetd is the ability to redirect a TCP


connection to another host. This is sometimes used when Xinetd is
run on a multi-homed firewall. For example within the telnet service
configuration file, telnet connections can be redirected to another
host with the following line:

tio
bu

service telnet
{
socket_type
wait
user
server
+
rlimit_as
+
rlimit_cpu
}

The Xinetd system has fine-grained logging abilities. You can specify
exactly what you would like logged, and you can log to SYSLOG or
bypass SYSLOG and log directly to files. The log_type attribute is
used to specify where to log.

AT

Xinetd can set limits on the amount of memory and CPU that
launched services can consume. This can be used to protect against
potentially malicious clients, or buggy launched daemons.

1-5

TCP Wrappers

TCP Wrappers

ed

AL

riz
ho
ut
na

EV

Generic Application Level Network ACL framework


/etc/hosts.allow
/etc/hosts.deny
Originally used to secure inetd launched services via binary
/usr/sbin/tcpd
Many Modern network daemons link against libwrap
sshd, vsftpd, xinetd, rpcbind
Some large network daemons forgo TCP Wrappers and implement
their own network ACL method
Apache
Samba

Securing Inetd

pr
re

Originally TCP Wrappers was primarily used to provide network ACLs


for services launched from Inetd. To change a standard Inetd telnet
service entry in /etc/inetd.conf to use TCP Wrappers, use tcpd to
wrap the service:

t
uc

od

AT

TCP Wrappers provides another tool useful for limiting access to


services by remote IP address or addresses, hostname or domain.
Using TCP Wrappers allows services to be accessible to trusted
hosts and denied to un-trusted hosts. This gives the system
administrator some flexibility for providing services instead of only
being able to provide them to either everyone or no one.

IO

n
io

in.telnetd

or

Centralized Administration

File: /etc/inetd.conf
telnet stream tcp nowait root /usr/sbin/in.telnetda

di

A nice feature of TCP Wrappers is that it provides a centralized


administrative point where access to all services on the system can
be managed; TCP Wrappers works by "wrapping around" existing
applications. Before incoming network connections get passed to the
appropriate daemon, they first get processed by TCP Wrappers,
which checks two files, /etc/hosts.allow and /etc/hosts.deny, and
then either drops the connection or passes it on to the appropriate
service.

+ telnet stream tcp nowait root /usr/sbin/tcpda

in.telnetd

ri
st

tio
bu

The network ACL abilities of TCP Wrappers can be compiled into a


program via the libwrap library. This allows a service to get all the
benefits of TCP Wrappers without performing a chained launch via
tcpd (which may not even be possible).

is

O
ite

PY

ib

oh

pr

Rules in the /etc/hosts.allow file specify hosts which can connect


to specific services, while /etc/hosts.deny specifies hosts to deny
access to for listed services. /etc/hosts.allow is read first, if it
exists, then /etc/hosts.deny.

libwrap

d.

1-6

The /etc/hosts.allow & /etc/hosts.deny Files


/etc/hosts.allow

EV

If a rule matches:
access is granted to the requested service rule checking
ends

/etc/hosts.deny

Access Control Rules

ed

AL

riz
ho
ut
na

If a rule matches:
access is denied to the requested service rule checking
ends
If there are no matches in either file, access is granted
Basic Syntax
daemon_list : client_list

The client_list Syntax

pr
re

The client_list is used to match the client's source IP address. This


can be specified in a variety of ways.

t
uc

od

AT

When incoming connections are wrapped, the hosts.allow and


hosts.deny files are checked for a match. A match means that both
the daemon_list and client_list pair matches.

or

Within each file, more specific rules should come first, then general
rules. If this isn't done, the more specific rules will never be matched
against when a more general rule is matched before ever checking
the more specific one.

Examples

PY

ib

oh

pr

sshd: 10.100.0.5
in.telnetd: 192.168. 10.5.2.0/255.255.255.0
in.ftpd sshd: .gurulabs.com

ite

For libwrap linked binaries, such as sshd, the daemon_list is usually


the binary name.

is

The daemon_list should be one (typical) or more daemon names.


When wrapping Xinetd services, the daemon_list should be the
name of the binary used in the server attribute. If the service doesn't
have a server attribute, usually an internal or redirect service, then the
daemon_list should contain the service name.

tio
bu

ri
st

di

The daemon_list Syntax

y An IPv4 address in the form n.n.n.n. For example, 192.0.2.4.


y An IPv4 network in the form n.n.n.n/m.m.m.m. For example
192.168.32.0/255.255.255.0. Note that CIDR notation is not
supported.
y An IPv6 address in the form [n:n:n:n:n:n:n:n]. For example
[3ffe:505:2:1::].
y An IPv6 network in the form [n:n:n:n:n:n:n:n]/m. For example
[3ffe:505:2:1::]/64.
y A partial IPv4 address terminated with a period. For example,
192.168. will match all IP addresses starting with 192.168. Note
that a single complete IP can also be used.
y A domain starting with a period. For example, .gurulabs.com.
This will match any IP that reverse resolves to a host in the
gurulabs.com domain.
y The wildcards * and ? can be used to match hostnames or IP
address.

IO

n
io

It is important to note that both files are checked top down, with
hosts.allow checked before hosts.deny. If no matches are found
then access is granted.

d.

1-7

/etc/hosts.{allow,deny} Shortcuts

ed

AL

riz
ho
ut
na

EV

Wildcard shortcuts
ALL
LOCAL
KNOWN
UNKNOWN
PARANOID
Operators
EXCEPT

The EXCEPT Operator

Shortcuts in the /etc/hosts.allow & /etc/hosts.deny Files

pr
re

The EXCEPT operator is useful when you want to match nearly all
hosts in a client_list. For example, you have a kiosk machine in
your lobby and you don't want people using the kiosk machine to
make connections to wrapped services on your corporate hosts. One
possible solution would be use TCP Wrappers and have:

File: /etc/hosts.{allow,deny}

File: /etc/hosts.{allow,deny}

IO

n
io

ALL: 127. [::1]


sshd: ALL

t
uc

od

AT

To ease and shorten rule writing, TCP Wrappers defines several


wildcard short cuts that can be used. The most commonly used
wildcard is the ALL wildcard. It always matches. For example:

ALL: .gurulabs.com EXCEPT kiosk.gurulabs.com

or

is

O
ite

PY

ib

oh

pr

d.

1-8

The problem with nesting the EXCEPT operator is that such practices
very quickly lead to the creation of rules that even the original author
will have difficulty understanding. This usually means that the
configuration which caused the confusion does more or less than
what was expected, instead of doing what the author (or editor) of
the configuration intended.

y The KNOWN wildcard will match an IP address for which a reverse


DNS lookup successfully resolves to a host name.
y The UNKNOWN wildcard will match an IP address that doesn't
reverse resolve to a host name.
y The PARANOID wildcard matches any host whose reverse and
forward name lookups are not-consistent.

Although the EXCEPT operator can be nested, this is strongly


discouraged.

tio
bu

The KNOWN, UNKNOWN, and PARANOID wildcards are used to match


based on whether or not the IP address reverse resolves to a host
name. Be careful using these keywords, as DNS problems can cause
what would normally match to not match.

Name and IP Address Matching

Note, that this rule would have to be added to each system which
you wanted to protect.

ri
st

di

The LOCAL wildcard matches any host whose name doesn't contain a
dot. This means that hosts within your same domain would match.

Advanced TCP Wrappers

Creating Banners with TCP Wrappers

ed

AL

riz
ho
ut
na

EV

Printing banner
banners
Running an alternative daemon
twist
Running a command on connection
spawn
Default deny configuration
ALL: ALL in /etc/hosts.deny
Put allowed hosts in /etc/hosts.allow
At least ALL: 127. [::1]

Using the spawn Option

pr
re

TCP Wrappers supports tokens that are replaced before a spawn is


performed. These tokens are supported:

t
uc

od

AT

One commonly sought after technique is instead of blocking


connections only, to block connections and display a message at the
same time.
This is done by creating a banner file, for example:

The client (server) host address

%a

or

IO

n
io

File: /etc/deny-banner
+
Attention, this is a private host!
+
To request access, email <root@example.com>

Token Function

di

%d

The daemon process name

%h

The client host name or address

%n

The client host name or unknown or paranoid

%p

The daemon pid


Server info: daemon@host, daemon@address

%s

tio
bu

File: /etc/hosts.deny
+ ALL: ALL : banners /etc/deny-banner

Client info: user@host, user@address, host name or an


address

ri
st

With appropriate allowed hosts already listed in the hosts.allow file,


add the following to the hosts.deny:

%c

This line would finger the connecting host and email the output with
a subject line containing the Client info.

ite

PY

ib

File: /etc/hosts.deny
+ in.telnetd: ALL : spawn (/usr/sbin/safe_finger -l @%h |a

d.

File: /etc/hosts.allow
+ in.telnetd: .badguys.com : twist exec /bin/ft.pl

oh

Sometimes, you may want to redirect connections into a fake server.


This can be used as part of a honeypot to catch and monitor network
attackers. For example to redirect telnet connections to a fake server:

Client username obtained via the ident protocol

pr

Using the twist Option

%u

is

Note that you can use ANSI or VT100 screen control characters as
well in banner files.

/bin/mail -s "Connect from %c" admin@example.com) &

1-9

Basic Firewall Activation

ed

AL

riz
ho
ut
na

EV

Enabled during install


Builds a stateful packet-filter firewall using Netfilter
http://netfilter.kernelnotes.org/
Red Hat Enterprise Linux firewall configuration tool
system-config-firewall (GUI and text-mode front-ends)

Firewalls on Red Hat Enterprise Linux Systems

pr
re

t
uc

od

AT

The firewall creation code built into the Anaconda installer has two
modes, Enabled (the default) and Disabled. It uses stateful rules. All
network traffic that is part of (or related to) some established
connection initiated by the host is automatically allowed along with
inbound ICMP and IPSec connections. All other, externally initiated,
inbound connections are rejected.

IO

n
io

or

After the system is installed, the firewall can be configured by using


the system-config-firewall tool.

di

is

O
ite

PY

ib

oh

pr

respectively. These files can be edited by hand, but depending on


configuration, may be overwritten.

tio
bu

The iptables and ip6tables service scripts load the contents of


/etc/sysconfig/iptables and /etc/sysconfig/ip6tables,

ri
st

The activation of the firewall is handled by Sys-V init scripts. The


iptables and ip6tables service scripts consult
/etc/sysconfig/iptables-config and
/etc/sysconfig/ip6tables-config for configuration options. These
options include loading and unloading Netfilter kernel modules and
saving the current firewall configuration when stopping or restarting.

d.

1-10

Netfilter: Stateful Packet Filter Firewall

The iptables Command

ed

AL

riz
ho
ut
na

EV

Part of Linux 2.4/2.6 kernel Netfilter firewalling subsystem


Flexible rules system
Filter by IP, MAC, protocol, port, user, frequency etc.
Connection tracking
Packets may be filtered based on connection state: NEW,
ESTABLISHED, RELATED, INVALID
Userspace tools
iptables: used to manipulate Netfilter configuration
iptables-save: Save configuration to STDOUT
iptables-restore: Load saved configuration from a file

userspace, where they can be further analyzed or manipulated.

pr
re

Once the iptables command has been used to configure a firewall,


this can be saved using the iptables-save command:

AT

iptables works by having chains of rules specifying how packets

od

should be filtered. Packets flow down the chains, and at every rule
they can be blocked, dropped, redirected to other chains or passed
on to the next rule. Netfilter can be configured in a stateful fashion
making it possible to filter packets by connection state, which can
especially be useful when configuring a firewall safely to permit
baroque protocols like FTP. In addition, maintaining state makes it
possible for Netfilter to prevent certain kinds of denial-of-service
attacks. It also makes it possible for Netfilter to deal with fragments
more safely than earlier Linux firewalls such as ipchains.

t
uc

# iptables-save > iptables

or

IO

n
io

The iptables-restore command can then be used to load this


configuration.

tio
bu

is

O
ite

PY

ib

oh

d.

Similarly, once Netfilter has matched a packet, it has a wide variety of


possible behaviors it can apply to the packet, including logging,
blocking, dropping, rejecting (with arbitrary ICMP error messages),
mirroring or redirecting the packet to local ports. It can also modify
the packet in various ways, such as by source or destination NAT,
source or destination PAT, and changing TOS bits or TTLs, to name a
few. It can even hand the packets to arbitrary programs running in

# service iptables save


. . . output omitted . . .

pr

In addition, Netfilter has very powerful selection criteria. It can match


packets at any point in their travel through the Linux network stack by
source or destination interface, TCP source or destination ports, TCP
flags, TCP options, UDP source or destination ports, ICMP types,
state, TOS bits or locally generated UID, GID, PID or SID. It even has
the ability to "mark" packets in a way that is invisible which can be
used to manipulate them later, or to impose rate limits on packets
matching any of the criteria available to Netfilter.

ri
st

di

On Red Hat Enterprise Linux, the /etc/init.d/iptables and


/etc/init.d/ip6tables init scripts can be used to automate the use
of these tools for persistence on boot, loading the ipv4
/etc/sysconfig/iptables and ipv6 /etc/sysconfig/ip6tables
firewall rules. Instead of using the iptables-save command to save
an existing firewall rule, use the init script:

1-11

Netfilter Concepts

Netfilter Concepts

ed

AL

riz
ho
ut
na

EV

Tables are maintained of actions to be performed on a packet at


various stages in its travels through the network stack
Tables contain set(s) of chains
Chains contain actual rules
General syntax:
If a packet matches X, then do Y

pr
re

Packet Input
ppp0
eth0
eth1

Packet Output

PREROUTING
nat, mangle

FORWARD

Routing
Decision

ppp0
eth0
eth1

POSTROUTING
nat, mangle

filter, mangle

t
uc

od

AT

By default, three chains exist: INPUT, FORWARD, and OUTPUT.


When a packet comes into the box, the kernel looks at the packet's
destination. If the destination is local, the packet gets handed off to
the INPUT chain. If the destination is not local and the machine has
IP forwarding enabled, the packet gets handed to the FORWARD
chain. If the destination is not local and the machine does not have IP
forwarding enabled, or has forwarding enabled but cannot forward
the packet (due to routing table configurations, for example), the
packet gets dropped. All local packets originated by programs
running on the system, leave via the OUTPUT chain.

INPUT

or

IO

n
io

filter, mangle

Routing
Decision

Legend

CHAIN
table

ce

Spa

Spa

ce

Local Services and Processes

Three tables exist to organize chains: filter, nat, and mangle. This
chart lists which chains are available in each table

Chain

is

filter nat mangle

PREROUTING

X
X

PY

POSTROUTING

X
X

d.

OUTPUT

ite

FORWARD

ib

INPUT

oh

pr

1-12

tio
bu

In addition to the default chains, user-defined chains can be created.


Rules to apply to packets can be created within user-defined chains
the same as built-in chains. These rules can even hand off packets to
other chains, allowing Netfilter great flexibility when handling packets.

nel
Ker

r
Use

ri
st

di

If network address translation (NAT) is being used, two additional


chains will exist: PREROUTING and POSTROUTING. If the
PREROUTING chain exists, all packets will pass through it as they
come into the box, before the kernel even decides whether to pass
them through the INPUT or FORWARD chains. This chain is where
destination network address translation can be implemented.
Similarly, if the POSTROUTING chain exists, all packets will pass
through it after they pass through the OUTPUT chain. This chain is
where source network address translation can be implemented.

OUTPUT
filter, mangle, nat

Using the iptables Command

EV

Adding new rules


Add a rule to block all traffic from host 10.1.2.3:

# iptables -A INPUT -s 10.1.2.3 -j DROP


Deleting existing rules
Delete rule that blocks all traffic from 10.1.2.3

# iptables -D INPUT -s 10.1.2.3 -j DROP

AL

riz
ho
ut
na

Listing existing rules


List all rules in all chains (or in just one specified chain):

# iptables -P FORWARD DROP

ed

Manipulating Rules

# iptables -L chain_name
Setting chain policy
To set the FORWARD chain's policy to DROP:

Listing Rules

pr
re

To list rules in chains, the basic command is (Rules in a specific chain


can be listed by specifying the chain of interest):

od

AT

The core functions of any firewalling software revolve around creation


of the rule sets to specify behaviors to apply to specific packets.

t
uc

Rules are added by using the -A option with the name of a chain to
specify that a rule is being added to that chain, and then supplying
the rule to be added. This iptables command would add a rule to
the INPUT chain which limits ICMP ping requests coming in via eth0
to one per second:

# iptables -L CHAIN
. . . output omitted . . .
Description

-n

Do not do DNS lookups

-v

Provide verbose output

or

IO

n
io

Option

-x

tio
bu

If no rules have matched by the time Netfilter reaches to bottom of a


built-in chain, that chain's policy takes effect. The policy can be set
using the -P option to either ACCEPT or DROP:

oh

ite

PY

# iptables -P CHAIN DROP

ib

d.

To delete all the rules in a chain use the -F (Flush) chain operator. If a
CHAIN is not specified, all rules in all chains in the specified table (the
filter table if the -t option is not used) are flushed:

Built-in Chain Policies

pr

Flushing all the rules

--line-numbers Show line numbers for each rule

is

# iptables -D INPUT -p icmp --icmp-type echo-requesta


-m limit --limit 1/s -i eth0 -j ACCEPT
# iptables -D INPUT 37

Provide exact values (do not round)

Rules can be deleted in two different ways, either by specifying the


exact rule to delete or by specifying the number of the rule, which
can be obtained by analysis of the output from iptables -L. For
example, if rule 37 limited incoming traffic to one ping request per
second, it could be deleted by either of these methods:

ri
st

di

# iptables -A INPUT -p icmp --icmp-type echo-requesta


-m limit --limit 1/s -i eth0 -j ACCEPT

# iptables -F CHAIN
1-13

Netfilter Rule Syntax

Match Specification

ed

AL

riz
ho
ut
na

EV

Zero or more Match Specifications


Specify certain property/value pairs of a packet to match
All or nothing
Zero or one Targets
What should be done when traffic matches this rule?
Policy Considerations
Default-open approach
Default-closed approach

pr
re

complex (like networking). A default-closed approach will yield better


results, is easier to build, maintain & update and is more secure.

AT

There are many options that can be used to match traffic. When
multiple switches are used on the command line, all of the conditions
listed must be satisfied in order for the rule to match. If any part does
not match, Netfilter moves on to the next rule in the chain, without
taking the action specified by the rule's target.

t
uc

od

To build default-closed Netfilter firewalls, the filter table's build-in


chains, INPUT, FORWARD and OUTPUT need their policy set to DROP.

IO

n
io

Targets

or

Only when every item in the match_spec has successfully matched


the packet being examined by Netfilter, will the target come into play.
Most of the time, rules processing will cease after Netfilter has done
with the packet as specified by the target.

C
O
ite

PY

ib

oh

d.

1-14

pr

From a security perspective, default-open is (almost) always the


wrong choice. This is especially true when the system involved is

is

In the default-closed model, the system examines the policy to see if


there is a reason to permit access. Otherwise, access will be denied.

In the default-open model, the system will examine the policy to see
if there is a reason to deny access and, if none can be found, will
grant access. Rules must be written to explicitly deny anything that
should not be allowed.

tio
bu

There are two different ways in which policy based systems can be
built. They are referred to as the "default-open" and the
"default-closed" models.

ri
st

di

Policy Considerations

Targets

The DROP Target

ed

AL

riz
ho
ut
na

EV

Most targets cause rule checking to cease when followed


DROP
REJECT
ACCEPT
Some targets cause rule checking to continue after processing
LOG

The ACCEPT Target

pr
re

When a rule whose target is ACCEPT matches a packet, Netfilter will


let that packet through with no further rule checking.

t
uc

od

AT

When a rule whose target is DROP matches a packet, Netfilter throws


the packet away without further rule checking. There is no other
action taken. No response is sent. No user-space daemon or other
program on the system will ever know the packet even existed.

The LOG Target

or

di

The REJECT Target

IO

n
io

One major security advantage of the DROP target's behavior is that it


minimizes the potential load that unwanted traffic can have on the
system and/or network behind the firewall.

Remember, any traffic that matches the match_spec portion of a rule


with the ACCEPT target will not be filtered further by Netfilter. Make
sure that such rules are built so as to not allow unwanted traffic
through.

When a rule whose target is LOG matches a packet, Netfilter will send
information about that packet to Syslog. Since Netfilter is a part of
the kernel, those log messages will be sent from the kernel using the
kern facility to syslogd.

tio
bu

ri
st

If the DROP target were referred to as the "rude" way to block traffic,
then the REJECT target might be called the "kind" way. When a rule
whose target is REJECT matches a packet, Netfilter throws the packet
away with no further rule checking, just like with the DROP target, but
also sends an ICMP response to the REJECT'ed packet's sender. Just
as with DROP'ed packets, user-space programs will never know of the
packet's existence.

is

pr

The only drawback to using the LOG target from a security


perspective, is that an attacker who knows or discovers that a log
message is generated when certain traffic hits the machine could use
that knowledge to cause the system to flood its syslog process,
possibly causing a DoS. Because of this, rules with the LOG target
should include rate limiting.

ite

PY

ib

oh

d.

There are some potential disadvantages of using the REJECT target,


from a security perspective. The machine the firewall is running on
can become visible when traffic comes in that is REJECT'ed but was
not destined for the firewall, depending on the chosen ICMP
message(s) to return. Also, if an attacker discovers that your firewall
will generate traffic in response to particular traffic that hits the
system, they could abuse that knowledge to create extra load on your
network or on another network.

Rule processing will continue with the next rule following a rule with
a matched LOG target. To log traffic before dropping it, create two
rules with the same match_spec; the first with the LOG target and the
second with the DROP target.

1-15

Common match_specs

Matching IP Addresses

ed

AL

riz
ho
ut
na

EV

IP Address
Source [-s] or destination [-d] address
Interface
Input [-i] or output [-o] interface
Protocol
-p
TCP, UDP & ICMP
For these protocols, iptables can match on most header values

pr
re

For the TCP, UDP & ICMP protocols, there are several additional
options available for narrowing down exactly what traffic to match.

AT

There are two match_spec options which can be used to match IP


addresses in the IP packet header. For the packet's source address
use the -s option. The -d option will match against the IP packet's
destination IP address. The address can be specified as a single
address or and an address/netmask pair using CIDR notation.

Matching TCP or UDP Ports

od

t
uc

If either tcp or udp has been specified as the protocol to the -p


option, you can then use the --sport and --dport options to match
against the source or destination TCP or UDP port, respectively. The
value specified to these options can either be a single port, or a
range of ports.

IO

or

# iptables -A INPUT -p tcp --dport 80 -j ACCEPT


# iptables -A INPUT -p udp --sport 1024:65535 --dport 53 a
-j ACCEPT

# iptables -A INPUT -p icmp --icmp-type port-unreachable a


-j ACCEPT

PY

ib

oh

To get a list of all parameters the --icmp-type option accepts, run:

ite

# iptables -p icmp -h

d.

1-16

# iptables -A INPUT -p 57 -j DROP


# iptables -A INPUT -p egp -j DROP

pr

The IP packet's protocol field can be tested using the -p option.


Protocols specified by name must be found in the /etc/protocols
file, as the iptables command needs to give Netfilter a number to
work with.

If icmp is the value given to the -p option, then the --icmp-type


option can be used. Despite the name of this option, the values
specified cover both the ICMP type and code.

is

Matching the Protocol

Matching ICMP

# iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

tio
bu

It is good practice to only allow certain traffic through based on


which network it came from. With multi-homed firewalls (including
routers) this can be accomplished using the -i and the -o options to
match against the input & output interfaces, respectively, associated
with the packet being tested.

ri
st

di

Matching the Interface

n
io

# iptables -A INPUT -s 10.100.0.3 -j DROP


# iptables -A OUTPUT -d 10.100.0.0/24 -j ACCEPT

Connection Tracking
NEW
No match in Netfilter's connection tracking state engine

EV

ESTABLISHED
The packet matches an ongoing communication

RELATED

The packet is not a direct part of a tracked connection

INVALID

riz
ho
ut
na

Stateless vs. Stateful

ed

AL

The packet is bogus

The RELATED State

pr
re

A packet will match the RELATED state when it was generated in


relation to some other communication (which is being tracked), but is
not actually part of that communication. The best example is an ICMP
packet generated in response to TCP or UDP traffic.

The state Module

# iptables -A INPUT -m state --state RELATED -j ACCEPT

t
uc

od

AT

Stateful packet-filtering adds the ability to consider a packet within


the context of an ongoing communication. In order to be able to
provide this capability, Netfilter must track a connection. This is
implemented in Netfilter's state module.

IO

n
io

The INVALID State

Once the state module is loaded, you can then use the --state
option to match a packet according to its Netfilter connection-tracking
state.

# iptables -A INPUT -m state --state INVALID -j REJECT

or

In order to use the state module, it must be loaded. This has to be


done on each iptables command line that you want to use stateful
rules with. The -m option is used to load a module.

O
ite

PY

ib

d.

# iptables -A INPUT -p tcp --dport 80 -m state --state NEW a


-j ACCEPT

oh

A packet will match the NEW state when it is not part of a


communication already being tracked by Netfilter's state module.

The NEW State

pr

# iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT

is

A packet will match the ESTABLISHED state when it is part of a


communication that is being tracked by Netfilter's state module. This
is not limited to just TCP, but also works with UDP and ICMP.

tio
bu

The ESTABLISHED State

ri
st

di

Packets that do not match another state, match the INVALID state.

1-17

SELinux Security Framework

Security Administrator Specifies Policy

ed

AL

riz
ho
ut
na

EV

Allows administrator to specify security policy


Policy defines the "correct operation" of the system
interaction of processes and files
use of POSIX capabilities
use of system resources (shared memory, etc.)
network sockets
interaction of processes (signals, pipes, IPC, etc.)
Uses labels called "Security Context"s
identity:role:type:security_level
Occasional relabeling of the filesystem may be required

pr
re

The security context (sometimes called the label) is a string and


consists of the following components:

AT

The SELinux extensions allow an administrator to define a security


policy. This policy can be very simple providing only basic limitation,
or it can be very detailed defining which of the many complex
interactions of system components are to be allowed. One of the
advantages of the SELinux security framework is its flexibility in
allowing security administrators to create a policy that meets their
TCB goals. The policy is then loaded and enabled so that the Linux
kernel can enforce compliance with the policy.

identity Name of the 'owner' of the object. System objects have

t
uc

od

or

IO

n
io

O
ite

PY

ib

oh

pr

d.

1-18

is

The security policy determines the permissible interactions between


objects on the system. To determine if a specific interaction is
permitted, the system compares the security context of the
interacting objects with the security policy.

Security Context

tio
bu

When a security administrator creates a policy, he or she is


essentially detailing the interactions that are expected for correct
operation of the system and its services. For example, a program
running under a specific security context should either be allowed to
interact with a given file, or it should not. The policy defines the
allowed level of interaction between the program and then the kernel
enforces it. If the program later tries to interact with the file in some
non-permitted way, or perhaps interact with some completely
different file, then the kernel will deny the attempt.

ri
st

di

Policy Defines the "Correct Operation" of the System

special identities. Unix user accounts can be mapped to specific


identities. A default identity (user_u) exists for Unix accounts not
explicitly mapped to an identity. Identity controls the available
roles.
role For processes, lists the domain of the process. For files, has
a placeholder value (object_r).
type Classifies the object as to its specific security needs; that is
each object that has unique (with respect to the other objects)
security needs will be assigned a unique type. Conversely, objects
with common security needs can share the same type.
security_level Compound value in the form sX-sX:cY-cY where
sX is the sensitivity level (valid values from s0s15) and cY is the
category (c0c255). Used by the MCS/MLS policies.

Relabeling Files

t
uc

od

AT

pr
re

ed

AL

riz
ho
ut
na

EV

If files on the filesystem have the wrong (or no) security context label,
then applications can fail. The most common reasons that security
labels become incorrect is either from copying files, or running the
system with SELinux disabled. You can relabel files or directories
using the setfiles, restorecon, or chcon commands. You can
relabel the entire filesystem using the fixfiles relabel command.

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

1-19

Choosing an SELinux Policy

SELinux Policies

ed

AL

riz
ho
ut
na

EV

Targeted
separate types for most commands and services
everything else runs under the unconfined_t, kernel_t, or
initrc_t domains
MLS (Multi-Level Security)
implements sensitivity and category security labels
primarily used in military and government
Minimum
Everything runs unconfined_t
All targeted modules are available if desired
Selected via /etc/selinux/config

Switching Policies

pr
re

It is simple to switch between the targeted and MLS policies (or


minimum):

od

AT

Three different SELinux policies are included with the SELinux


reference policy: targeted, MLS, and minimum.

t
uc

targeted policy Originally focused on the network services most


likely to be the source of a security breach (e.g. Apache, BIND).
With the targeted policy, any applications that do not have a
policy defined will run under the unconfined_t, kernel_t, or
initrc_t domain.
MLS policy Multi Level Security provides a policy based around
security levels and categories. The goal is to get LSPP, RBAC, and
CAPP certification at EAL 4+. The security model provided by this
policy is most commonly used in military or government
deployments and not appropriate for typical corporate systems,
with the possible exception of high-profile, sensitive servers.
Minimum Policy The minimum policy was introduced in Fedora
10 as a variant of the targeted policy, preserving the unconfined_t
target as the default: all services run as unconfined_t, kernel_t,
or initrc_t, unless configured to be confined by the
administrator.

or

IO

n
io

1. Verify that the policy files for the desired policy exist. They are
contained in the following RPMS: selinux-policy
(configuration), selinux-policy-minimum,
selinux-policy-targeted, and selinux-policy-mls.
2. Set the active policy in /etc/selinux/config to
SELINUXTYPE=mls, SELINUXTYPE=minimum, or
SELINUXTYPE=targeted.
3. Reboot the machine for the new policy to take effect.

tio
bu

SELinux functionality can also be controlled by passing parameters to


the kernel on boot. To disable SELinux a single time at boot, use the
interactive GRUB interface to add one of two options to the kernel's
arguments. To boot into permissive mode, add enforcing=0. To boot
without loading SELinux at all, add selinux=0.

is

O
ite

PY

ib

oh

pr

d.

1-20

ri
st

di

Initial development versions of SELinux contained a single policy that


was similar to the original strict policy. Due to conflicts generated by
the nascent policy code, SELinux was disabled by default in
distributions that first started shipping SELinux. In subsequent
versions of Linux, SELinux was enabled and a targeted policy was
implemented.

SELinux Kernel Options

SELinux Commands
sestatus

EV

display current SELinux settings


-v displays contexts for files and processes listed in

/etc/sestatus.conf
chcon set the security context of a file or files

ed

AL

riz
ho
ut
na

Many core commands have new options to support Security Context


labels

permissions. The three options that are used for changing an object's
context are -u for user, -r for role, and -t for type. Like many Unix
commands, the -R option performs recursive file modification.

New Commands Included with SELinux

pr
re

od

AT

Several new commands were created to provide an interface to the


new SELinux functionality. These commands are provided in the
policycoreutils package. Descriptions and example invocations of
these new commands follow.

t
uc

IO

n
io

The sestatus Command

# ls -Z
-rw-r--r-- guru guru system_u:object_r:user_home_t file.txt
# chcon -t staff_home_t file.txt
# ls -Z
-rw-r--r-- guru guru system_u:object_r:staff_home_t file.txt

or

The sestatus command can be used to display the current state of


an SELinux enabled system. If the -v option is used then the report
will include the security contexts of all the files and processes listed
in the /etc/sestatus.conf file. This allows an administrator to
quickly verify the context of key objects. This can be helpful in
spotting incorrect context on critical files that may commonly have
their context clobbered due to improper handling.

Supporting Security Context Labels

O
ite

PY

ib

oh

d.

Security contexts on system objects can be changed with the chcon


command. It has similar functionality and syntax to the chmod
command, but changes contexts instead of traditional Unix

$ ps -eZ
. . . output omitted . . .

pr

The chcon Command

is

enabled
/selinux
enforcing
enforcing
21
targeted

tio
bu

# sestatus
SELinux status:
SELinuxfs mount:
Current mode:
Mode from config file:
Policy version:
Policy from config file:

ri
st

di

Many of the core commands that work with files have had options
added to support the security context labels for files. When possible,
these commands have used the -Z option--with the meaning of the
option varying greatly command to command. Examples of
commands that have been patched to support SELinux in some way
include: login, su, id, ls, ps, cp, mv, stat, and find. For example:

1-21

SELinux Booleans

Booleans

ed

AL

riz
ho
ut
na

EV

Easy way of activating certain policy rules


Immediate changes made with:
setsebool [-P]
togglesebool
"Batch" changes made via /selinux filesystem
echo X > /selinux/booleans/boolean_name
"Batch" must be committed to take effect
echo 1 > /selinux/commit_pending_bools

Toggling Booleans

pr
re

The most common tool for activating or disabling a boolean value is


the setsebool command. Basic usage is as follows:

od

AT

To make SELinux more flexible and easy-to-use, categories of policy


have been added that can be turned on or off. These boolean values
can be toggled in real time and immediately become active. Most are
intuitively named such as spamassassin_can_network, user_rw_usb,
and named_write_master_zones.

t
uc

# setsebool [-P] boolean_name value

n
io

The value field may be true or 1 to enable the boolean; false or 0 to


disable it. The togglesebool command can be used to toggle a
boolean value on or off. Both the setsebool and togglesebool
commands immediately make changes active in the running policy.

or

IO

A complete list of possible boolean values for the current running


policy can be found with the sestatus -b or the getsebool -a
commands:

It is also possible to enable boolean policy values in the selinuxfs.


This virtual filesystem is similar to /proc, and is usually mounted on
/selinux. Like /proc, values can be echoed into /selinux to change
SELinux's current configuration. An example could be:

tio
bu

# echo 1 > /selinux/booleans/allow_ypbind

Changes to files in /selinux/booleans do not take effect


immediately, instead SELinux must be alerted to the change. The
following command atomically commits all changes made to boolean
files:

is

PY

ib

oh

pr

off
off
off
off
off
off
off

ri
st

di

# sestatus -b
. . . snip . . .
Policy booleans:
allow_httpd_anon_write
allow_httpd_apcupsd_cgi_script_anon_write
allow_httpd_bugzilla_script_anon_write
allow_httpd_mod_auth_pam
allow_httpd_squid_script_anon_write
allow_httpd_sys_script_anon_write
allow_java_execstack
. . . snip . . .

ite

# echo 1 > /selinux/commit_pending_bools

d.

Booleans set using the -P (persistent) option will be written to the


policy file on disk and become permanant (i.e. survive a reboot).

1-22

Graphical SELinux Policy Tools


system-config-selinux

The system-config-selinux Command

pr
re

ed

AL

riz
ho
ut
na

EV

status, booleans, file-labeling, SELinux user creation and


mapping, translations for MLS, network ports, and control of
loaded policy modules

t
uc

od

AT

Newly introduced in RHEL6 this tool provides a unified graphical


interface for most of the system administration tasks associated with
SELinux:

or

IO

n
io

y selection of SELinux mode


y force relabel of filesystem on next boot
y view and modify SELinux booleans
y view and modify file context labeling expressions
y create SELinux users and map them to Linux user accounts and
roles
y define translations for MLS security-levels/categories
y define network ports accessible by SELinux types
y add and remove policy modules

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

1-23

or

N
is

ite

d.

PY

ib

oh

pr

C
n

tio
bu

ri
st

di

IO

n
io

AT
t
uc

od

pr
re

ed

AL

riz
ho
ut
na

EV

1-24

Lab 1

EV

Estimated Time: 70 minutes

Task 1: Securing xinetd Services

AL

riz
ho
ut
na

Page: 1-26
Time: 10 minutes
Requirements: b (1 station)

Task 2: Enforcing Security Policy with xinetd

ed

Page: 1-29
Time: 10 minutes
Requirements: b (1 station)

AT

t
uc

od

Page: 1-32
Time: 10 minutes
Requirements: bb (2 stations)

pr
re

Task 3: Securing Services with TCP Wrappers

Task 4: Securing Services with Netfilter

N
C

tio
bu

Page: 1-45
Time: 5 minutes
Requirements: b (1 station)

ri
st

Task 6: SELinux File Contexts

di

Page: 1-41
Time: 20 minutes
Requirements: b (1 station)

or

Task 5: Troubleshooting Practice

IO

n
io

Page: 1-36
Time: 15 minutes
Requirements: bb (2 stations) c (classroom server)

is

O
ite

PY

ib

oh

pr

d.

1-25

Lab 1

Objectives
y Discover what services are running and listening for connections.
y Configure xinetd to provide a variety of limits for connecting to services.

EV

Task
1
Securing xinetd Services

Requirements
b (1 station)

Estimated Time: 10 minutes

AL

The following actions require administrative privileges. Switch to a root login


shell:

AT

t
uc

od

2)

pr
re

$ su -l
Password: makeitso

ed

1)

riz
ho
ut
na

Relevance
Identifying and securing running services is crucial in today's hostile
network environments. xinetd provides several powerful features for
securing the services it provides.

Determine which services are currently configured to run:

or

IO

n
io

# chkconfig --list | grep on


. . . output omitted . . .

tio
bu

3)

ri
st

di

When examining a list of services such as this one, there are some questions that
should always be asked about each one: What is the purpose of the service? Is it
really necessary for this machine?
List the services bound to UDP ports using one of the following commands:

O
ite

PY

ib

oh

d.

List the services listening on TCP ports using one of the following commands:

# netstat -tlp
1-26

4)

pr

Note: all three commands may not be installed on your system.

is

netstat -ulp
lsof -i UDP
ss -uap
. . output omitted . . .

#
#
#
.

# lsof -i TCP
# ss -tlp

EV

5)

Install the in.telnetd server and client for use in the remaining steps:

AL

6)

riz
ho
ut
na

# yum install -y telnet-server telnet


. . . output omitted . . .
Enable telnet for use in testing:

# chkconfig telnet on

ed

7)

File: /etc/xinetd.d/telnet

t
uc

n
io

tio
bu

ri
st

di

Create a new banner file with this content:

IO

= /usr/sbin/in.telnetd
+= USERID
+= DURATION
= 5
= 1
= /etc/go-away.banner

or

8)

od

+
+
+
+

service telnet
{
. . . snip . . .
server
log_on_failure
log_on_success
instances
per_source
banner
}

AT

pr
re

To more tightly secure the telnet service, modify the /etc/xinetd.d/telnet


service configuration file:

is

# service xinetd reload

d.

Cause xinetd to re-read its configuration files and check the log for indications of
errors:

ite

9)

PY

ib

oh

pr

File: /etc/go-away.banner
+ This is a secured system. Unauthorized access is prohibited.
+ All access is logged.

1-27

Test the new telnet configuration by attempting to open two simultaneous


telnet connections:

AL

riz
ho
ut
na

10)

EV

. . . snip . . .
# tail /var/log/messages | grep xinetd
xinetd[1714]: Starting reconfiguration
xinetd[1714]: Swapping defaults
xinetd[1714]: Reconfigured: new=1 old=0 dropped=0 (services)

t
uc

od

AT

pr
re

ed

# telnet localhost
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is ^].
This is a secured system. Unauthorized access is prohibited.
All access is logged.
. . . snip . . .
login: guru
Password: work
Last login: Tue May 31 13:59:06 from localhost.localdomain
$ ]
telnet> z

IO

n
io

or

[1]+ Stopped
telnet localhost
# telnet localhost
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is ^].
This is a secured system. Unauthorized access is prohibited.
All access is logged.
Connection closed by foreign host.
# fg
telnet localhost

tio
bu

ri
st

di

xinetd blocks the connection due to the configured


per_source limit.

is

PY

ite

d.

1-28

# tail /var/log/messages
. . . snip . . .
xinetd[5497]: START: telnet pid=28392 from=127.0.0.1
xinetd[5497]: FAIL: telnet per_source_limit from=127.0.0.1
xinetd[5497]: EXIT: telnet status=0 pid=28392 duration=47(sec)

ib

Examine the log for evidence of the telnet connection being denied:

oh

11)

pr

Connection closed by foreign host.

Lab 1

Objectives
y Configure a sensor (using xinetd) to log connection attempts.

EV

Task
2
Enforcing Security Policy

Requirements
b (1 station)

with xinetd
Estimated Time: 10 minutes

AL

1)

riz
ho
ut
na

Relevance
Once a security policy - such as "no telnet" - has been established, it is
important to have some mechanism to detect violations of the policy and
report them to the administrator.
Create a new xinetd service configuration file with this content:

ed

t
uc

od

AT

pr
re

File: /etc/xinetd.d/notelnet
+ service notelnet
+ {
+
disable
= no
+
type
= INTERNAL
+
flags
= SENSOR
+
protocol
= tcp
+
port
= 23
+
socket_type = stream
+
wait
= no
+
user
= root
+
log_type
= FILE /var/log/violators
+
banner
= /etc/notelnet-violation.banner
+ }

or

IO

n
io

C
O
ite

PY

ib

oh

d.

3)

pr

File: /etc/notelnet-violation.banner
+ Remember the new security policy!
+ *telnet* is no longer acceptable.
+ Your IP address has been logged.

is

Create a new banner file, with this content:

tio
bu

ri
st

di

2)

Modify the /etc/services file so that the line for the telnet protocol contains an
alias for the new service name. The new line should read:

1-29

4)

notelnet # Telnet

EV

File: /etc/services
- telnet
23/tcp
+ telnet
23/tcp

riz
ho
ut
na

Configure xinetd to use the new notelnet service and check the logs for signs of
problems (correct as necessary):

AL

# chkconfig telnet off


# grep deactivated /var/log/messages
Jul 19 11:13:59 stationX xinetd[5535]: service telnet deactivated

pr
re

Test the new service by trying to connect via telnet:

AT

5)

ed

Examine the log output carefully for any errors, and correct your service definition
if needed.

banner is displayed, logs the attempt, and locks out


that address for 10 minutes.

t
uc

od

# telnet localhost
Trying 127.0.0.1...
Connected to localhost.
Escape character is ^].
Remember the new security policy!
*telnet* is no longer acceptable.
Your IP address has been logged.
Connection closed by foreign host.

IO

or

tio
bu

is

Cleanup

ri
st

di

Look at the log for information about the connection activity:

# tail /var/log/violators
FAIL: notelnet address from=::1

pr

Clean up the xinetd services so that future lab exercises will operate correctly:

PY

ite

# chkconfig notelnet off


# chkconfig telnet off

ib

oh

7)

n
io

6)

d.

1-30

8)

Modify the /etc/services file so that the line for the telnet protocol no longer
contains the alias for the notelnet service:

EV

notelnet # Telnet

t
uc

od

AT

pr
re

ed

AL

riz
ho
ut
na

File: /etc/services
- telnet
23/tcp
+ telnet
23/tcp

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

1-31

Lab 1

Objectives
y Use TCP Wrappers to secure various services.

EV

Task
3
Securing Services with TCP

Requirements
bb (2 stations)

Wrappers
Estimated Time: 10 minutes

AL

Install the vsftpd package:

od

Configure TCP wrappers to explicitly permit certain service/IP pairs:

t
uc

2)

AT

pr
re

# yum install -y ftp vsftpd


. . . output omitted . . .

ed

1)

riz
ho
ut
na

Relevance
A frequent security need is the ability to prevent connections to services
from specific IP addresses. The TCP Wrapper framework provides a
centralized place to enforce these IP address based connection
restrictions.

or

IO

n
io

File: /etc/hosts.allow
+ ALL: 127. [::1] 10.100.0.254
+ sshd: 10.100.0.Y
+ vsftpd: 10.100.0.0/255.255.255.0 EXCEPT 10.100.0.Y

di

Configure TCP wrappers to deny all connections not matching a rule in the
hosts.allow file (any existing comments can be left in place):

3)

tio
bu

ri
st

Normally you would permit the local IP address of the system to all services as
well (adding it to the first line). It is left off only to facilitate testing within the lab.

O
PY

ite

d.

1-32

ib

# service vsftpd start

oh

Since vsftpd is not started by default, start it now:

pr

4)

is

File: /etc/hosts.deny
+ ALL: ALL

5)

Enable telnet, which is wrapped via Xinetd:

6)

EV

# chkconfig telnet on

riz
ho
ut
na

Verify you can connect to the SSH and telnet services via loopback, but not your
assigned IP:

Connection is established.

t
uc

od

AT

pr
re

ed

AL

# ssh guru@localhost
The authenticity of host localhost (127.0.0.1) cant be established.
RSA key fingerprint is 36:fe:89:5a:d4:57:da:3d:29:9d:6b:d4:27:65:fd:3e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added localhost (RSA) to the list of known hosts.
guru@localhosts password: work
. . . snip . . .
# exit
logout
Connection to localhost closed.
# telnet localhost
Trying 127.0.0.1...
Connected to localhost.
Escape character is ^].
This is a secured system, unauthorized access is prohibited.
All access is logged.
login: ]
telnet> close
Connection closed.

or

IO

n
io

Connection is denied

# ssh guru@10.100.0.X
ssh_exchange_identification: Connection closed by remote host
# telnet 10.100.0.X
Trying 10.100.0.X...
Connected to 10.100.0.X.
Escape character is ^].
This is a secured system, unauthorized access is prohibited.
All access is logged.
Connection closed by foreign host.

tio
bu

ri
st

di

Connection is established

is

O
ite

d.

Verify you can connect to the FTP service via both loopback and your assigned IP:

# ftp localhost

PY

ib

oh

pr

7)

Connection is denied

1-33

Connected to localhost (127.0.0.1).


220 (vsFTPd 2.2.2)
Name (localhost:guru): c

Connection is established

EV
U

# ftp 10.100.0.X
Connected to 10.100.0.1 (10.100.0.1).
220 (vsFTPd 2.2.2)
Name (10.100.0.X:guru): c

Connection is established

AL

riz
ho
ut
na

If you are working with a lab partner, wait for them to reach this point before
continuing.

9)

Examine the log files for evidence of connection attempts:

ed

8)

t
uc

od

AT

pr
re

# tail -n 20 /var/log/messages
. . . snip . . .
xinetd[25390]: libwrap refused connection to telnet (libwrap=in.telnetd) from ::ffff:9.100.0.X
xinetd[25390]: FAIL: telnet libwrap from=10.100.0.X
xinetd[25311]: START: telnet pid=25390 from=10.100.0.X
xinetd[25311]: EXIT: telnet status=0 pid=25390 duration=0(sec)

IO

n
io

If you are working with a lab partner, wait for them to reach this point before
continuing.

11)

Verify that you can connect to the SSH service of your designated lab partner's
system:

or

10)

tio
bu

ri
st

di

# ssh guru@10.100.0.Y
The authenticity of host stationY (10.100.0.Y) cant be established.
RSA key fingerprint is 1f:63:ea:ed:07:bf:82:09:79:99:08:57:e9:79:d0:28.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added stationY,10.100.0.Y (RSA) to the list of known hosts.
guru@stationYs password: work
$ exit
Connection is established
logout
Connection to 10.100.0.Y closed.

is

O
ite

PY

ib

oh

pr

d.

1-34

12)

Attempt to connect to your lab partner's FTP and telnet service (expecting to be
denied):

EV

# ftp 10.100.0.Y
Connected to 10.100.0.Y (10.100.0.Y).
421 Service not available.
ftp> quit
# telnet 10.100.0.Y
Trying 10.100.0.Y...

Connection is denied

AL

riz
ho
ut
na

Connected to stationY.
Escape character is ^].
This is a secured system, unauthorized access is prohibited.
All access is logged.
Connection closed by foreign host.

ed

The Xinetd banner is also printed.

IO

n
io

or

Clean up the TCP Wrappers rules to prevent conflicts with future lab exercises:

tio
bu

ri
st

di

# >/etc/hosts.deny
# >/etc/hosts.allow

15)

t
uc

od

Optional: Examine log files again looking for evidence of the denial messages
associated with your lab partner's attempts to connect to your services.

Cleanup

14)

AT

pr
re

13)

Denied for the stationX IP address and permitted for


others on the subnet.

Clean up telnet and ftp services so that future lab exercises will operate
correctly:

is

O
ite

PY

ib

oh

pr

# chkconfig telnet off


# chkconfig vsftpd off
# service vsftpd stop

d.

1-35

Lab 1

Objectives
y Use Netfilter stateful packet filtering to protect the system.

EV

Task
4
Securing Services with

Requirements
bb (2 stations) c (classroom server)

Netfilter
Estimated Time: 15 minutes

AL

Remove any pre-configured firewall:

or

IO

n
io

N
C

is

Hangs because the outbound packet is discarded due to


the OUTPUT chain's DROP policy.

ib

# ping -c3 localhost


1-36

d.

Try pinging the loopback address in an attempt to identify the networking


problem:

ite

5)

PY

oh

pr

# telnet 10.100.0.254
Trying 10.100.0.254

tio
bu

Try connecting to server1 via telnet:

ri
st

di

Clear out any rules that may already be present in Netfilter:

# iptables -F
# iptables -t nat -F
# iptables -t mangle -F

4)

t
uc

# iptables -P INPUT DROP


# iptables -P FORWARD DROP
# iptables -P OUTPUT DROP

3)

AT

Change the chain policies for all chains in the filter table to DROP:

od

2)

pr
re

# service iptables stop

ed

1)

riz
ho
ut
na

Relevance
Netfilter provides a powerful packet manipulation framework that can be
used to protect networked services. Today's hostile network environments
basically necessitate packet filtering, and Netfilter's stateful rules allow
even simple configurations to provide impressive security.

EV

PING localhost.localdomain (127.0.0.1) from 10.100.0.X : 56(84) bytes of data.


ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
--- localhost.localdomain ping statistics --3 packets transmitted, 0 received, 100% loss, time 11999ms

AL

riz
ho
ut
na

6)

Always allow all traffic on the loopback interface:


Many local services use loopback to communicate and
break without these rules.

# iptables -A INPUT -i lo -j ACCEPT


# iptables -A OUTPUT -o lo -j ACCEPT

ed

7)

Add rules to allow connection tracked traffic (i.e. stateful rules) to be accepted:

pr
re

8)

t
uc

od

AT

# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT


# iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

IO

n
io

Add a rule to allow this host to send ICMP echo-request messages (so that the
ping command will work):

or

# iptables -A OUTPUT -p icmp --icmp-type echo-request -m state --state NEW -j ACCEPT

ri
st

Ping server1, to test the new rules:

di

9)

tio
bu

# ping -c1 10.100.0.254


PING 10.100.0.254 (10.100.0.254) from 10.100.0.X : 56(84) bytes of data.
64 bytes from 10.100.0.254: icmp_seq=1 ttl=64 time=0.211 ms
--- 10.100.0.254 ping statistics --1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.179/0.179/0.179/0.000 ms

is

Add a rule to allow this system to initiate telnet sessions:

PY

ib

oh

pr

10)

ite

# iptables -A OUTPUT -p tcp --sport 1024:65535 --dport telnet -m state --state NEW -j ACCEPT
Try to use telnet to connect to server1 by IP address:

# telnet 10.100.0.254

d.

11)

1-37

AL

12)

riz
ho
ut
na

EV

Trying 10.100.0.254...
Connected to 10.100.0.254.
Escape character is ^].
Red Hat Enterprise Linux Server release 6.0 (Santiago)
Kernel 2.6.32-71.el6.i686 on an i686
login: ]
telnet> close
Connection closed.
Try to use telnet to connect to server1 by hostname:

AT

pr
re

13)

ed

# telnet server1
telnet: server1: Name or service not known
server1: Host name lookup failure

Insert rules to allow this system to perform DNS lookups:

od

t
uc

# iptables -I OUTPUT 4 -p udp --sport 1024:65535 --dport 53 -m state --state NEW -j ACCEPT
# iptables -I OUTPUT 5 -p tcp --sport 1024:65535 --dport 53 -m state --state NEW -j ACCEPT

IO

n
io

14)

Try to use telnet to connect to server1 by hostname:

or

tio
bu

ri
st

di

# telnet server1
Trying 10.100.0.254...
Connected to 10.100.0.254.
Escape character is ^].
Red Hat Enterprise Linux Server release 6.0 (Santiago)
Kernel 2.6.32-71.el6.i686 on an i686
login: ]
telnet> close
Connection closed.

is

Wait for your lab partner to reach this point before continuing with this step.

PY

ite

Try to ping your lab partner's system:

ib

oh

pr

15)

d.

# ping stationY
PING stationY.example.com (10.100.0.Y) from 10.100.0.X : 56(84) bytes of data.

1-38

This fails because there is no rule in the target's


Netfilter configuration to allow incoming echo request
packets

. . . snip . . .
c

EV

16)

Allow echo requests of a reasonable size (the default is 56 bytes), but don't allow
large flood pings:

AL

17)

riz
ho
ut
na

# iptables -A INPUT -p icmp --icmp-type echo-request -m length --length :128 -j ACCEPT


Wait for your lab partner to reach this point before continuing with this step.
Ping your lab partner's system, then again with a large packet size:

t
uc

od

AT

pr
re

ed

# ping -c1 stationY


PING stationY.example.com (10.100.0.Y) 56(84) bytes of data.
64 bytes from stationY.example.com (10.100.0.Y): icmp_seq=1 ttl=64 time=0.444 ms
--- stationY.example.com ping statistics --1 packets transmitted, 1 received, 0% packet loss, time 2038ms
t min/avg/max/mdev = 0.085/0.212/0.224/0.045 ms
This fails because the ping packet is greater than the
# ping -s 500 -c1 stationY
allowed incoming echo packet size
PING stationY.example.com (10.100.0.Y 508(528) bytes of data.

IO

n
io

or

--- stationY.example.com ping statistics -1 packets transmitted, 0 received, 100% packet loss, time 10000ms

ri
st

Add a rule to allow incoming SSH connections:

di

18)

Find the rule which allows this system to initiate telnet connections:

19)

tio
bu

# iptables -A INPUT -s 10.100.0.0/24 -p tcp --dport 22 -m state --state NEW -j ACCEPT

is

PY

ite

Replace the rule that allows this system to connect using telnet, with one that
permits SSH:

ib

20)

oh

pr

# iptables -nv -L OUTPUT --line-numbers | tail -n1


6 18 5728 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp spt:1024:65535 dpt:23

d.

# iptables -D OUTPUT 6
Rule number must match the one found in Step 19.
# iptables -I OUTPUT 6 -p tcp --sport 1024: --dport 22 -m state --state NEW -j ACCEPT

1-39

21)

Make these firewalling rules persistent across reboots:

Drop down to single-user mode and then back to run-level 5 to demonstrate that
the rules are restored:

init 1
. . snip . . .
init 5
. . snip . . .

Login as root and check the Netfilter rules:

IO

n
io

24)

t
uc

Cleanup

od

# iptables -nvL
. . . output omitted . . .

AT

pr
re

23)

ed

AL

#
.
#
.

riz
ho
ut
na

22)

EV

# service iptables save


iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ]

Clean up to prevent Netfilter from interfering with future labs:

or

tio
bu

ri
st

di

# for i in INPUT OUTPUT FORWARD; do iptables -P $i ACCEPT; done


# iptables -F
# service iptables save

is

O
ite

PY

ib

oh

pr

d.

1-40

Lab 1

Objectives
y Practice troubleshooting common system errors.

EV

Task
5
Troubleshooting Practice

Requirements
b (1 station)

Estimated Time: 20 minutes

AL

As the root user, invoke the tsmenu program:

AT

The first time the troubleshooting framework is started, you are required to
confirm some information about your system:

t
uc

od

2)

pr
re

# tsmenu

ed

1)

riz
ho
ut
na

Relevance
Troubleshooting scenario scripts were installed on your system as part of
the classroom setup process. You use these scripts to break your system
in controlled ways, and then you troubleshoot the problem and fix the
system.

IO

n
io

Confirm the distribution of Linux is correct by selecting Yes and then press .

or

select OK and then press .


You are presented with the 'Select Troubleshooting Group' screen.

ri
st

di

This first break system scenario is a simple HOW-TO for the tsmenu program
itself. Its function is to familiarize you with the usage of the program:

tio
bu

3)

Use the UP and DOWN arrow keys to select 'Troubleshooting Group #0'.

Use the LEFT and RIGHT arrow keys to select OK and press to continue.
You are taken to the 'Select Scenario Category' screen.

is

O
PY

ite

d.

Select OK and press to continue.


You are taken to the 'Select Scenario Script' screen.

ib

Select the 'Learn: Example learning scenarios' category.

oh

Pick the category of problem that you want:

pr

4)

1-41

5)

Pick the specific troubleshooting script that you want to run:

EV

Select the 'learn-01.sh' script

select OK and press .


You are taken to the 'Break system?' screen.

riz
ho
ut
na

The 'Break system?' screen provides you with a more detailed description of the
scenario and asks whether you want to proceed and "break the system now?".
Read the description of the problem and then Select Yes and press .

AL

6)

pr
re

ed

You are taken to the 'SYSTEM IS BROKEN!' screen. Select OK and press . The
system is now locked on the selected scenario and will not permit you to run
another scenario until the current scenario is solved.

t
uc

od

7)

AT

Depending on the scenario, a reboot may be required before the problem is


noticed. In these cases, the system will reboot automatically when you select OK.

IO
ri
st

di

You can also get information about the currently locked problem by re-running the
tsmenu program. As the root user, launch the tsmenu program:

tio
bu

# tsmenu

8)

or

# cat /problem.txt
. . . output omitted . . .

n
io

You can re-read the description of the scenario two different ways. First, the
description is written into a text file. Display the contents of this file:

You are taken to the 'Youre in learn-01.sh (Example scenario)' screen.

is

ite

d.

Select the 'Hints' menu item, then select OK and press .


The 'Hints' screen is displayed. Notice that the total number of hints available is
indicated, and that past hints (if already displayed) are also shown in the list.

1-42

PY

ib

oh

The scenario description text is displayed.

10)

Use the UP and DOWN arrow keys to select the 'Description' menu item, then
select OK and press to continue.

pr

9)

Select the 'Hints' menu item several times until you have seen all of the available
hints for the learn-01.sh scenario.

12)

The 'Check' menu item is used to check if the currently locked troubleshooting
scenario has been correctly solved. Select 'Check', then select OK and press .

EV

11)

AL

riz
ho
ut
na

You are presented with the message 'ERROR: Scenario not completed'. This
indicates that the conditions required by the script have not yet been met. If you
feel that you have solved the problem, then you may need to carefully review the
requirements as listed in the 'Description'. If you are still unsure about how to
proceed then you should consult with the instructor.

t
uc

od

or

IO

n
io

Launch the tsmenu program again.

# tsmenu

AT

Solve this problem by creating the required file:

# touch /root/solved

14)

pr
re

13)

ed

Select Cancel and press to exit the tsmenu program.

di

15)

select the 'Check' menu item

tio
bu

ri
st

Each time the tsmenu program launches, it checks to see if you have solved the
current problem. If you leave the tsmenu program open, then you can check a
problem at any time by following these steps:

select OK and press


you are presented with a 'SUCCESS: Scenario completed' message
Select OK and press
You are taken back to the main 'Select troubleshooting group' screen

is

O
ite

d.

You should now proceed to complete the troubleshooting scenarios shown in the
following table using the same basic procedure as shown in the previous steps.

PY

ib

16)

oh

pr

Select Cancel and press to exit the tsmenu program

1-43

Troubleshooting Group Scenario Category Scenario Name


Group 2

TCP Wrappers

tcpwrappers-01.sh

EV

Group 2

IP Tables

iptables-01.sh

Group 2

Xinetd

xinetd-01.sh

t
uc

od

AT

pr
re

ed

AL

riz
ho
ut
na

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

1-44

Lab 1

Objectives
y Examine the effect of the cp and mv commands on SELinux file contexts

EV

Task
6
SELinux File Contexts

Requirements
b (1 station)

Estimated Time: 5 minutes

AL

Create a new file and view the default SELinux file context assigned:

ed

1)

riz
ho
ut
na

Relevance
When copying and moving files, the SELinux security label (file context)
attached to a file can be modified. Understanding the effect of commands
on these file context labels will allow you to fix and avoid file context
problems.

2)

/etc/testfile

t
uc

od

AT

pr
re

# echo "data" > /etc/testfile


# ls -Z /etc/testfile
-rw-r--r--. root root unconfined_u:object_r:etc_t:s0

IO

n
io

Copy and move the file into the /tmp directory and view the file contexts assigned
to the new files:

or

# cp /etc/testfile /tmp/testfile-cp
# mv /etc/testfile /tmp/testfile-mv
# ls -Z /tmp/testfile-*
-rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/testfile-cp
-rw-r--r--. root root unconfined_u:object_r:etc_t:s0 /tmp/testfile-mv

tio
bu

ri
st

di

Set the file context on the moved file to the correct value for the new location:

3)

is

# chcon -t user_tmp_t /tmp/testfile-mv


# ls -Z /tmp/testfile-mv
-rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/testfile-mv

O
ite

PY

ib

oh

pr

d.

1-45

or

N
is

ite

d.

PY

ib

oh

pr

C
n

tio
bu

ri
st

di

IO

n
io

AT
t
uc

od

pr
re

ed

AL

riz
ho
ut
na

EV

AL

riz
ho
ut
na

EV

Content
Naming Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
DNS A Better Way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
The Domain Name Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Delegation and Zones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Server Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Resolving Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Resolving IP Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Basic BIND Administration . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Configuring the Resolver . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Testing Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Lab Tasks
16
1. Configuring a Slave Name Server . . . . . . . . . . . . . . . . . . 17

ed

Chapter

t
uc

od

AT

pr
re

or

IO

n
io

di

tio
bu

ri
st

DNS CONCEPTS

is

O
ite

PY

ib

oh

pr

d.

Naming Services

pr
re

Before DNS

ed

AL

riz
ho
ut
na

EV

Computers and Humans


Computers fundamentally work at a binary level
Objects have numerical labels
Humans work best with names rather than numbers
Naming Services map names to native numerical labels
The original Internet Naming Service HOSTS.TXT and SRI-NIC
Scalability problems as ARPAnet grew
Excessive traffic/load on SRI-NIC
Name collisions with flat name-space
Consistency problems
High administrative burden

t
uc

od

AT

In the 1970s, all name-to-address mappings for hosts on ARPAnet,


the precursor to today's Internet, were maintained in a single master
file, HOSTS.TXT. Starting in March of 1973, this file was updated by
submitting changes via email to a central repositoryat Stanford
Research Institute's Network Information Center (SRI-NIC). New
releases were posted a couple of times a week for retrieval via
anonymous FTP.

Connected to sri-nic
220 SRI-NIC.ARPA FTP Server Process 5Z(47)-6
at Fri 25-Dec-87 20:28-PST
Name (sri-nic.arpa:dkelson): anonymous
331 ANONYMOUS user ok, send real ident as password.
Password:
230 User ANONYMOUS logged in at Fri 25-Dec-87 20:28-PST.
ftp> get NETINFO:HOSTS.TXT
200 Port 4.158 at host 128.114.130.3 accepted.
150 ASCII retrieve of <NETINFO>HOSTS.TXT.5 started.
226 Transfer completed. 652121 bytes transferred.
local: NETINFO:HOSTS.TXT remote: NETINFO:HOSTS.TXT
652121 bytes received in 22.74 seconds (28 Kbytes/s)
ftp> quit
221 QUIT command received. Goodbye.

or

IO

n
io

O
ite

PY

ib

oh

pr

d.

2-2

is

% ftp sri-nic

After obtaining the HOSTS.TXT file, a script was run to convert it to


the /etc/hosts format.

The SRI-NIC server was a DEC-2065, running the TOPS20 operating


system. It was located in Menlo Park, California. It contained over 90
network related documents available via FTP. An example of
downloading the HOSTS.TXT file:

tio
bu

Obtaining a copy of the HOSTS.TXT file

ri
st

di

This system worked well when ARPAnet was small, but as ARPAnet
grew, researchers quickly realized that this HOSTS.TXT system was
not going to scale. Among other problems, SRI was being
overwhelmed trying to maintain and distribute the file, people were
often requesting the same host name for different sites (a conflict SRI
did not even have the authority to resolve, other than by informally
adopting a first-come, first-serve policy), and system administrators
often found that their systems' copies of the file were inconsistent
with other systems' copies. By the time updated copies made their
way across ARPAnet, they were already out-of-date.

DNS A Better Way

pr
re

Replacing HOSTS.TXT

ed

AL

riz
ho
ut
na

EV

The Domain Name System (DNS)


Distributed Database
Client/Server
Hierarchical Namespace
Distributed Administration
DNS Server Implementations
BIND versions 4, 8, 9
djbdns, MaraDNS, PowerDNS, NSD & Unbound

t
uc

od

AT

ARPAnet's governing bodies set out to design a replacement for the


HOSTS.TXT system, eventually leading to Paul Mockapetris' release of
RFC882 and RFC883 in 1984. These RFCs described the technical
details of a new Domain Name System (DNS), which Mockapetris had
implemented a couple of years earlier in a software package he
called JEEVES. DNS was intended to solve all the problems inherent
to the HOSTS.TXT scheme, and as such it was designed as a
distributed database with a client/server architecture and a
decentralized, hierarchical, distributed administration.

primary goal of the re-write was making version 9 more robust and
secure.
BIND Security Troubles

or

IO

n
io

All versions of BIND have had poor security track records, although
BIND 9 is much better. In light of its track record, it is important that
BIND updates be closely tracked and applied. This is normally done
through the operating system vendor, as BIND is the standard DNS
server shipped with Unix systems.

di

Popular free alternatives to BIND include djbdns, MaraDNS,


PowerDNS and NSD/Unbound. Daniel J. Bernstein's djbdns hasn't
been updated for years but is still very popular because it has a very
good security history. MaraDNS was also created with security as a
primary goal and while its history hasn't been perfect, it has been
good. PowerDNS was designed for performance and flexibility. It can
provide unique responses based on the geographic location of the
client. It also supports multiple backends including RDBMS and
LDAP. NSD was created by NLnet Labs of Amsterdam "with the
purpose of creating more diversity in the DNS landscape." It holds the
distinction of being the only software other than BIND used on root
DNS servers. Because NSD can only be used as an authoritative
name server, Unbound was created as a companion recursive and
caching name server.

O
ite

PY

ib

oh

d.

BIND version 9 is a complete re-write of version 8. The feature set is


nearly the same as version 8, with the addition of IPv6 support. A

pr

BIND version 8 was created by the Internet Software Consortium. It


has many improvements over BIND version 4 including negative
answer caching, incremental zone transfers, and split DNS.

is

The BIND project was started as a graduate student project at the


University of California, Berkeley under a grant from the US Defense
Advanced Research Projects Administration (DARPA). The code
produced at Berkeley is the core of BIND version 4.

tio
bu

BIND, The Berkeley Internet Name Domain

ri
st

After the release of JEEVES, a team of graduate students at UC


Berkeley wrote a suite of DNS software for the upcoming 4.3 BSD.
Their package, BIND, is still by far the most popular DNS software in
use today.

Alternative DNS Server Implementations

2-3

The Domain Name Space

DNS Structure

ed

AL

riz
ho
ut
na

EV

The nameless root "."


Top Level Domains (TLDs)
Second Level Domains (SLDs)
Hosts are organized into domains
Logical relationship independent of physical location or network
address
Host name/domain name/FQDN
Stores more than just host names to IP mappings

TLD Country

pr
re

As a hierarchical database, DNS is structured as a large inverted tree.


At the top of the tree is the nameless root node, Under that node are
the Top-Level Domains (TLDs). The original list of TLDs included:

AT

.de Germany

od

.it Italy

Description

.jp Japan

t
uc

TLD

.ru Russia, originally including all of the U.S.S.R.

IO

n
io

.arpa DNS structure (like reverse lookups) and other meta info

.uk the United Kingdom

commercial

.edu

educational institutions

.gov

the U.S. government

.int

international organizations, like NATO, WHO, the World Bank,


etc.

or

.com

.us United States

This inverted database offers several advantages over the flat map
provided by the earlier HOSTS.TXT scheme. Individual hosts are
grouped into logical subdomains, which are further organized into
logical domains, allowing management responsibilities for each
domain and subdomain to be delegated, removing the necessity for a
single administrator like SRI-NIC.

ite

PY

ib

oh

organization, meant for non-profits that don't fit in one of the


other TLDs

pr

.org

is

networks, meant for internetworking providers

Under each TLD are Secondary-Level Domains (SLDs); these include


entries such as .google.com, .whitehouse.gov, and .utah.edu.
Below each SLD there can be additional subdomains, until eventually
the level of the individual host is reached, such as
sloane.section31.example.com.

.net

tio
bu

U.S. military

ri
st

di

.mil

The original list also included all of the 2-letter ISO country codes.
This table shows a few examples:

All of these TLDs are still in use today, along with several newer
TLDs which have been officially adopted over the years.

d.

Consider the .gurulabs.com subdomain. ICANN administers the .com


2-4

EV

domain, so it has delegated authority to Guru Labs for the


gurulabs.com. zone, which contains the .gurulabs.com domain.
Guru Labs then administers the gurulabs.com. zone independently of
ICANN.

AL

riz
ho
ut
na

Logical relationships between hosts are easily identified by their fully


qualified domain name (FQDN). All machines at the University of
California, Berkeley will have a domain name of .berkeley.edu, just
as all hosts at Fuzzy Wuzzy will have a domain name of

.fuzzywuzzy.com.
The inverted tree structure of DNS also makes possible a logical,
tree-walking approach to determine IPs from FQDNs. For example, to
resolve www.fuzzywuzzy.com, a resolver will first ask a root name
server for the answer. That server will tell the resolver where to find
the name server for the com. zone, which will tell the resolver where
to find the name server for the fuzzywuzzy.com. zone, which will
return the IP address for www.fuzzywuzzy.com.

" "

AT

pr
re

ed

.gov

.edu

.info

t
uc

od

.com

n
io

whitehouse

usps

IO

GuruLabs utah stanford


or

cnn

linuxtraining

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

2-5

Delegation and Zones

pr
re

Delegation

ed

AL

riz
ho
ut
na

EV

Decentralized administration through delegation


Domains vs. zones
Domains define logical groupings of hosts
Zones contain the same information as the corresponding
domain name except for delegated subdomains
A DNS server is authoritative for domains delegated to it
Delegations are defined via the DNS Tree.

t
uc

od

AT

Delegation of administrative duties is one of the key advantages of


DNS over its predecessor, HOSTS.TXT. This is done by assigning
responsibilities for subdomains to other organizations; for example,
ICANN assigned responsibility for the .gurulabs.com subdomain to
Guru Labs, LC.

n
io

or

IO

One subtle distinction to keep in mind is the difference between


"zones" and "domains." Domains represent logical groupings of hosts;
all commercial hosts could belong to the .com domain, all educational
organizations could belong to the .edu domain, etc. Zones, however,
represent the administrative duties associated with their
corresponding domain or subdomain. For example, in the United
States, NeuStar administers the .us domain and the corresponding
us. zone. Under the .us domain exist subdomains for all 50 states,
such as .ca.us (California) and .ut.us (Utah).

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

The concept of delegation holds true throughout the Internet, starting


from the root (".") server. Zone delegation can be managed separately
from their parent zones. A couple of good examples are
www.l.google.com and mail.yahoo.com.

d.

2-6

Server Roles

pr
re

BIND DNS Server Types

ed

AL

riz
ho
ut
na

EV

Types of name servers


Authoritative servers
Primary masters (masters)
Secondary masters (slaves)
Caching only
Zone transfers keep slaves in sync with masters
A DNS server can be authoritative for many different domains
Limited only by resources (CPU, Memory, Bandwidth, etc.)
A single name server can serve different roles

t
uc

od

AT

It is important to understand that from the DNS namespace


perspective all servers that are authoritative for a domain are treated
equally. To help manage, and keep all the servers synchronized, the
BIND name server uses the concept of primary master, and
secondary master, (sometimes called slave servers). Primary master
servers are those which read the data for a zone from a local file. All
edits and administration takes place on the primary master.
Secondary master servers, while still being authoritative, obtain the
zone data from another authoritative server for the zone. The other
server may either be the primary master server or another secondary
master server. The transfer of zone data from the master server to a
secondary master server is known as a zone transfer.

wants to go to Yahoo!, servers typically cache the results of DNS


lookups. The second time a user goes to http://www.yahoo.com/,
the DNS information for www.yahoo.com will be retrieved from the
cache. If the user then wants to go to http://mail.yahoo.com/, the
cache will already know where to find the name server responsible
for the .yahoo.com domain, so the root and .com name servers will
not have to be queried. Because of the speed benefits, even sites
which have no other need for a name server will commonly set up
caching-only name servers.

or

IO

n
io

NS

oh

Zone Transfer

NS

ite

PY

ib

d.

In addition to being authoritative for domains, name servers also


cache DNS queries. Resolving host names is a lengthy iterative
process; the first time a user tries to load http://www.yahoo.com/ at
least three name servers will be queried (root, .com, and .yahoo.com).
To avoid having to repeat all those queries every single time a user

Secondary Masters
(Slaves)

NS

pr

DNS Record Caching

Primary Master

is

It's important to keep in mind that most name servers fill a variety of
roles. They may be primary master servers for some zones, while
simultaneously being secondary master servers for other zones and
caching servers for all other zones.

tio
bu

ri
st

di

Roles are Defined at the Zone Level

Authorative nameservers
for example.com

2-7

Resolving Names

Types of DNS Queries

ed

AL

riz
ho
ut
na

EV

Mapping Name to IP address


Recursion (recursive resolution)
Iteration (iterative resolution)
Mapping IP address to Name
Caching
DNS record TTL trade-off

pr
re

zone. The TTL for positive caching is adjustable in the zone file using
the $TTL variable and can be set on individual records. The TTL for
each record is one of the parameters returned in answer to every
DNS query.

od

AT

Resolution of a FQDN to an IP address can either be of a type


recursive or iterative. Normally, queries that a host makes to a DNS
server are recursive, and queries between DNS servers are iterative.
In recursive resolution, a client queries a name server for the IP of a
FQDN, and the name server can respond in two ways: it can either
send the IP address, which it will have to determine itself, or it can
send an error saying that it can't resolve that FQDN. With an iterative
query, the name server can respond in one of three ways: it can send
the IP if it is known; it can send an error saying that the FQDN can
not be resolved; or it can refer the client to a different name server
(at which point the process starts over).

t
uc

When setting the TTL, keep in mind that doing so is always making a
trade-off between accuracy and performance. Long TTLs improve
network performance, but mean out-of-date DNS records will be
cached for a long time, while short TTLs mean that cached DNS
records are always likely to be accurate, but that DNS queries will
have to be made more frequently.

or

IO

n
io

O
ite

PY

ib

oh

d.

2-8

pr

For negative results, the TTL is configured in the SOA record for the

is

Resolution of names relies heavily on caching of previous results.


One important detail to keep in mind when managing DNS records is
that data is cached based on its Time To Live, or TTL. The TTL
determines how long the data can be cached before the caching
name server must discard it. The TTLs for both positive and negative
caching are adjustable by the zone administrator.

Caching Records and TTL Values

In addition, newer name servers can also do negative caching,


meaning that they cache not only successful DNS queries (such as
that www.yahoo.com has, amongst other addresses, an IP of
66.94.230.50), but also unsuccessful DNS queries (such as that
fake.example.com does not exist, at least at the time this book was
written). The benefits in terms of increased speed and reduced
network traffic on the whole Internet from caching negative DNS
queries are enormous.

tio
bu

The reverse process, that of resolving IP addresses to a FQDN, is not


as straight-forward, but is resolved by a rather clever method. Every
IP address is also part of another domain, the .in-addr.arpa
domain, which can be queried just like any other domain.

ri
st

di

Negative Record Caching RFC2308

DNS Resolution for www.GuruLabs.com

1. What's the IP for www.GuruLabs.com?


2. What's the IP for www.GuruLabs.com?
3. We don't know. Go talk to the com. name servers. Here is a list
of them. (Server A caches this information.)
4. What's the IP for www.GuruLabs.com?
5. We don't know. Go talk to the gurulabs.com. name servers.
Here is a list of them. (Server A caches this information.)
6. What's the IP for www.GuruLabs.com?
7. The IP address for www.GuruLabs.com is 67.137.148.8. (Server
A caches the answer.)
8. Server A returns the answer back to the requesting client.

EV

NS
NS NS
NS

NS
NS NS
NS

riz
ho
ut
na

AL

D
4

NS
NS NS
NS

pr
re

ed

AT

NS

t
uc

od

IO

n
io

or

PC

A:
B:
C:
D:

Client configured DNS server


Root name servers
.com name servers
GuruLabs.com name servers

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

2-9

Resolving IP Addresses

pr
re

The .in-addr.arpa Domain

ed

AL

riz
ho
ut
na

EV

Why resolve IP address?


Authorization based on hostname or domainname
Analyzing log files
Sorting nodes by their IP address
in-addr.arpa. subdomain
Provides for logical delegation on class boundaries

t
uc

od

AT

In addition to mapping names to addresses, it is often desirable to


map addresses to names. Perhaps you're an administrator looking
through server logs, and you want to know that the cracker
attempting to break into your system from 192.168.0.254 was
coming from server1.example.com, or perhaps you're running TCP
Wrappers or other software which does an IP address to hostname
resolution before permitting authentication.

server for the address of the .in-addr.arpa nameserver. It will then


ask the .in-addr.arpa server for the address of the nameserver
which is authoritative for the 192.in-addr.arpa. zone (in other
words, the nameserver which knows about all hosts in the
192.0.0.0/8 netblock). It will then ask the nameserver for the
.192.in-addr.arpa domain for the address of the authoritative server
for the 168.192.in-addr.arpa. zone. .168.192.in-addr.arpa is the
domain for all addresses in the 192.168.0.0/16 netblock; that
particular netblock has been allocated to example.com in the
classroom, so the authoritative nameserver for the
168.192.in-addr.arpa. zone will be the classroom nameserver. The
resolver will connect to that nameserver and query it for
254.0.168.192.in-addr.arpa, and the nameserver will respond that
254.0.168.192.in-addr.arpa has the hostname
server1.example.com.

or

IO

n
io

IPv6 DNS Namespace

While IPv4 uses the .in-addr.arpa domain, IPv6 uses the ip6.arpa
domain. For example:

is

oh

pr

ite

PY

6.6.6.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.0.8.1.c.0.0.0.b.0.a
e.f.f.3.ip6.arpa

ib

Addresses in the .in-addr.arpa domain are resolved in the standard


fashion. When querying DNS for the address
254.0.168.192.in-addr.arpa, the resolver will first ask the root

tio
bu

Resolution is Performed in the Normal Fashion

ri
st

di

Resolution of IP addresses into names is typically referred to as


reverse lookup or reverse resolution. It also uses DNS, by querying
the special .in-addr.arpa domain. All IPv4 addresses on the Internet
have a corresponding node in the .in-addr.arpa domain. The
corresponding node of a given address is obtained by reversing the
order of the blocks in their IP address and using this reverse IP
address as their hostname within the .in-addr.arpa domain. For the
previous example of 192.168.0.254, the corresponding node in the
.in-addr.arpa domain is 254.0.168.192.in-addr.arpa.

d.

2-10

""

The in-addr.arpa node for


the 192.0.2.53 IP address

.com

EV

arpa
in-addr

AL

riz
ho
ut
na

192

ed

255

255

od

AT

pr
re

or

IO

n
io

tio
bu

ri
st

hostname station53.example.com

255

di

53

255

t
uc

0
2

is

O
ite

PY

ib

oh

pr

d.

2-11

Basic BIND Administration

Managing the named Process

ed

AL

riz
ho
ut
na

EV

Primary daemon: named


start/stop/restart/reload/status via Sys V init script
Fine grained control of running daemon via rndc
Logs to /var/log/messages
debug level set with named -d level
debug level changed with rndc trace [level]
toggle logging of queries with rndc querylog
SELinux named_selinux(8)
named_{conf,zone,cache,var_run}_t

pr
re

The rndc command can be used for more fine grained control of the
running named process. For example, service named reload will
reload all zones, but rndc reload zone_name will reload just the
specified zone. The following table shows examples of other
commands (a complete list is produced by running rndc without and
arguments):

or

Description

reload zone

reload the specified zone

freeze|thaw zone suspend or enable updates for a dynamic zone


reconfig

reload configuration file and any new zones

stats

write server statistics to the log file

querylog

toggle query logging on or off


dump the cache to a file

dumpdb

tio
bu

ri
st

di

stop

is

PY

turn off debugging

ite

notrace

increase debugging by the specified level

ib

trace level

stop the server immediately

oh

halt

save any pending updates and stop the server

pr

flush

flush the server's caches

status

display the server status

d.

In addition, named can be managed while running by using one of the


name daemon controller utilities. For BIND 8, this utility is called ndc,
while on BIND 9 this utility is called rndc. One advantage of rndc is
the use of keys for authentication. The rndc utility uses this feature to
allow secure remote administration of a BIND 9 server, It connects to
a running named process, using either a Unix domain socket to control
named running on the local machine, or using a TCP socket to control
named running on remote systems. In BIND 9, this control channel is
authenticated, greatly decreasing the security risks posed by it.
2-12

Option

IO

n
io

# service named start


. . . output omitted . . .
# service named status
version: 9.7.0-P2-RedHat-9.7.0-5.P2.el6
CPUs found: 2
worker threads: 2
number of zones: 18
debug level: 0
xfers running: 0
xfers deferred: 0
. . . snip . . .

t
uc

od

AT

The daemon which implements BIND is called named. Basic


administration of named is managed by its SysV Init script, which
supports the standard commands to start and stop the daemon as
well as a few other management commands:

Configuring the Resolver

EV

Client needs the IP address of at least one name server, and


optionally one or more search suffixes

/etc/resolv.conf
search domain.tld
nameserver w.x.y.z

Client Configuration

ed

AL

riz
ho
ut
na

Static vs. DHCP configuration

pr
re

file. Name servers should be selected which are well-connected via


separate networks and which are geographically dispersed. Name
servers are defined with statements like:

t
uc

od

AT

DNS operates via a client-server architecture. The name server


supplies DNS information in response to queries from a client, the
resolver.

or

di

The search Directive

nameserver 10.100.0.254
nameserver 82.165.40.134
nameserver 192.128.167.77

IO

n
io

On Unix machines, the resolver is configured in the file


/etc/resolv.conf, which tells the client which DNS servers to use
and which domains to search when provided with bare host names
rather than with fully qualified domain names.

File: /etc/resolv.conf

tio
bu

ri
st

When given a hostname, the resolver will, by default, append the


localhost's domain name to the hostname and then query the name
servers for that fully qualified domain name. This behavior can be
overridden by specifying a search path, listing domain names which
should be appended to bare host names. This is done with
statements like:

When given a fully qualified domain name, the resolver will connect
to the name servers listed, in the order in which they are listed, and
query them for the IP address of that fully qualified domain name
until it gets a positive response or an authoritative negative response.

O
ite

PY

ib

oh

d.

Up to three name servers can be defined in the /etc/resolv.conf

The nameserver Directive

pr

This tells the resolver to first search for host.domain1.com and then
to search for host.domain2.com if host.domain1.com cannot be
found when asked to search for a bare hostname.

is

search domain1.com domain2.com

Most DHCP clients configure /etc/resolv.conf automatically,


providing both a useful search path and nameserver(s). When using
static IP addresses, the file must be manually configured for the
system resolver to be able to find any nameservers.

File: /etc/resolv.conf

Static vs. DHCP Configuration

2-13

Testing Resolution

EV

ping, telnet
host
dig
Querying a specific server

nslookup

Testing Configurations

ed

AL

riz
ho
ut
na

Interactive vs. command line

default.

pr
re

Testing DNS resolution can involve several different tools. Simple


applications like ping or telnet can be used just to see if the system
you're on can resolve anything. They are good to test whether the
system resolver can resolve:

or

IO

n
io

$ ping foo.example.com
$ telnet foo.example.com

t
uc

od

AT

$ dig www.gurulabs.com
; <<>> DiG 9.7.0-P2 <<>> www.gurulabs.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 55825
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 0

host and dig can also be used to query specific servers. If no

IN

;; ANSWER SECTION:
www.gurulabs.com. 3600

IN

64.245.157.8

IN
IN
IN
IN

NS
NS
NS
NS

ns2.p02.dynect.net.
ns3.p02.dynect.net.
ns1.p02.dynect.net.
ns4.p02.dynect.net.

Query time: 640 msec


SERVER: 127.0.0.1#53(127.0.0.1)
WHEN: Thu Mar 24 12:04:58 2011
MSG SIZE rcvd: 136

ite

PY

ib

oh

d.

Notice that the dig command outputs results in "zone file" format by
2-14

;;
;;
;;
;;

pr

$ host www.gurulabs.com
www.gurulabs.com has address 67.137.148.8
$ host gurulabs.com
gurulabs.com has address 67.137.148.8
gurulabs.com mail is handled by 5 mail.gurulabs.com.

is

The following examples show queries with the host and dig
commands:

;; AUTHORITY SECTION:
gurulabs.com.
172800
gurulabs.com.
172800
gurulabs.com.
172800
gurulabs.com.
172800

host www.gurulabs.com ns1.gurulabs.com


. . output omitted . . .
dig @ns1.gurulabs.com www.gurulabs.com
. . output omitted . . .

tio
bu

$
.
$
.

ri
st

di

nameserver is specified on the command line, they both will use the
nameserver lines in /etc/resolv.conf. Both of these forms query
the name server ns1.gurulabs.com about the host
www.gurulabs.com:

;; QUESTION SECTION:
;www.gurulabs.com.

One important difference between dig and host is that host will
automatically use the search list specified in resolv.conf, and dig
will not (although both commands have options to control this
behavior).

BIND 4, BIND 8 and BIND 9 provide the nslookup command which


can be used either non-interactively or interactively, such as:

AL

riz
ho
ut
na

EV

$ nslookup
> www.kersplat.com
Server: server1.example.com
Address: 10.100.0.254#53
Non-authoritative answer:
Name:
www.kersplat.com
Address: 205.178.145.166
> exit

This example shows a non-interactive invocation of nslookup:

t
uc

od

AT

pr
re

ed

$ nslookup www.kersplat.com
Server: server1.example.com
Address: 10.100.0.254#53
Non-authoritative answer:
Name:
www.kersplat.com
Address: 205.178.145.166

or

IO

n
io

This example shows the result of one of the more common errors
seen in BIND DNS zone files. The data portion of the CNAME record
for the zulu host is missing the terminating dot (period) and
subsequently has had the origin string appended causing the domain
portion (example.com) to be repeated:

di

tio
bu

IN

ri
st

# dig zulu.example.com
. . . snip . . .
;; QUESTION SECTION:
;zulu.example.com.
86400

IN

CNAME

station1.example.com.example.com.

;; AUTHORITY SECTION:
example.com.

600

IN

SOA

localhost. root.localhost. 2007050401 28800 14400 3600000 600

is

O
ite

PY

ib

oh

pr

d.

Query time: 1 msec


SERVER: 10.100.0.254#53(10.100.0.254)
WHEN: Tue Apr 20 13:34:05 2010
MSG SIZE rcvd: 119

;;
;;
;;
;;

;; ANSWER SECTION:
zulu.example.com.

2-15

Lab 2

EV

Estimated Time: 30 minutes

Task 1: Configuring a Slave Name Server

t
uc

od

AT

pr
re

ed

AL

riz
ho
ut
na

Page: 2-17
Time: 30 minutes
Requirements: b (1 station) c (classroom server)

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

2-16

Lab 2

Objectives
y Install the BIND name server and configure it to act as a slave for the
example.com and the 0.100.10.in-addr.arpa classroom domains.

EV

Task
1
Configuring a Slave Name

Requirements
b (1 station) c (classroom server)

Server
Estimated Time: 30 minutes

AL

1)

riz
ho
ut
na

Relevance
Slave name servers provide redundancy and load balancing for DNS record
resolution.

t
uc

Install the BIND packages onto your system:

or

IO

n
io

# yum install -y bind bind-chroot


. . . output omitted . . .

3)

AT

od

2)

pr
re

$ su -l
Password: makeitso

ed

The following actions require administrative privileges. Switch to a root login


shell:

Examine what files are included in the bind package:

tio
bu

ri
st

di

# rpm -qil bind | less


. . . output omitted . . .

In addition to the core components, RHEL6 includes many DNSSEC related


binaries, and extensive documentation (ARM, RFC's, sample configs, man pages,
etc.)

is

ib

oh

PY

Basic directory structure provided by package.

ite

d.

# rpm -ql bind-chroot | less


/var/named/chroot
/var/named/chroot/dev
/var/named/chroot/dev/null
. . . snip . . .
# rpm -q --scripts bind-chroot | sed -n /postinstall/,/:;/p
. . . output omitted . . .

Examine the changes made by the bind-chroot package:

pr

4)

/etc/sysconfig/named modified by postinstall script.


2-17

The BIND SysV init script (/etc/init.d/named) sources /etc/sysconfig/named


and reacts to the $ROOTDIR variable.

EV

5)

Configure the system to act as a slave server for the example.com domain by
adding the following to the end of the existing configuration file:

In a dedicated terminal window (designated [X2]) monitor the system log:


BIND is good at reporting configuration and other
problems, and this can help you catch problems quickly.

od

[X2]# tail -f /var/log/messages

AT

pr
re

6)

ed

AL

riz
ho
ut
na

File: /etc/named.conf
+ zone "example.com" {
+
type slave;
+
file "slaves/example.com.zone";
+
masters { 10.100.0.254; };
+ };

t
uc

Leave this terminal window open (and running tail) for the duration of the lab
task.

IO

n
io

7)

or

Validate the basic syntax and structure of your new configuration file using the
supplied BIND program:

tio
bu

ri
st

di

# named-checkconf && echo OK


OK
# chkconfig named on

If errors are reported, re-open the file and repair it as needed. You may get
notified of newly changed defaults, but should not see any error messages. An
example of a notification would be the following: the default for the

is

auth-nxdomain option is now no

oh

pr

8)

In a separate terminal window, start the name server:

ite

[ OK ]

PY

ib

# service named start


Starting named:

d.

2-18

9)

Verify that the needed files and directories are mounted into the chroot:

AL

See what files are visible to the BIND process:

ed

10)

riz
ho
ut
na

EV

# mount | grep named


/etc/named on /var/named/chroot/etc/named type none (rw,bind)
/var/named on /var/named/chroot/var/named type none (rw,bind)
/etc/named.conf on /var/named/chroot/etc/named.conf type none (rw,bind)
/etc/named.rfc1912.zones on /var/named/chroot/etc/named.rfc1912.zones type none (rw,bind)
/etc/rndc.key on /var/named/chroot/etc/rndc.key type none (rw,bind)
/usr/lib/bind on /var/named/chroot/usr/lib/bind type none (rw,bind)
/etc/named.iscdlv.key on /var/named/chroot/etc/named.iscdlv.key type none (rw,bind)

od

Examine the contents of the system log by looking at the running tail command
in terminal [X2]. There should be a line similar to:

t
uc

11)

AT

pr
re

# ls -R /proc/$(pgrep named)/root/
. . . output omitted . . .

n
io

or

IO

named[27114]: transfer of example.com/IN from 10.100.0.254#53: Transfer completed:a


1 messages, 509 records, 11994 bytes, 0.045 secs (266533 bytes/sec)

Examine the contents of the zone database file that was created from the zone
transfer from the master server:

Looking at the contents and syntax of this file is a great


prelude to the upcoming DNS lab.

is

# less /var/named/slaves/example.com.zone
. . . output omitted . . .

Run a simple query to see if name resolution is working:

PY

d.

The lookup returned the correct answer, but which name server is providing
them?

ite

# host station1
station1.example.com. has address 10.100.0.1

ib

oh

pr

13)

tio
bu

12)

ri
st

di

This indicates that the transfer of the zone file from 10.100.0.254 (server1) was
successful.

2-19

14)

Try another lookup using the verbose option to see (among other things) the
server that gave the answer:

EV

The -t A option limits the query to just an address


record (otherwise it attempts several queries by
default).

AL

riz
ho
ut
na

# host -t A -v station1
Trying "station1.example.com."
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 31519
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 1
;; QUESTION SECTION:
;station1.example.com.

IN

;; ANSWER SECTION:
station1.example.com. 86400 IN

10.100.0.1

ed

server1.example.com.

od

;; ADDITIONAL SECTION:
server1.example.com. 86400 IN

NS

AT

pr
re

;; AUTHORITY SECTION:
example.com.
86400 IN

Notice the IP address of the server that returned the


answer.

10.100.0.254

t
uc

or

15)

IO

n
io

Received 92 bytes from 10.100.0.254#53 in 0 ms


. . . output omitted . . .

N
C

is

d.

2-20

ite

File: /etc/resolv.conf
- nameserver 10.100.0.254
+ nameserver 127.0.0.1

PY

Use a text editor to modify the /etc/resolv.conf so that it defaults to using your
own server for name resolution:

ib

16)

oh

pr

station1.example.com has address 10.100.0.1

tio
bu

# host station1 localhost


Using domain server:
Name: localhost
Address: ::1#53
Aliases:

ri
st

di

Run the query again, this time specifying the slave name server running on your
local system for name resolution:

17)

Verify that only the correct entries are present. If not, modify the
/etc/resolv.conf file again.

EV

# tail -n2 /etc/resolv.conf


search example.com
nameserver 127.0.0.1

If your station is currently configured to use DHCP, when the DHCP lease is
renewed, any changes made to /etc/resolv.conf will be lost. To prevent this,
disable DNS configuration updating from DHCP, then restart your network
interface:

ed

Some classrooms may have more than one NIC. If this


is the case on your system and you are uncertain which
interface is being used, ask the Instructor for help with
this step.

echo PEERDNS="no" >> /etc/sysconfig/network-scripts/ifcfg-eth0


echo DNS1="127.0.0.1" >> /etc/sysconfig/network-scripts/ifcfg-eth0
service network restart
. . output omitted . . .

t
uc

od

AT

pr
re

#
#
#
.

19)

AL

riz
ho
ut
na

18)

Notice the IP address of the server that returned the


answer.

or

# host -v station1 | tail -n 1


Received 77 bytes from 127.0.0.1#53 in 3 ms

IO

n
io

Verify that names in the example.com domain are now resolved by this system's
name server by default:

This command fails because the name server is not


currently loading a zone file for this domain.

Configure the name server as a slave server for the appropriate reverse lookup
zone by adding these lines to the end of the named.conf configuration file:

is

21)

tio
bu

# host 10.100.0.1
Host 1.0.100.10.in-addr.arpa not found: 3(NXDOMAIN)

Attempt a reverse lookup for this station's IP address:

ri
st

di

20)

O
ite

PY

ib

oh

pr

d.

2-21

File: /etc/named.conf

ed

AL

riz
ho
ut
na

22)

EV

+
+
+
+
+

zone "example.com" {
type slave;
file "slaves/example.com.zone";
masters { 10.100.0.254; };
};
zone "0.100.10.in-addr.arpa" {
type slave;
file "slaves/0.100.10.in-addr.arpa.zone";
masters { 10.100.0.254; };
};

od

AT

# named-checkconf

pr
re

Verify that the configuration file does not contain typographical errors by running it
through the BIND syntax checker:

t
uc

If errors are reported then double check the configuration file and correct the
errors.
Restart the named daemon so that the new configuration takes effect:

or

[ OK ]
[ OK ]

tio
bu

ri
st

di

# service named restart


Stopping named:
Starting named:

24)

IO

n
io

23)

Try the reverse lookup of this station's IP address again. This time it should
succeed:

is

# host 10.100.0.1
1.0.100.10.in-addr.arpa. domain name pointer station1.example.com.

O
ite

PY

ib

oh

pr

d.

2-22

AL

riz
ho
ut
na

EV

Content
HTTP Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Apache Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Dynamic Shared Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Adding Modules to Apache . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Apache Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . 8
httpd.conf Server Settings . . . . . . . . . . . . . . . . . . . . . . . . . 9
httpd.conf Main Configuration . . . . . . . . . . . . . . . . . . . . . 10
HTTP Virtual Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Virtual Hosting DNS Implications . . . . . . . . . . . . . . . . . . . . 12
httpd.conf VirtualHost Configuration . . . . . . . . . . . . . . . . 13
Port and IP based Virtual Hosts . . . . . . . . . . . . . . . . . . . . . . 14
Name-based Virtual Host . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Apache Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Log Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
The Webalizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Lab Tasks
19
1. Apache Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2. Apache Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3. Configuring Virtual Hosts . . . . . . . . . . . . . . . . . . . . . . . . . 25

ed

Chapter

t
uc

od

AT

pr
re

or

IO

n
io

di

tio
bu

ri
st

USING APACHE

is

O
ite

PY

ib

oh

pr

d.

HTTP Operation

HTTP v1.1

ed

AL

riz
ho
ut
na

EV

HTTP Version 1.1


Stateless
Requires the Host: header be first
Client Request Structure
Request Method (GET, POST, etc.)
Headers
Body (optional)
Server Response Structure
Response code (200,300,400, etc.)
Headers
Body

. . . output omitted . . .

pr
re

You can also use the w3m text-mode web browser which allows you
to do HEAD requests using the -dump_head option:

od

AT

HTTP is the protocol that powers the World Wide Web. It is a simple,
stateless file transfer protocol consisting of a client-side request and
a server-side response. Both the request and the response are
structured in three parts: a request method/response code, a header
section followed by a blank line, and a body section.

t
uc

$ w3m -dump_head http://www.google.com/


. . . output omitted . . .

n
io

Finally, the Lynx text-mode web browser allows for HEAD requests
using the -head option:

or

IO

Use the netstat command to see connections initiated by your web


browser. For example, this command shows an established
connection from a host to http://www.google.com/:

PY

ite

Server Response

ib

oh

HTTP/1.1 200 OK
Date: Fri, 12 Jan 2007 01:24:27 GMT
Server: Apache
Set-Cookie: Apache=66.62.77.11.279431042161867442;

d.

8-2

pr

$ wget --server-response --spider http://www.google.com

is

. . . or using the wget retrieval tool using the --server-response, and


--spider options:

GET / HTTP/1.1
Host: www.linuxtraining.com
User-Agent: Mozilla/5.0 (X11; U; Linux i686)
Accept: text/xml, image/png, image/jpeg, image/gif
Accept-Language: en-us, en;
Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66
Keep-Alive: 300
Connection: keep-alive

$ telnet www.google.com 80
Trying 216.239.53.100...
Connected to www.google.com (216.239.53.100).
Escape character is ^].
GET / HTTP/1.1
. . . snip . . .

Client Request

tio
bu

You can view the server headers using the HTTP HEAD request
method. You can connect to web servers and manually issue GET
requests using telnet . . .

ri
st

di

$ netstat -tp
tcp 0 0 entmoot:32931 www.google.com:80 ESTABLISHED

$ lynx -head http://www.google.com/


. . . output omitted . . .

t
uc

od

AT

pr
re

ed

AL

riz
ho
ut
na

EV

path=/; expires=Sun, 17-Jan-2038 01:24:27 GMT


Last-Modified: Thu, 11 Jan 2007 22:44:48 GMT
ETag: "bea6a-46fd-3e1dfb60"
Accept-Ranges: bytes
Content-Length: 18173
Connection: close
Content-Type: text/html

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

8-3

Apache Architecture

AL

riz
ho
ut
na

EV

Maintained by the Apache Software Foundation


Membership by invitation only, based on skills and contributions
More Apache servers than all other HTTP servers combined
Over 60% Market Share
Apache runs as a stand-alone network service daemon
Multiple process/thread models (MPMs) available
Extending Apache via Modules
Apache Core modules

http://modules.apache.org/

ed

Apache History

http://httpd.apache.org/docs/2.2/mod/
Third-party modules

General Architecture

pr
re

Apache's success is in large part due to its architecture. Two key


concepts went into the development of Apache: modularity and
efficiency.

t
uc

od

AT

In 1995, most people running web servers were using NCSA's httpd
1.3 software which NCSA had stopped actively maintaining. A group
of web server administrators led by Brian Behlendorf began collecting
all the various patches they were individually using to make NCSA's
httpd more usable, and A PAtCHy sErver was born. Shortly thereafter
the Apache Group re-wrote Apache from the ground up. Less than a
year after it was created Apache had become the most commonly
used web server and has continued to pull ahead of other
competitors. Apache owns more than 60% market share on the
Internet, according to the NetCraft survey, which can be found online
at http://www.netcraft.com/archives/web_server_survey.html.

Modularity: Dynamic Shared Objects

or

IO

n
io

There are now hundreds of modules available implementing support


for a vast range of functions from server-side scripting languages like
PHP, JSP, and ASP to authentication against LDAP and SQL servers,
audio streaming, and even intrusion detection.

is

pr

Efficiency: Multi-process/Multi-thread

oh

ite

PY

To better support native operating system multi-threading features,


Apache developers have modularized Apache's multi-processing
engine. A number of Multi-Processing Modules (MPMs) exist to
implement native multi-threading features for specific operating
systems and architectures.

ib

d.

The Apache web server can be downloaded freely from the Apache
Software Foundation (ASF) at http://www.apache.org/.
Comprehensive documentation is also available at the site.

tio
bu

Apache remains one of the most actively developed open source


projects. Its success has spawned a number of important web
projects including the Java-based Jakarta projects (Ant, Tomcat,
Struts, Taglib), XML parsers and libraries (Xerces, Xalan, FOP), as well
as the popular web scripting language, PHP. In addition to its Unix
roots, which comprises the vast majority of web servers, Apache runs
on several non-Unix platforms.

ri
st

di

Apache Availability

Apache was designed to be a small, fast web server. At the same


time the server needed to be extensibleable to run the latest
features in the fast changing landscape of the Internet. To
accommodate these conflicting requirements the developers of
Apache built a modular server. Only the most basic web server
functions exist in the core Apache server. Other functionality can be
added by loading dynamic modules.

Historically Apache had a single method of operation. A child process


8-4

Note that the /usr/sbin/httpd.event binary is available as well.

EV

was assigned to exclusively serve a single connection. This turned


out to be a highly reliable method of operation. This is due to the
standard memory protection of Linux that isolates each child process
from other processes coupled with the fact that child processes are
replaced after a defined number of connection which means that
memory leaks never get too severe. This method is known as the
prefork MPM.

pr
re

Non-threadsafe Modules

ed

AL

riz
ho
ut
na

A more scalable method (yet less robust and potentially incompatible


see below) method known as the worker MPM creates multiple
child processes which each spawn multiple threads. Each thread
handles a single connection. There is an experimental MPM variant of
worker known as event that increases scalability even more by more
efficiently handling network sockets. However it sacrifices
compatibility with mod_ssl and other input filters.

t
uc

od

AT

If you use the threaded worker MPM, you must make sure that all of
the modules that you load into Apache are also threadsafe (meaning
the module's source code has been synchronized to work with
multiple threads). Otherwise a condition called "deadlock" can occur
in which a thread enters a mode to wait for a signal that the program
has no mechanism to send and the program hangs.

IO

n
io

or

Currently many of the third-party modules, and even some standard


Apache modules, are not thread-safe and deadlocks are common.
Work is being done to fix the problems, but the Apache Software
Foundation recommends using the prefork MPM when third-party
modules are required.

is

O
ite

PY

ib

oh

pr

The httpd package provides multiple httpd binaries. To switch to the


worker MPM, make the following edit:

tio
bu

Currently MPM is compiled into the httpd binary so an entirely


different binary must be used to switch MPMs. Fortunately modern
Linux distributions provide alternative binaries. This is due to change
in Apache 2.4 where a single httpd binary can load a MPM at
runtime. Use the following procedure to switch to the worker MPM:

d.

File: /etc/sysconfig/httpd
- #HTTPD=/usr/sbin/httpd.worker
+ HTTPD=/usr/sbin/httpd.worker

ri
st

di

Enabling the worker MPM

8-5

Dynamic Shared Objects

AL

riz
ho
ut
na

EV

Dynamically Load Modules at Run Time


Update or add modules without recompiling Apache.
Prototype and test features and functionality.
DSO support is provided by mod_so.c
mod_so must be statically compiled into the Apache core.
List the modules statically compiled into the Apache core
# /usr/sbin/httpd -l
Third-party Modules
Modules maintained outside of the Apache Software Foundation

pr
re

ed

Core and MPM Modules

http://modules.apache.org/

t
uc

od

AT

core Core Apache HTTP Server features that are always available
(must be compiled in).
mpm_common A collection of directives that are implemented by
more than one multi-processing module (MPM).
perchild MPM allowing daemon processes serving requests to be
assigned a variety of different UIDs.
prefork Implements a non-threaded, pre-forking web server. This
is how Apache 1.3 works.
threadpool Yet another experimental variant of the standard
worker MPM.
mpm_winnt MPM optimized for WinNT (NT/2000/XP/2003).
worker MPM implementing a hybrid multi-threaded, multi-process
web server.

mod_imap Server-side imagemap processing.


mod_include Server-parsed HTML documents (also called Server
Side Includes, or SSI for short).
mod_mime_magic Determines the MIME type of a file by looking
at the first few bytes of its content.
mod_rewrite Provides a rule-based rewriting engine to rewrite
requested URLs on the fly.
mod_so Loading of executable code and modules into the server
at start-up or restart time (must be compiled in).
mod_speling Attempts to correct mistaken URLs that users might
have entered by ignoring capitalization and by allowing up to one
character of misspelling.
mod_ssl Strong cryptography using the Secure Sockets Layer
(SSL) and Transport Layer Security (TLS) protocols.
mod_status Provides information on server activity and
performance.
mod_suexec Allows CGI scripts to run as a specified user and
group.
mod_unique_id Provides an environment variable with a unique
identifier for each request.
mod_userdir User-specific directories (i.e.
http://www.example.com/guru/).
mod_usertrack Clickstream logging of user activity on a site.

or

IO

n
io

is

O
ite

PY

ib

oh

pr

d.

8-6

tio
bu

mod_access Provides access control based on client. hostname,


IP address, or other characteristics of the client request.
mod_alias Provides for mapping different parts of the host
filesystem in the document tree and for URL redirection.
mod_auth User authentication using text filesmod_auth_anon
Allows "anonymous" user access to authenticated areas.
mod_cgi Permits execution of CGI scripts.
mod_dav Distributed Authoring and Versioning (WebDAV)
functionality.
mod_dir Provides for "trailing slash" redirects and serving directory
index files.

ri
st

di

Important Modules Included in the Apache Distribution

Adding Modules to Apache

AL

riz
ho
ut
na

EV

The APache eXtenSion (apxs) Utility


Build modules outside of the Apache source tree.
Apache C header files
Compiler and linker flags
Matches the currently running core httpd binary
SELinux Context: httpd_modules_t
Edit the httpd.conf
LoadModule
Optionally use -a or -A
Module-specific configuration directives

ed

The APache eXtenSion Utility

conf.d/mod_modulename.conf

DSO Configuration File

pr
re

Any module-specific directives should be placed into a configuration


file located in the conf.d/ directory. For example, for a module
named mod_modulename, create a file named mod_modulename.conf
(or, perhaps, modulename.conf). The filename is not important, but it
must end with the .conf filename extension.

t
uc

od

AT

Apache modules are standard shared libraries (.so on Unix, .dll on


Windows). In order for a library to be loaded and integrated into
Apache's already running binary, the module has to be precisely
compatible with the internal binary structures of the Apache program.
Those structures can vary depending on how Apache was compiled,
even including what flags were used with the compiler and linker.

RHEL6 Apache Module RPM Packaging

IO

n
io

or

The APache eXtenSion utility (part of the Apache package), is


compiled with Apache, and therefor the apxs command can be used
to compile modules after-the-fact.

O
ite

PY

ib

oh

d.

# apxs -i -a -c mod_modulename.c
. . . output omitted . . .

pr

The APache eXtenSion utility can build the module and install the
shared object file into the Apache library directory. The -a option
causes the command to insert the required LoadModule directive into
the httpd.conf file. If the -A option is used, the command will insert
the directive commented out. An example of using this utility is:

is

Using the APache eXtenSion Utility

$ httpd -l
. . . output omitted . . .

y php, mod_perl
y mod_ssl, mod_python
y mod_auth_mysql, mod_auth_pgsql, mod_auth_kerb
y mod_dav_svn, mod_authz_ldap

tio
bu

To use this extension mechanism, the platform must support DSO


module loading and the Apache binary must be built with the mod_so
module. Check if the mod_so module has been statically built into the
Apache binary with this command:

ri
st

di

There are a number of pre-built modules that can extend Apache by


installing them via the yum command. These modules are included in
these RPM packages:

8-7

Apache Configuration Files

Apache Configuration Files

ed

AL

riz
ho
ut
na

EV

The httpd.conf file is divided into three main sections:


Section 1: Global environment
Section 2: "Main" server configuration
Section 3: Virtual hosts
Apache configuration on RHEL6
/etc/httpd/conf/httpd.conf
/etc/httpd/conf.d/
SELinux Context: httpd_config_t

Section 2: "Main" Server Configuration

pr
re

Directives in this section affect the main, or default, server


environment as opposed to individual virtual host configurations. For
example: specifying multiple <Directory> block directives to limit
access to documents within the default server's shared document
root.

t
uc

od

AT

The main configuration file for Apache is httpd.conf. This file allows
for configuring global options, options that affect the main server,
and virtual hosting options. Options include the port to have the
server listen on, the server's document root directory location, or the
MPM configuration.

n
io

or

is

O
ite

PY

ib

oh

pr

d.

8-8

Each configured virtual host may have its own DocumentRoot


environment. The documents available within this environment can be
controlled within the virtual host context. For example, you can
specify multiple <Directory> block directives to limit access to
documents within the virtual host's shared document root.

The global environment for the Apache configuration has options that
affect the server itself. Directives such as MinSpareServers and
KeepAliveTimeOut tune the server's operation, and directives such as
ServerName, Listen, and LoadModule configure the server's
environment. Module specific configuration files are loaded with the
line:

Section 3: Virtual Hosts

tio
bu

Section 1: Global Environment

ri
st

di

The configuration file on RHEL6 is located at


/etc/httpd/conf/httpd.conf. Red Hat Enterprise Linux disables
public_html directories by default.

Include conf.d/*.conf

The default document root is /var/www/html/. No index file is


provided. Web browsers requesting the document root result in an
error, and a custom error page (titled "Test page") is displayed that
explains the situation.

IO

In general, the default Apache configuration provides a basic web


server for the host, providing a single place to put files that can be
shared publically, though requiring an index file to be created. In
some cases, a $HOME/public_html directory is enabled for users to
share files.

httpd.conf Server Settings

httpd.conf Section 1

ed

AL

riz
ho
ut
na

EV

Important configuration directives include:


ServerRoot
StartServers, MinSpareServers, MaxSpareServers
MaxClients
LoadModule
Listen
User/Group
SELinux
When protected, httpd processes run as the httpd_t type
Many related SELinux booleans affect restrictions imposed on
process

Syntax for the LoadModule directive is:

pr
re

ServerName The name and port that the server uses to identify
itself. Example: www.example.com:80
ServerRoot The absolute path specifying the directory structure

od

AT

LoadModule module-name filename

t
uc

under which the Apache configuration and log files are kept. On
Red Hat, this is usually set to /etc/httpd/.
StartServers Accepts a numeric argument specifying how many
servers to initially start.
MinSpareServers/MaxSpareServers These directives take
numerical arguments regulating the size of the idle Apache server
pool. At all times, at least MinSpareServers will be held in
reserve, and no more than MaxSpareServers will be running idle.
MaxClients Specifies the maximum number of simultaneous
client connections that Apache will handle. Others who connect
when the server is "full", will get a 503 (Service Unavailable) "error"
message, instead.
ServerLimit Specifies the maximum number of Apache
processes which may run. This setting will prevent the
MinSpareServers directive from causing Apache to launch more
spares.
LoadModule Used to load modules into the server and activate
them.
Listen Specifies the port(s) to which Apache should bind. By
default, this is 80 for HTTP and 443 for HTTPS.
User/Group Specify the user and group (either by name or ID) the
Apache process should run as. For security reasons, it's a good
idea to create a special user and group for this.

or

IO

n
io

Apache module RPMs place their configuration files in the


/etc/httpd/conf.d/ directory. Apache will include all files in the
/etc/httpd/conf.d/ directory with names that end in .conf. For
example, to configure the SSL options edit the
/etc/httpd/conf.d/mod_ssl.conf file.

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

8-9

httpd.conf Main Configuration

pr
re

Shared Directives

ed

AL

riz
ho
ut
na

EV

Important configuration directives include:


DocumentRoot
SELinux context for HTML files: httpd_sys_content_t
Alias url-path /path/to/{file,dir}
<Directory /path/to/dir></Directory>
<Location url-path></Location>
AccessFileName
MIME type definitions and handlers: /etc/mime.types
Log file locations and formats
Module specific configuration blocks

maps to (the root of the site).

od

AT

DocumentRoot Specifies what filesystem path the root URL path


Alias url-path /path/to/{file,dir} Maps a URL into the

t
uc

filesystem namespace. Allows Apache to serve documents that


exist outside of <DocumentRoot>.
<Directory /path/to/dir> . . . </Directory> Limits the scope of
the configuration options contained within the block to just the
filesystem path(s) specified.
<Location url-path> . . . </Location> Limits the scope of the
configuration options contained within the block to just the URL
path(s) specified.
AccessFileName Specifies the name of the file in each directory
which can set access control information. If omitted, the default
name .htaccess is used.
TypesConfig MIME type definitions can extend Apache's support
for additional file types, such as new compression algorithms, by
defining handlers (external programs which can be launched to
handle files for which Apache doesn't have built-in support). The
definitions of available mime types are found in the
/etc/mime.types file.
AddType Can override the types defined in the TypesConfig
specified file or add additional types.

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

8-10

HTTP Virtual Servers

Virtual Servers

ed

AL

riz
ho
ut
na

EV

Virtual Web Hosting


Serving multiple domains from a single server
HTTP 1.0: IP-based hosting
HTTP 1.1: IP-based and name-based hosting
Dynamic Mass Virtual Hosting
Add directory to your filesystem
No config changes
No server restart

Dynamic Mass Virtual Hosting

pr
re

An Internet Service Provider (ISP) or web hosting service will often


use virtual servers to host multiple domains. Using the Apache web
server, these service providers can add new virtual hosts by adding a
directory to their filesystems. No configuration file changes are
needed and therefore the web server does not have to be restarted.
This technique involves using the mod_vhost_alias Apache module
and then specifying the VirtualDocumentRoot and
VirtualScriptAlias directives in the httpd.conf configuration file
with variable placeholders specifying the domain name being served.
For example, these configuration directives enable mass virtual
hosting under the /srv/www/hosts/ directory:

t
uc

od

AT

For a single machine to host several domains, it must be able to


differentiate between inbound requests and route them to the
appropriate virtual server.

or

IO

n
io

The two most common mechanisms used to differentiate the


inbound requests are IP-based and Name-based Virtual Hosts.
IP-based virtual hosts handle requests inbound to a specific IP
address, whereas Name-based virtual hosts handle requests based
on the Host: header specified in the inbound request by the web
client.

tio
bu

ri
st

di

A third mechanism, Port-based virtual hosting, is less commonly used


because it often requires manual manipulation of the URL by the
client.

is

O
ite

PY

ib

oh

pr

You can find complete details at

d.

See http://httpd.apache.org/docs-2.2/vhosts/ for detailed


documentation on configuration of virtual hosts under Apache.

# Obtain the server name from the Host: header


UseCanonicalName Off
# Prefix log entries with virtual host name
LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
CustomLog logs/access_log vcommon
# Use /srv/www/hosts/servername/html as documentroot
VirtualDocumentRoot /srv/www/hosts/%0/html

The older HTTP 1.0 protocol does not provide the Host: header and
is therefore limited to IP-based solutions for virtual hosting. On the
other hand, the HTTP 1.1 protocol introduces, and requires, the Host:
header, providing a way for the client application to specify the fully
qualified domain name of the server to which it is connecting. This
allows multiple virtual servers to all listen on the same IP and port
and route requests to the appropriate virtual server by name only.

File: httpd.conf

http://httpd.apache.org/docs-2.2/vhosts/mass.html.

8-11

Virtual Hosting DNS Implications

IP-based vs. Name-based Virtual Hosts

ed

AL

riz
ho
ut
na

EV

IP-based Virtual Hosting


Multiple IP addresses bound to NIC
Each DNS record maps to own unique IP address
www.dom1.com -> 192.0.2.1
www.dom2.com -> 192.0.2.2
Name-based Virtual Hosting
Single IP address
Multiple DNS records map to the single IP address
www.dom1.com -> 192.0.2.10
www.dom2.com -> 192.0.2.10

pr
re

The alias configuration files contain the same information needed to


configure a physical network interface: IP address, subnet mask, etc.

AT

Although virtual hosts can share a single server, each virtual host still
requires its own DNS record. For IP-based hosting, each DNS record
must point to one or more unique IP addresses. To conserve IP
addresses, HTTP version 1.1 added the Host: header, which made
name-based virtual hosting possible. Although virtual hosts may share
a single IP when using name-based virtual hosting, clients are
required to include the server's fully qualified domain name in the
Host: header. This makes it possible to distinguish the intended
virtual host for each request.

HTTPS and Virtual Hosting

t
uc

od

or

IO

n
io

C
O
ite

PY

ib

oh

pr

d.

8-12

is

ifcfg-eth0
ifcfg-eth0:1
ifcfg-eth0:2
ifcfg-eth0:3

Under RHEL6 you can create interface aliases by populating files in


the /etc/sysconfig/network-scripts/ directory. The configuration
files are named by placing a colon and the alias number after the
network device name of the physical interface you are aliasing. For
example, if the device eth0 had four IP addresses bound to it, you
would create these files:

tio
bu

Linux supports assigning multiple IP addresses to a single physical


network card. One way to accomplish this is using interface aliases.
For example, eth0 could have one address while the alias eth0:0
could have another.

ri
st

di

Binding IP Addresses for IP-based Hosting

The HTTPS protocol requires that an SSL handshake occur as the


very first step. During the SSL handshake the web server sends the
client its certificate. The certificate contains the FQDN of the web
server. For name-based virtual HTTPS hosting to work, the web
server would have to know which certificate to send to the client
during the SSL handshake. The server doesn't know this until the
client sends the Host: header transmitted after a successful SSL
handshake. Therefore, virtual hosting SSL sites requires the use of
unique IP addresses for each site.

httpd.conf VirtualHost Configuration

VirtualHost Directives

ed

AL

riz
ho
ut
na

EV

NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin sinuhe@linuxtraining.com
DocumentRoot "/srv/lt"
ServerName www.linuxtraining.com
ServerAlias linuxtraining.com
</VirtualHost>

specifies which directory is being served by a specific virtual host.

pr
re

t
uc

od

AT

The first VirtualHost entry overrides the Main configuration, (and


inherits what it does not override). It is the default fallback for any
undefined ServerName referenced by the name server.

NameVirtualHost Specifies which IP address (or address:port

or

IO

n
io

pairs) you want to configure to serve multiple domains by name.


This will usually be the address to which your name-based virtual
hostnames resolve. You can enter the IP address or use the *
wildcard.
<VirtualHost *:80> . . . </VirtualHost> This block directive
specifies the options for the virtual namespace. The IP address
specified as an option inside the directive must exactly match the
IP address or wildcard used in the NameVirtualHost directive.
Within the <VirtualHost> directive's block you can specify any
directives that can be used in section 2 of the httpd.conf file for
configuring the main server's webspace.
ServerName Use this directive within the <VirtualHost> block to
tell Apache which domain is being served by this <VirtualHost>.
If the address:port pair specified in the <VirtualHost> block
wrapped around this ServerName directive matches one of the
NameVirtualHost values, then the value of ServerName will be
used by Apache to identify which <VirtualHost> to use.
ServerAlias Specifies additional names the containing
<VirtualHost> block applies to. ServerAlias can only be used
within <VirtualHost> blocks.
DocumentRoot When used within the <VirtualHost> block,

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

8-13

Port and IP based Virtual Hosts

Port-based Virtual Host

ed

AL

riz
ho
ut
na

EV

Port-based
Multiple Sites Single Host
Single IP Address and Host Name
No Additional DNS Entries
Client Specifies Port in URL
Listen and NameVirtualHost Directives
IP-based
Multiple IP Addresses Single Host
Multiple Network Interfaces
Network Interface Aliases
One-to-One Domain to IP Address
VirtualHost Directive for Each Virtual Host

IP-based Virtual Host

pr
re

The best practice is to use IP-based virtual hosting from port 80. You
can host multiple domains from the same server by binding the IP
addresses of the domains to the network interface of the single host.
These IP addresses must then exist in the DNS for the domains they
serve.

t
uc

od

AT

Port-based virtual servers allow multiple web sites to run on a single


host without having to update DNS records. The drawback is that the
URL must specify the port number. Port-based virtual hosting can be
used in conjunction with IP-based or Name-based virtual hosting, or
standalone. To configure Apache for Port-based virtual hosting,
specify Listen directives for each port number, and IP address if
needed. This lends flexibility, allowing multiple IP addresses to be
served on separate ports. This example illustrates a web server using
a single IP address to serve two virtual hosts on different ports.

or

IO

n
io

<VirtualHost 192.0.2.166>
ServerName www.foo.com
DocumentRoot /srv/www/virtual/foo.com/docroot
</VirtualHost>

is

oh

pr

ite

PY

<VirtualHost 209.140.64.2>
ServerName www.bar.com
DocumentRoot /srv/www/virtual/bar.com/docroot
</VirtualHost>

ib

d.

8-14

File: httpd.conf

<VirtualHost 192.0.34.166:3080>
ServerName www.foo.com
DocumentRoot /srv/www/virtual/foo.com-port3080/docroot
. . . snip . . .
</VirtualHost>

<VirtualHost 192.0.34.166:80>
ServerName www.foo.com
DocumentRoot /srv/www/virtual/foo.com-port80/docroot
. . . snip . . .
</VirtualHost>

tio
bu

Listen 80
Listen 3080

ri
st

di

File: httpd.conf

For example, the IP addresses 192.0.2.166 and 209.140.64.2 are


either bound to multiple network cards on the host, or the host has a
single network card bound with multiple IP address aliases. The
following example illustrates the Apache httpd.conf file virtual host
configuration for two virtual hosts with IP addresses 192.0.2.166 and
209.140.64.2.

Name-based Virtual Host

Name-based Virtual Host

ed

AL

riz
ho
ut
na

EV

Multiple Host Names Single Host


Single IP Address
NameVirtualHost Directive
VirtualHost Directive for Each Virtual Host

File: httpd.conf

pr
re

NameVirtualHost *:80

t
uc

od

AT

With the HTTP1.1 specification's Host: header, you can now specify
virtual hosting based on the fully-qualified domain name of the host.
The benefit is that you can now host multiple virtual domains from a
single host bound to a single IP address.

or

IO

n
io

Each virtual host has a DNS entry pointing to the same IP address.
This IP address must be specified in the NameVirtualHost directive in
the Apache httpd.conf configuration file. Alternatively, you can
specify all inbound IP addresses by using the wildcard character, *,
with the NameVirtualHost directive.

<VirtualHost *:80>
ServerName www.foo.com
DocumentRoot /srv/www/virtual/foo.com/docroot
. . . snip . . .
</VirtualHost>

tio
bu

ri
st

di

Each virtual host needs a VirtualHost directive entry in the Apache


httpd.conf file. The IP address in the VirtualHost directive must
match the IP address specified in the NameVirtualHost directive.
Therefore, if the wildcard is used with NameVirtualHost, the same
wildcard must be used with the VirtualHost directive.

<VirtualHost *:80>
ServerName www.bar.com
DocumentRoot /srv/www/virtual/bar.com/docroot
. . . snip . . .
</VirtualHost>

is

O
ite

PY

ib

oh

pr

d.

8-15

Apache Logging

EV

Log formats
Common Log Format
Combined logs
Log customization
LogFormat
CustomLog

riz
ho
ut
na

access_log

AL

ErrorLog

ed

Apache Logging

error_log
SELinux Context: httpd_log_t

pr
re

Additional logging formats are pre-defined and can be used by


uncommenting the appropriate line in the stock httpd.conf file
shipped with Linux.

od

AT

Apache supports a very flexible logging mechanism that lets you


define exactly what you want to log and where you will log it to.

Custom LogFormat

t
uc

Traditionally web servers have used Common Log Format (CLF), and
depending on what you plan on doing with your Apache logs, you
may need to use CLF. For example if you plan on using a log analysis
package which only supports CLF. CLF logs the requesting host
("host"), the username of the client as reported by identd ("ident"), the
user ID used if the request was for a password-protected document
("authuser"), the date and time of the request ("date"), the response
returned to the client ("status"), and the number of bytes returned to
the client ("bytes").

or

IO

n
io

This example illustrates a more specific logging task in which a


separate log is created for broken referralssites elsewhere which
link to pages on your server which don't exist. You might then have a
log analysis tool or script that reads this file and sends an email
report to a web developer who can notify the owners of the linked
web sites. You can create the new format by creating a new
LogFormat directive and then using the new format in a CustomLog
directive. For example:

http://httpd.apache.org/docs-2.2/mod/mod_log_config.html#formats

O
ite

PY

ib

oh

pr

d.

8-16

For a detailed description of the LogFormat variable formatters, see

is

LogFormat "%h %l %u %t \"%r\" %>s %b" common


CustomLog /var/log/httpd/access_log common

LogFormat "%!200,304,302{Referer}i" broken


CustomLog /var/log/httpd/broken_referral_log broken

Configuration of logging in Apache is extremely flexible and can be


based on the response returned. You can also specify separate log
files for each virtual server. Logging styles are first defined with the
LogFormat directive and then used with a CustomLog statement. For
example:

tio
bu

Log Customization

ri
st

di

Another standard log format is the "combined" log which extends the
CLF by adding the previous URL the client was at ("referer") and what
software the client is using ("user agent").

Log Analysis

Apache Log Analysis

ed

AL

riz
ho
ut
na

EV

Apache Log Analysis


HostnameLookups
Log Analysis Tools
Summaries of page access, Kbytes downloaded, etc.
Analog
Webalizer
AWStats
Log Maintenance and Rotation
Apache's rotatelogs program

Log Analysis Tools

pr
re

Multiple utilities exist that can process raw logs and produce more
meaningful data. These tools provide services like access summaries,
graphing, charts, etc. on a daily, weekly, or monthly basis. The
reports are often rendered in HTML making them immediately
accessible.

t
uc

od

AT

Browsing through your Apache log files can give you isolated
information about pages accessed, kbytes downloaded, etc., but to
be useful you need summaries of the information into reports. This
analysis can give you information about parts of the site that are not
being visited or let you know when your system needs to be
upgraded.

Analog is the oldest log analysis tool. The reports it produces have a
dated look and lack the detail of newer tools.

or

IO

n
io

Disable Hostname Lookups

The Webalizer is a robust analysis tool written in C for speed.


The AWStats is the newest utility and produces the nicest looking
reports with very good detail that also offers the ability to drill down
to specific time periods. The package can be obtained from
http://awstats.sourceforge.net/.

Keep in mind that the web logs may need periodic rotating. Every
10,000 hits will use approximately one megabyte of drive space, so
as your server becomes popular, the web logs could overload your
storage unless they are periodically trimmed. Apache ships with the
rotatelogs program which can be used to automatically rotate log
files by doing logging through a pipe. This example will rotate the
access log every 24 hours (that's every 86,400 seconds).

ite

PY

ib

oh

pr

d.

Note that most log analysis tools provide hostname lookups


themselves.

is

# logresolve < access_log > output_log

Log Maintenance and Rotation

Apache provides the logresolve program which will lookup


hostnames for the IP addresses within the log file and rewrite the
output. This way you can update the hostnames as a batch during
analysis rather than take the performance hit real-time. This example
processes the access_log file and redirects the output to a new log
that can now be used for analysis.

tio
bu

ri
st

di

Apache can log requests either by IP address or by hostname. For


performance and network traffic reasons you should configure
Apache to log requests by IP address. Logging by hostname requires
at least one additional DNS lookup for every client request that the
server receives. This behavior is controlled in the httpd.conf file by
the HostnameLookups directive.

TransferLog "|rotatelogs access_log 86400"

8-17

The Webalizer

pr
re

The Webalizer

ed

AL

riz
ho
ut
na

EV

Webalizer can process your web server logs and create graphs and
statistics such as:
Number of hits per hour, day, month, etc.
Entry and exit pages
Top referrers
Bandwidth usage by hour, day, month, etc
By default, report available at
http://server/usage/

t
uc

od

AT

In addition to analysis of web logs, the Webalizer can also analyze


logs from many other common services, such as squid and wu-ftpd.
It also has support for analysis of incremental logs such as those
created by rotatelogs, an increasingly important feature as your site
becomes popular and your web logs become huge.

n
io

or

IO

A great resource to check out if you encounter problems with the


Webalizer is http://www.mrunix.net/webalizer/, which has
documentation and example configuration files.

is

O
ite

PY

ib

oh

pr

Webalizer is included on RHEL6 and when the RPM is installed,


places a script in the /etc/cron.daily/ directory. The script checks
for the existence of the /var/log/httpd/access_log file, and if it
exists, runs /usr/bin/webalizer.

http://server/usage/

tio
bu

The configuration file is /etc/webalizer.conf. The produced report is


available from:

ri
st

di

Webalizer Configuration Details

d.

8-18

Lab 8

EV

Estimated Time: 75 minutes

Task 1: Apache Architecture

AL

riz
ho
ut
na

Page: 8-20
Time: 15 minutes
Requirements: b (1 station) c (classroom server)

Task 2: Apache Content

ed

Page: 8-23
Time: 15 minutes
Requirements: b (1 station)

pr
re

Task 3: Configuring Virtual Hosts

t
uc

od

AT

Page: 8-25
Time: 45 minutes
Requirements: b (1 station) d (graphical environment)

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

8-19

Lab 8

Objectives
y Explore the Apache Configuration
y Determine which Apache modules are configured to load

EV

Task
1
Apache Architecture

Requirements
b (1 station) c (classroom server)

Estimated Time: 15 minutes

AL

Install the Apache web server and manual packages:

ed

1)

riz
ho
ut
na

Relevance
Apache has many components and can be installed onto a system in a
wide variety of ways by a Linux distributor. Knowing how Apache is
installed on the system will enable you to quickly administer it.

od

Get an idea of where the main Apache files are located:

IO

or

Examine the main Apache configuration directory structure:

tio
bu

ri
st

di

3)

n
io

# rpm -ql httpd | less


/etc/httpd
/etc/httpd/conf
/etc/httpd/conf.d
/etc/httpd/conf.d/README
. . . snip . . .

t
uc

2)

AT

pr
re

# yum install -y httpd httpd-manual


. . . output omitted . . .

# ls -l /etc/httpd
total 28
drwxr-xr-x 2 root root 4096 Aug 18 15:19 conf
drwxr-xr-x 2 root root 4096 Aug 18 17:41 conf.d
lrwxrwxrwx 1 root root 19 Aug 18 14:50 logs -> ../../var/log/httpd
lrwxrwxrwx 1 root root 27 Aug 18 14:50 modules -> ../../usr/lib/httpd/modules
lrwxrwxrwx 1 root root 13 Aug 18 14:50 run -> ../../var/run

is

O
ite

d.

8-20

PY

ib

oh

pr

Notice the symbolic links.

4)

Examine the main configuration file:


No need to read every line, just skim through to get a
feel for the structure and how well commented it is.

Examine the main configuration file stripping out all comments to see just the
actual configuration directives:

AL

riz
ho
ut
na

5)

EV

# cd /etc/httpd/conf
# less httpd.conf

# egrep -v "^ *(#|$)" httpd.conf | less

6)

t
uc

tio
bu

ri
st

di

List which Apache modules are available from the repositories configured on your
system (most Apache module RPMsincluding 3rd party modulesfollow the
naming convention mod_module_name):

8)

cd /etc/httpd/conf.d/
ls -l
. . output omitted . . .
cat manual.conf
cat README

or

#
#
.
#
#

IO

Determine which Apache configuration files are in that directory, examine a


configuration file, and then read the README contained therein:

n
io

7)

od

# grep ^Include httpd.conf


Include conf.d/*.conf

AT

pr
re

ed

Apache configuration supports the Include directive that enables the


configuration to be loaded from alternative files. This is used by default. Find
exact configuration line in order to determine the directory and file pattern for
configuration files that are automatically loaded:

is

O
ite

d.

The Apache web server comes with many modules for specific features and
functionality. Most modules are loaded by default. For example, the mod_proxy
module enables Apache to function as a caching proxy server. Determine which
Apache modules are enabled:

PY

ib

oh

9)

pr

# yum list mod_*


. . . output omitted . . .

8-21

t
uc

[ OK ]

or

IO

n
io

# service httpd start


Starting httpd:
# chkconfig httpd on

11)

AT

Start Apache and configure it for persistence:

od

10)

pr
re

ed

AL

riz
ho
ut
na

EV

# grep LoadModule /etc/httpd/conf/httpd.conf


. . . output omitted . . .
# grep LoadModule /etc/httpd/conf.d/*.conf
. . . output omitted . . .
# httpd -M
Loaded Modules:
core_module (static)
mpm_prefork_module (static)
http_module (static)
so_module (static)
auth_basic_module (shared)
auth_digest_module (shared)
authn_file_module (shared)
. . . snip . . .
Syntax OK

ri
st

di

Determine where Apache is configured to log to by the values of ErrorLog and


CustomLog:

tio
bu

# grep -E ^(Error|Custom)Log /etc/httpd/conf/httpd.conf


ErrorLog logs/error_log
CustomLog logs/access_log combined
# ls -dl /etc/httpd/logs
lrwxrwxrwx 1 root root 19 Aug 18 14:50 /etc/httpd/logs -> ../../var/log/httpd
# ls -l /var/log/httpd
total 12
-rw-r--r-- 1 root root 0 Aug 18 18:29 access_log
-rw-r--r-- 1 root root 440 Aug 18 18:29 error_log
# cat /var/log/httpd/error_log
. . . output omitted . . .

is

O
ite

PY

ib

oh

pr

d.

8-22

Lab 8

Objectives
y Create an index.html file

EV

Task
2
Apache Content

Requirements
b (1 station)

Estimated Time: 15 minutes

AL

1)

riz
ho
ut
na

Relevance
Being able to create minimal content for Apache is a basic task for System
Administrators. By doing so, an administrator can confirm that Apache is
serving up the correct files.

od

AT

pr
re

ed

By default on RHEL the Apache document root directory is /var/www/html/. If a


web browser connects to the web server without specifying a file (e.g.
http://stationX.example.com/), Apache will search the DirectoryIndex
directive for a list of resources. These resources are usually the name of a file
within the directory. Apache will return the first one that it finds.

t
uc

Determine what file(s) Apache looks for by seeing what parameter the
DirectoryIndex directive has by default:
The files are listed in order of preference from left to
right. The index.html.var can be used for auto
language negotiation between Apache and the web
browser.

tio
bu

ri
st

# ls -al /var/www/html/
total 4
drwxr-xr-x 2 root root 4096 Jul 15 2009 .
drwxr-xr-x 9 root root 4096 Aug 18 14:50 ..

di

Determine if either file exists:

or

2)

IO

n
io

# grep ^DirectoryIndex /etc/httpd/conf/httpd.conf


DirectoryIndex index.html index.html.var

is

3)

d.

This configuration file enables the default "Welcome"


page if there is no default index page present for
the root URL. To disable the Welcome page, comment
out all the lines below.

PY

cat /etc/httpd/conf.d/welcome.conf

ite

#
#
#
#
#
#

ib

oh

pr

As you see, there is not a /var/www/html/index.html file. The configuration


directive in the file /etc/httpd/conf.d/welcome.conf specifies the error page to
load if there is not an index file present:

8-23

4)

EV

#
<LocationMatch "^/+$">
Options -Indexes
ErrorDocument 403 /error/noindex.html
</LocationMatch>

AL

riz
ho
ut
na

Connect to http://stationX.example.com/ using an HTTP user agent and verify


that the Test Page (/var/www/error/noindex.html) is displayed:

od

Create the new /var/www/html/index.html file with content that identifies your
workstation:

t
uc

5)

AT

pr
re

ed

# wget --server-response --spider http://stationX.example.com


--13:53:55-- http://stationX.example.com/
Resolving stationX.example.com... 10.100.0.X
Connecting to stationX.example.com|10.100.0.X|:80... connected.
HTTP request sent, awaiting response...
HTTP/1.1 403 Forbidden
. . . snip . . .

or

IO

n
io

tio
bu

ri
st

di

is

O
PY

Connect to http://stationX.example.com/ with a web browser and verify that


the new web page is displayed.

ite

6)

ib

oh

pr

File: /var/www/html/index.html
+ <!DOCTYPE html>
+ <html lang="en-US">
+ <head>
+ <meta charset="UTF-8">
+ <title>Your Names Web Server</title>
+ </head>
+ <body>
+ <h1>StationX</h1>
+ <p>Hello, World!</p>
+ </body>
+ </html>

d.

8-24

Lab 8

Objectives
y Configure Apache Virtual Hosts
y Use the "Main" server for global settings
y Create virtual servers for www.superthingy.org and
www.random-nonsense.com

EV

Task
3
Configuring Virtual Hosts
Estimated Time: 45 minutes

AL

riz
ho
ut
na

Requirements
b (1 station) d (graphical environment)

t
uc

or

IO

n
io

$ su -l
Password: makeitso

2)

AT

The following actions require administrative privileges. Switch to a root login


shell:

od

1)

pr
re

ed

Relevance
Using virtual hosts is a method that webservers use to host more than one
domain on the same server. Making use of virtual hosts will allow an
administrator to save resources by combining multiple domains onto a
single server, thus reducing the extra overhead of maintaining a single
server for each site being served.

tio
bu

ri
st

di

Before you can bring up any virtual hosts, name resolution must be functioning
properly. In order to avoid configuring BIND with a new zone for your virtual hosts,
configure the /etc/hosts file for name resolution. Add your virtual hosts to the
127.0.0.1 line as follows:

File: /etc/hosts
- 127.0.0.1 localhost.localdomain localhost
+ 127.0.0.1 localhost.localdomain localhost www.superthingy.orga

is

www.random-nonsense.com

Create directories to serve as your virtual host's document root directories:

ite

PY

ib

d.

# mkdir -p /srv/www/{html,superthingy,random-nonsense}
# restorecon -R /srv/www

oh

pr

3)

8-25

4)

Create the index.html for each virtual host.

Configure Apache to handle requests for your virtual hosts by creating a virtual
host configuration file snippet that will be automatically included into the Apache
configuration and adding a NameVirtualHost directive as the first line in the file:

AL

riz
ho
ut
na

5)

EV

# echo "Super Thingy Website" > /srv/www/superthingy/index.html


# echo "Random Nonsense Website" > /srv/www/random-nonsense/index.html

File: /etc/httpd/conf.d/vhosts-127.0.0.1.conf
+ NameVirtualHost 127.0.0.1:80

ed

Append the superthingy.org and random-nonsense.com virtual host entries to the


file just created:

t
uc

od

AT

pr
re

6)

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

8-26

File: /etc/httpd/conf.d/vhosts-127.0.0.1.conf

NameVirtualHost 127.0.0.1:80
<VirtualHost 127.0.0.1:80>
ServerName www.superthingy.org
ServerAdmin webmaster@superthingy.org
DocumentRoot /srv/www/superthingy
ErrorLog logs/superthingy-error_log
TransferLog logs/superthingy-access_log
<Directory /srv/www/superthingy>
Options Indexes FollowSymLinks ExecCGI Includes
</Directory>
</VirtualHost>

pr
re

ed

AL

riz
ho
ut
na

AT

<VirtualHost 127.0.0.1:80>
ServerName www.random-nonsense.com
ServerAdmin webmaster@random-nonsense.com
DocumentRoot /srv/www/random-nonsense
ErrorLog logs/random-nonsense-error_log
TransferLog logs/random-nonsense-access_log
<Directory /srv/www/random-nonsense>
Options Indexes FollowSymLinks ExecCGI Includes
</Directory>
</VirtualHost>

t
uc

od

IO

or

tio
bu

ri
st

di

Open a second terminal window, switch to a root login shell, and monitor the
Apache error log:

is

oh

pr

$ su -l
Password: makeitso
# tail -f /var/log/httpd/error_log

ite

d.

# apachectl configtest
Syntax OK

PY

Run a syntax check on the changes you have made to the Apache configuration:

ib

8)

n
io

7)

EV

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

If you get an error message, note the line number and


fix it by editing httpd.conf.

8-27

9)

Restart the Apache web server:

EV

# service httpd restart


Stopping httpd:
Starting httpd:

[ OK ]
[ OK ]

Use a web browser to connect to the http://www.superthingy.org/ URL. You


should see "Super Thingy Website." Also try connecting to the
http://www.random-nonsense.com URL. If your results are not what you
expected, check the logs and verify your virtual host configuration in the
httpd.conf file.

11)

Use a web browser to connect to the http://localhost URL. Did you get the
expected results? Can you explain what happened?

AT

pr
re

ed

AL

riz
ho
ut
na

10)

t
uc

od

When you specify an IP address in a NameVirtualHost directive the requests to


that IP address will only be served by matching <VirtualHost> sections. The
"Main" server context will no longer service requests to the IP address listed in the
NameVirtualHost directive. Therefore, when you use name-based virtual hosts you
no longer use the "main" server as an independent web server context. The "Main"
server becomes merely a place for configuring directives that are common for
your virtual hosts which your virtual hosts can override within their <VirtualHost>
sections.

or

IO

n
io

ri
st

di

Configure your localhost to be its own virtual web server by setting up another
name-based virtual host by appending the following to the configuration file
previously created:

tio
bu

12)

is

O
ite

PY

ib

oh

pr

d.

8-28

Run a syntax check on the changes you have made to the Apache configuration:

IO
N

ri
st

di

[ OK ]
[ OK ]

tio
bu

Use a web browser to connect to the http://localhost URL. You should now
see the index.html of your main server document root, or the test page.

Cleanup

is

Restore the pre-lab configuration by renaming the vhosts-127.0.0.1.conf file so


that it no longer ends in .conf and therefore won't be automatically included into
Apache's configuration.

PY

d.

cd /etc/httpd/conf.d
mv vhosts-127.0.0.1.conf vhosts-127.0.0.1.conf.disabled
service httpd restart
. . output omitted . . .

ite

#
#
#
.

ib

oh

pr

16)

or

15)

n
io

# service httpd restart


Stopping httpd:
Starting httpd:

AT

Restart the Apache web server:

If you get an error message, note the line number and


fix it by editing httpd.conf.

t
uc

14)

od

# apachectl configtest
Syntax OK

pr
re

13)

ed

AL

riz
ho
ut
na

EV

File: /etc/httpd/conf.d/vhosts-127.0.0.1.conf
+ <VirtualHost 127.0.0.1:80>
+ ServerName localhost
+ ServerAlias localhost.localdomain
+ ServerAdmin webmaster@localhost.localdomain
+ DocumentRoot /var/www/html
+ ErrorLog logs/localhost-error_log
+ TransferLog logs/localhost-access_log
+ <Directory /var/www/html>
+
Options Indexes FollowSymLinks ExecCGI Includes
+ </Directory>
+ </VirtualHost>

8-29

17)

Exit from the tail command, and exit from the second terminal.

Administrative privileges are no longer required; exit the root shell to return to an
unprivileged account:

t
uc

od

AT

pr
re

ed

AL

# exit

riz
ho
ut
na

18)

EV

c
d
d

or

IO

n
io

tio
bu

ri
st

di

is

O
ite

PY

ib

oh

pr

d.

8-30

Vous aimerez peut-être aussi