Copyright © 2006 Pakistan Software Export Board (G) Limited Ministry of Information Technology Government of Pakistan Printing Artland Communications

, Lahore. September 2006 Published by Pakistan Software Export Board The Funding Agency This open source toolkit is funded by the Open Source Resource Center (OSRC) project of the Pakistan Software Export Board (PSEB). PSEB is the entity within Government charged with the task of enhancing exports of software and IT enabled services (ITES) from Pakistan. PSEB is a guarantee limited company totally owned and funded by the Government of Pakistan. Any questions or comments about this toolkit may be directed to PSEB Islamabad at 92-51-111-333-666 or through e-mail at osrc@pseb.org.pk. Disclaimer This toolkit is published by the PSEB for members of the IT industry and the public-at-large. The toolkit’s compilers, or the editor, are not responsible, in any way possible, for the errors/omissions of this toolkit. The OSRC does not accept any liability for any direct and consequential use of this toolkit or its contents. The contents of this toolkit may be distributed only subject to the terms and conditions set forth in the Open Publication License v 1.0 or later. The latest version is presently available at http://opencontent.org/openpub/

i

TABLE OF CONTENTS INTRODUCTION...............................................................................................................................................1 DOMAIN NAME SYSTEM (DNS)........................................................................................................2 1. NAMED.CONF..............................................................................................................................................3 2. STEP-BY-STEP CONFIGURATION GUIDE..........................................................................................................3 APACHE WEB SERVER ......................................................................................................................8 1. INTRODUCTION TO APACHE.......................................................................................................9 2. INSTALLATION............................................................................................................................................9 2.1. Installing from the rpm..................................................................................................................9 2.2. Installing from the source............................................................................................................10 3. APACHE CONFIGURATION..........................................................................................................................10 3.1. Running Apache...........................................................................................................................11 4. BASICS OF APACHE CONFIGURATION...........................................................................................................11 4.1. Server-wide configuration...........................................................................................................11 4.2. Site-specific configuration...........................................................................................................12 4.3. Virtual Hosts................................................................................................................................12 4.4. Authentication, Authorization and Access Control.....................................................................14 4.5 Logging.........................................................................................................................................17 5. AN EXAMPLE SET-UP...............................................................................................................................17 6. REFERENCE ............................................................................................................................................18 MAIL SERVER.....................................................................................................................................19 1. HOW ELECTRONIC MAIL WORKS...............................................................................................................20 1.1 Mail between full-time Internet machines....................................................................................20 2. NOTIFIERS...............................................................................................................................................22 3. MAILBOX FORMATS..................................................................................................................................22 4. CHOOSING A MAIL TRANSPORT AGENT (MTA)..........................................................................................22 4.1 Sendmail.......................................................................................................................................23 4.2 smail v3.2......................................................................................................................................23 4.3 qmail.............................................................................................................................................23 5. LOCAL DELIVERY AGENTS (LDAS)...........................................................................................................23 6. USER AGENT ADMINISTRATION..................................................................................................................23 6.1 Mutt...............................................................................................................................................23 6.2 Elm................................................................................................................................................23 6.3 Mailx.............................................................................................................................................24 7. SENDMAIL - STEP-BY-STEP CONFIGURATION ................................................................................................24 7.1. MTA (sendmail)...........................................................................................................................24 7.2. POP3............................................................................................................................................26 7.3. Starting and Testing the Mail Server...........................................................................................26 8. QMAIL - STEP-BY-STEP CONFIGURATION ....................................................................................................26 8.1. Pre-requisites/Pre-installation steps...........................................................................................27 8.2 qmail Installation and Configuration...........................................................................................28 8.3. qmail additional tools and utilities..............................................................................................30
8.1.1. Required software/packages.............................................................................................................27 8.1.2. Software/packages that should not be installed................................................................................28 8.2.1. Download qmail...............................................................................................................................28 8.2.2. Installing qmail.................................................................................................................................28 8.3.1. ezmlm...............................................................................................................................................30 8.3.2. Autoresponder..................................................................................................................................30 8.3.3. Vpopmail..........................................................................................................................................30 8.3.4. Vqadmin...........................................................................................................................................30 8.3.5. Maildrop...........................................................................................................................................31 8.3.6. Qmailadmin......................................................................................................................................31 4.3.1. IP-Based...........................................................................................................................................13 4.3.2. Name-Based.....................................................................................................................................13

8.4. qmail Configuration.....................................................................................................................32 8.5. Testing qmail Installation and Configuration.............................................................................32 8.6. Courier-imap/imaps and Courierpassd.......................................................................................34

i

8.7. SquirrelMail.................................................................................................................................37 8.8. ClamAntivirus and SpamAssasin.................................................................................................39 9. REFERENCES............................................................................................................................................41 DYNAMIC HOST CONFIGURATION PROTOCOL (DHCP).......................................................42 1. INTRODUCTION.........................................................................................................................................43 2. INSTALLTION............................................................................................................................................43 2.1. Server Configuration...................................................................................................................43 2.2. Client Configuration....................................................................................................................45 3. REFERENCES............................................................................................................................................45 LIGHTWEIGHT DIRECTORY ACCESS PROTOCOL (LDAP)...................................................46 1. OVERVIEW:.............................................................................................................................................47 2. HOW DOES LDAP WORK?........................................................................................................................47 3. LDAP BACK-ENDS, OBJECTS AND ATTRIBUTES.............................................................................................48 4. STEP-BY-STEP CONFIGURATION GUIDE........................................................................................................49 4.1. Scenario.......................................................................................................................................49 4.2. Downloading and Installing the LDAP Packages.......................................................................49 4.3. Configuring the LDAP Server.....................................................................................................50
4.2.1. Required LDAP Server RPMs..........................................................................................................49 4.2.2. Required LDAP Client RPMs..........................................................................................................50 4.3.1. Create a database directory...............................................................................................................50 4.3.2. Create an LDAP "root" password.....................................................................................................50 4.3.3. Edit the slapd.conf file......................................................................................................................50 4.3.4. Start the LDAP daemon...................................................................................................................51 4.3.5. Convert the /etc/passwd file into LDIF format.................................................................................51 4.3.6. Create the ldapuser test account.......................................................................................................51 4.3.7. Extract the required records from /etc/passwd..................................................................................51 4.3.8. Find the conversion script................................................................................................................51 4.3.9. Convert the ".ldapuser" file..............................................................................................................52 4.3.10. Modify the LDIF files....................................................................................................................52 4.3.11. Edit the user LDIF file....................................................................................................................52 4.3.12. Create an LDIF file for the "tdomain.com" domain........................................................................52 4.3.13. Import the LDIF files into the database..........................................................................................53 4.3.14. Test the LDAP database.................................................................................................................53 4.4.1. Edit the ldap.conf configuration file.................................................................................................53 4.4.2. Edit the /etc/nsswitch file.................................................................................................................53 4.4.3. Create Home Directories on the LDAP Client..................................................................................54 4.4.4. Check if ldapuser is missing from the /etc/passwd file.....................................................................54 4.4.5. Create the Home Directory for ldapuser on the LDAP Client...........................................................54

4.4. Configuring the LDAP Client......................................................................................................53

4.5. Testing..........................................................................................................................................55 SAMBA...................................................................................................................................................56 1. OVERVIEW..............................................................................................................................................57 2. CONFIGURING SAMBA...............................................................................................................................58 2.1. Setting the NetBIOS parameters..................................................................................................58 2.2. Global printing settings...............................................................................................................58 2.3. Global security settings...............................................................................................................59 2.4. Global name resolution settings..................................................................................................59 2.5. Creating shares............................................................................................................................59 2.6. Share permissions........................................................................................................................60 2.7. Creating shares for home directories..........................................................................................60 2.8. Creating a printer share..............................................................................................................61 3. STARTING AND STOPPING THE SAMBA SERVER...............................................................................................61 4. STEP-BY-STEP CONFIGURATION GUIDE........................................................................................................61 4.1. Samba as Primary Domain Controller .......................................................................................61 4.2. Join Domain.................................................................................................................................63 SQUID CACHE SERVER ...................................................................................................................64 1. AN OVERVIEW.........................................................................................................................................65 2. WHY CACHE?..........................................................................................................................................65 2.1. Origin Server Load......................................................................................................................65 2.2. Quick Abort..................................................................................................................................65

ii

2.3. Peer Congestion...........................................................................................................................65 2.4. Traffic spikes................................................................................................................................66 2.5. Unreachable sites........................................................................................................................66 2.6. Costs............................................................................................................................................66 3. SUPPORTED PROTOCOLS............................................................................................................................66 3.1. Supported Client Protocols..........................................................................................................66 3.2 Inter-cache and Management Protocols......................................................................................66 3.3 Inter-cache Communication Protocols.........................................................................................66 4. SQUID CONFIGURATION.............................................................................................................................67 4.1 The Configuration File.................................................................................................................67 4.2 Setting Squid's HTTP Port............................................................................................................67 4.3 Storing Cached Data....................................................................................................................67 4.4 E-mail for the Cache Administrator.............................................................................................67 5. ACCESS CONTROL LISTS AND ACCESS CONTROL OPERATORS.........................................................................68 5.1 Simple Access Control..................................................................................................................68 6. STEP-BY-STEP CONFIGURATION GUIDE........................................................................................................69 FIREWALLS..........................................................................................................................................71 1. INTRODUCTION.........................................................................................................................................72 2. CONCEPTS...............................................................................................................................................72 3. IPFIREWALL (IPFW) .......................................................................................................................72 3.1. Enabling IPFW............................................................................................................................73 3.3. IPFW Rule Sets............................................................................................................................75 3.4. Building a Rule Script..................................................................................................................78
3.4.1. A Sample Inclusive Rule set.............................................................................................................79 3.4.2. A Sample NAT and Stateful Rule set...............................................................................................82 3.1.1. Kernel Options.................................................................................................................................73 3.1.2. /etc/rc.conf Options..........................................................................................................................74 3.3.1. Rule Syntax......................................................................................................................................75

ASTERISK ............................................................................................................................................87 1. OVERVIEW..............................................................................................................................................88 2. INTRODUCTION.........................................................................................................................................88 2.1. The Components..........................................................................................................................88
2.1.1. The IP PBX......................................................................................................................................88 2.1.2. Phones..............................................................................................................................................89 2.1.3. Network...........................................................................................................................................89

3. INSTALLATION AND CONFIGURATIONS..........................................................................................................89 Change the Linux Password...............................................................................................................91 Change the IP Address .....................................................................................................................91 Set Time Zone ....................................................................................................................................92 4. CONNECT TO AMP FROM A WEB BROWSER................................................................................................93 4.1 Logging into an Asterisk Management Portal (AMP)..................................................................93 4.2. General Settings...........................................................................................................................94 4.3. Extensions....................................................................................................................................95 5. SETTING THE SOFT PHONE..........................................................................................................................96 5.1. Profile Tab...................................................................................................................................97 5.2. Audio and Video Tab...................................................................................................................98 5.3. Network Tab.................................................................................................................................98 5.4. Call-forwarding...........................................................................................................................98 5.5. Flash Operator Panel (FOP).......................................................................................................99

iii

Introduction

This open source toolkit has been developed by the Open Source Resource Center (OSRC), a project of the Ministry of Information Technology (MoIT). This toolkit contains step-by-step manuals related to open source applications for databases, application servers, desktop applications, office productivity suites, Enterprise Resource Planning (ERP) and Customer Relationship Management (CRM) software, and open source desktop applications for the Microsoft Windows platform. A set of CDs, including some Linux distributions and other applications, forms an integral part of this open source toolkit. I would like to thank the OSRC team, including Mr. Abubakar Shoaib, Mr. Iftikhar Ahmad, Mr. Muhammad Hammmad, Mr. Muazzam Ali, Mr. Sher Shah Farooq, and Mr. Qandeel Aslam, who have compiled this toolkit; and Miss Seema Javed Amin, who has edited it. The OSRC would especially wish to thank PSEB’s Director (Projects) Mr. Nasir Khan Afridi, Former Project Manger(OSRC) Mr. Osman Haq and Ministry of Information Technology's Member (IT) Mr. M. Tariq Badsha for their generous moral support, without which this toolkit would never have been completed. This is the first edition of this toolkit, and the OSRC hopes to continue to improve it with the help of your feedback and comments.

Sufyan Kakakhel Open Source Resource Center, Pakistan Software Export Board, 2nd Floor, ETC, Agha Khan Road, F-5, Islamabad, Pakistan. Ph: +92-51-9208748 Fax: +92-51-9204075 Email: skakakhel@pseb.org.pk http://www.osrc.org.pk

Open Source Software Training Toolkit

1

Domain Name System (DNS)

Linux Servers Configuraton

2

A domain name server can be configured using a configuration file, several zone files, and a cache file. The part of a network that the name server is responsible for is known as a zone. A zone is not the same as a domain, in that in a very large domain you can have several zones, each with its own name server. You can also have one name server service several zones, each with its own name server. You can also have one name server service several zones. In this case, each zone will have its own zone file. The zone files hold resource records that provide hostname and IP address associations for computers on the network that the domain name server is responsible for. There are zone files for the server’s network and the local machine. In addition, there is also a cache file that lists the root servers your domain server connects to.

1. named.conf
The configuration file for the named daemon is named.conf, located in the /etc directory. It uses a flexible syntax similar to C programs. The format enables easy configuration of selected zones, enabling features such as access control lists and categorized logging. The named.conf file consists of BIND configuration commands with attached blocks, within which specific options are listed. A configuration command is followed by arguments and a block that is delimited with braces. Within the block are lines of option and feature entries. Each entry is terminated with a semicolon. Comments can use the C, C++ or Shell/Perl Syntax: enclosing /* */, preceding //, or preceding #. The following example shows a zone command followed by the zone name and a block of options that begin with an opening brace, {. Each option entry ends with a semicolon. The entire block ends with a closing brace also followed by a semicolon. // a caching only nameserver config // zone “.” { type hint; file “named.ca”; }; The zone command is used to specify the domains that the name server will service for you. Enter the keyword zone followed by the name of the domain placed within double quotes. Do not place a period at the end of the domain name. There are several types of zones to choose from: master, slave, stub, forward, and hint. The type master specifies that the zone holds master information and is authorized to act on it. The type slave indicates that the zone needs to update its date periodically from a specified master name server. A slave is also known as a secondary server. You can use this entry if your name sever is operating as a secondary server for another primary (master) domain name server. A stub zone only copies other name server entries, instead of the entire zone. A forward zone will direct all queries to a specified name server. A hint zone specifies the set of root name servers used by all Internet domain name servers. You can also specify several options that will override any global options set with the options command. The following example illustrates a simple zone command for the mytrek.com domain. Its class is Internet, IN, and type is master.

2. Step-by-step Configuration Guide
The machine used in this example has been configured and assigned an IP as follows: Hostname Domain name FQDN Routable/Static IP Non-Routable IP ops-isb test.edu.pk ops-isb.test.edu.pk 203.135.44.5 192.168.1.14

Open Source Software Training Toolkit

3

Open the file /etc/named.conf. It must be configured in the manner given below: // generated by named-bootconf.pl options { directory "/var/named"; /* * If there is a firewall between you and nameservers you want * to talk to, you might need to uncomment the query-source * directive below. Previous versions of BIND always asked * questions using port 53, but BIND 8.1 uses an unprivileged * port by default. */ // query-source address * port 53; }; // // a caching only nameserver config // zone “.” IN{ type hint; file db.cache; }; zone “test.edu.pk” IN{ type master ; file “db.test”; }; zone “44.135.203.in-addr.arpa” IN{ }; zone “0.0.127.in.addr.arpa” IN{ type master ; file named.local ; }; Explaining the /etc/named.conf file: options { }; zone “.” { type hint; file db.cache; }; This portion of the file is left to its original state. type master ; file “db.203.135.44”;

Linux Servers Configuraton

4

This block is also left to its original configuration. After this block, you can start the real theme of named.conf i.e. defining your zone. zone “test.edu.pk” { type master ; file “db.test” ; }; The key word zone is written as it is. Write the name of your zone in quotes. This zone name must be the name as your domain name. Now the first line of the block defines the type of this zone i.e. master. The type master means that it is an independent Name Server (NS) i.e., it doesn’t need to be updated from any other NS, and if was to be updated from another NS, then it would have been a type slave. File shows the name of your zone file i.e. db.test, in which you will be configuring your zone. zone “44.135.203.in-addr.arpa” { type master ; file “db.203.135.44” ; }; This file configures the backward mapping i.e. resolves IP to name. zone “0.0.127.in.addr.arpa”{ type master ; file named.local ;

}; NOTE • Don’t forget to put a semicolon (;) after the closing braces of every zone block. • Don’t forget to put the semicolon after each statement of the zone block. • .db in the filename is just a naming naming convention and you can use your own naming convention for this purpose. • All the files mentioned in named.conf must exist in the specified path in the option {} block and must be correctly configured. After configuring the named.conf file, the next step is the zone files’ configuration. Go to the path mentioned in the option {} block of the named.conf file, i.e., /var/named. Begin with the zone file db.test (as mentioned in the third block of named.conf).
1. @ 2. 3. 4. 5. 1 week 6. 7. 8. 9. 10. 11. 12. $ORIGIN 13. xyz 14. ops-isb 15. www 16. abc 17. bakar 18. www.bakar IN SOA ops-isb.test.edu.pk. root.ops-isb.test.edu.pk. ( 1 ; Serial 10800 ; Refresh after 3 hours 3600 ; Retry after 1 hour 604800 ; Expire after 86400 ; Minimum TTL of 1 day ) IN IN test.edu.pk. IN A IN A IN A IN A IN A IN A NS A ops-isb.test.edu.pk. 203.135.44.5 203.135.44.5 203.135.44.5 203.135.44.5 203.135.44.5 203.135.44.5 203.135.44.5

Open Source Software Training Toolkit

5

NOTE


• •

Here ops-isb is the hostname i.e. the name of machine on which the named daemon is running. 203.135.44.5 is the IP address the machine ops-isb (hostname) has been assigned. xyz, abc, bakar and www.bakar are the names of my virtual hosts. For example, the full address of the virtual host, bakar, would be bakar.test.edu.pk. You can add as many virtual hosts as you want. When writing the SOA, write the “hostname.zonename” (zone name is the name that you have declared in the file named.conf). In this example, as in the line one, it is ops-isb.test.edu.pk, where ops-isb is the host name of my machine and test.edu.pk is the zonename. Write the name of the administrator of the zone in the format root.hostname.zonename. In this example, it is root.ops-isb.test.edu.pk. Don’t forget to put dot (.) after “ops-isb.test.edu.pk., root.ops-isb.test.edu.pk. and test.edu.pk.” in line 1, 9 and 12.

The next configuration is the reverse lookup zone i.e. it resolves IP to domain name. The file name used in this example is db.203.135.44
1. @ ( 2. 3. 4. 5. 6. 7. 8. 9. 10. 1.44.135.203.IN-ADDR,ARPA IN SOA ops-isb.test.edu.pk. root.ops-isb.test.edu.pk. 1 10800 3600 604800 86400 ) IN IN NS PTR ; Serial ; Refresh after 3 hours ; Retry after 1 hour ; Expire after 1 week ; Minimum TTL of 1 day

ops-isb.test.edu.pk. ops-isb.test.edu.pk.

named.local:
1. @ ( 2. 3. 4. 5. 6. 7. 8. 9. IN 10. 1.0.0.127.IN-ADDR.ARPA. IN SOA 1 10800 3600 604800 86400 ) NS IN NS ops-isb.test.edu.pk. root.ops-isb.test.edu.pk. ; Serial ; Refresh after 3 hours ; Retry after 1 hour ; Expire after 1 week ; Minimum TTL of 1 day 127.0.01 PTR locahost.

NOTE • Numbers have been assigned to the above configuration files in order to clearly explain each line, otherwise they (numbers i.e. 1, 2, 3…) must not be written, neither in the zone, nor in any configuration files. The next step is the zone file db.cache. Leave the zone db.cache to its default configurations. Open the file /etc/resolv.conf and write the following lines: search test.edu.pk nameserver 203.135.44.5 nameserver 127.0.0.1

Linux Servers Configuraton

6

NOTE

• •

In search, give the domain name of your system nameserver is the IP of the machine in the example, and the loopback address

Starting the Daemon: Start the DNS server by starting its daemon by running the following script: /etc/rc.d/init.d/named start You can start, stop or restart the daemon by putting start, stop, restart at the end of the /etc/rc.d/init.d/named script. Testing the DNS: There are two major ways to ensure that your DNS has been configured correctly: • Ping your domain name or any of your virtual host (s). ping test.edu.pk ping bakar.test.edu.pk If you get the ping reply that means your DNS is functioning correctly.

Use nslookup command. nslookup test.edu.pk If it is functioning correctly, it will give the following message: Server: localhost Address: 127.0.0.1 Name test.edu.pk Address 203.135.44.5

Open Source Software Training Toolkit

7

Apache Web Server

Linux Servers Configuraton

8

1. Introduction to Apache
The World Wide Web (WWW) is the Internet’s most successful application, and its most prominent component is a web server. The web server serves the user’s request by returning the requested web page to the user. Two applications are required in order to process such requests: a web server, and a web client. A protocol known as the Hyper Text Transfer Protocol (HTTP or http) is required for communication between a client and a server, and between a web client and a web server. According to Netcraft’s monthly secure server surveys available at http://news.netcraft.com/, the Apache web server currently has 68.01% of the market share as compared to its competitors, Microsoft at 20.56%, and Sun Microsystems at 2.47%. The Apache HTTP web server is a part of the Apache Software Foundation, which supports other open source projects as well, including Ant, SpamAssasin, Struts, and Tomcat, etc. The current version of the Apache web server, which is being used for the purposes of this tutorial, is version 2.2.0. It can be downloaded from its official website at http://httpd.apache.org/download.cgi.

2. Installation
Apache is usually pre-installed in most Linux distributions. Use the rpm -qa |grep httpd command to confirm whether it is installed or not. If Apache has been installed from the source code, the command mentioned above will not produce any result. In this case, try locating the httpd/apache/apache2 directories. If these directories exist on your system, it means that Apache has already been installed on it. Apache can also be installed manually as well, by downloading either the rpm or the source code. This tutorial will demonstrate both methods.

2.1. Installing from the rpm

1. Download Apache’s latest version from http://httpd.apache.org/download.cgi.
# wget \ http://apache.mirrors.pair.com/httpd/binaries/rpm/i386/http://apache.mirrors.pa ir.com/httpd/binaries/rpm/i386/httpd-2.2.0-1.i386.rpm 2. If you have already installed a previous version of Apache:

• •

From the rpm: Uninstall it, using the command: # rpm -e httpd From the source installation: Install the new rpm on a path that is different from the path of the source installation. Apache’s rpm can be installed by the following command: # rpm -ivh httpd-2.2.0-1.i386.rpm

If you get any dependency errors regarding the Apache Portable Runtime (APR or apr) packages, upgrade it to the version compatible with the current version, httpd2.2.0-1. This is the apr-1.2.2-1, which can be downloaded from http://apr.apache.org/. 3. Verify the installation by running:

Open Source Software Training Toolkit

9

# rpmm -q httpd Browse to the "/etc/httpd" path.

2.2. Installing from the source
A number of options can be used to configure Apache. Customized installation will be discussed in the “References” section. • Download Apache from http://httpd.apache.org/download.cgi # wget http://apache.mirror99.com/httpd/httpd-2.2.0.tar.gz

Create an Apache directory in "/usr/local". This path is optional, and is being used for the purposes of this tutorial only. Unpack the distribution: # tar zxvf httpd-2.2.0.tar.gz -C /usr/local # cd /usr/local/httpd-2.2.0/ # cd apache2

Run configure with the following options: # ./configure --with-layout=Apache --prefix=/usr/local/apache2 \--enablemodule=most--enable-mods-shared=most

Run make to compile the distribution: # make

Install Apache by running the following command: # make install

3. Apache Configuration
If you are using pre-installed Apache that comes with the distribution, then it is probably installed in /etc/httpd. If you have built it from the source, and followed the procedure mentioned in the previous section, then the path is /usr/local/apache2. In order to refer to this default installation path (“/etc/httpd" or "/usr/local/apache2") $APACHE_HOME will be used for the purposes of this tutorial only. Apache runs as a daemon in the background, on which the server handles requests continuously. Port 80 is specified by default in the Apache configuration file, httpd.conf. Running Apache on port 80 requires root privileges, and can be run via the following command: # $APACHE_HOME/bin/apachectl start [If a pre-installed version of Apache is being used, then the bin might not be under the $APACHE_HOME directory] Other useful commands include: # $APACHE_HOME/bin/apachectl stop

Linux Servers Configuraton

10

# $APACHE_HOME/bin/apachectl restart # $APACHE_HOME/bin/apachectl status A start-up script, httpd can also be used to start, stop, or restart the Apache web server: # /etc/init.d/httpd start Apache reads a special file at start-up, httpd.conf, which contains configuration-specific information. This is the main configuration file, and its location can be configured either at the time of compilation, or it can be specified by passing the -f option, $apachectl -f /path/to/config/file. This configuration file is divided into three sections:

• •

Global Environment: This section defines configuration parameters for the Apache server process e.g. the path to the Apache configuration directory; the Apache pid file, and the path to other configuration files, etc. Main Server Configuration: Apache can be configured to host multiple websites on a single host, and each website can be handled by defining a virtual host entry. The main server configuration specifies the default settings for the Apache server which are not handled by virtual hosts. Virtual Host: This section defines settings for virtual hosts that are either IP-based, or name-based.

The configuration file is configured by placing directives. Most directives have a global scope that applies to the entire server, but this can be changed by placing the directives in some special directives, such as <Directory>, <DirectoryMatch>, <Files>, and <Location>, etc.

3.1. Running Apache
In order to test whether the web server configuration file is syntactically correct or not, run the command: # apachectl configtest The output will display "Syntax OK" if everything is correct. The Apache configuration file, httpd.conf, specifies the web server listening port; it is 80 by default. If it is not, change the port to 80, restart the Apache web server, and browse to "http://localhost". If the configuration is correct, the browser will display, "Test Page". Note: In Fedora Core 3, a special package, "SE Linux", can create problems in Apache’s configuration. Ensure that it is disabled before testing the configuration, and then restart Apache.

4. Basics of Apache Configuration
Some common configuration tasks include server-wide configuration, configuration, virtual hosting, logging, access control and authentication. site-specific

4.1. Server-wide configuration
Basic server configuration specifies the following: Server Name: This specifies the server name and the port which is used by the server to identify itself. This is useful for the purposes of redirection e.g. when the machine’s name is

Open Source Software Training Toolkit

11

xyz.osrc.org.pk, but it has the DNS entry for www.osrc.org.pk, and you want to identify the machine as the latter, then the "ServerName" can be used as given below: ServerName www.osrc.org.pk:80 Specify the server name in order to prevent any problem at start-up. This directive can also be used in the virtual host section. Listening Port: This specifies the port number or IP, and the port number on which the web server will listen for incoming requests. If only the port is specified, then the server will listen on the given port number on all IP interfaces, otherwise it will listen to the specified IP and port number only: Listen 80 [Listens on port 80 and all available interfaces] Listen 12.34.56.78:80 [Listens on port 80 and the IP 12.34.54.78 only]

4.2. Site-specific configuration
Document Root: The default web folder for Apache is /var/www/html where you can publish HTML documents. This can be changed by using the DocumentRoot directive. This directive can also be used in the virtual host section: DocumentRoot /var/www/html Directory Index: If the requested URL specifies a directory, this option specifies the resources to look for e.g. http://www.xyz.com/downloads/ where / specifies that "downloads" is a directory. The resources can be, for instance, index.html index.php, etc. It is important to note that the order matters, and that the first available resource will always be returned: DirectoryIndex index.html idnex.php index.txt The above configuration tells Apache to look for the index.html file in the "downloads" directory. If there is no index.html, look for index.php, and then index.txt. If none of these resources can be found, then the behavior depends upon whether the Options directive is set or not with the Indexes options. This directive can also be used in virtual host section. Options Indexes: If this option is set for a directory, and the requested URL maps to a directory e.g. http://www.xyz.com/downloads/, and no DirectoryIndex is set, or the resource specified in the DirectoryIndex cannot be found, then this option will create a default formatted listing for the requested directory: <Directory "/var/www/html"> Options Indexes </Directory> This configuration will set the auto index generation for the directory "html" and its subdirectories. This directive can also be used in the virtual host section.

4.3. Virtual Hosts
Virtual hosting allows running more than one website on a single machine. Apache usually allows running only one website on a single machine. In order to run multiple websites, you can either use multiple Apache daemons, with each daemon handling a specific website, or configure Apache for virtual hosting. Running multiple daemons is an inefficient practice, and should, therefore, be avoided. Virtual hosts can be:

Linux Servers Configuraton

12

4.3.1. IP-Based This allows running multiple websites, each with a different IP, on a single machine. This can be achieved by hosts that have multiple network connections, or by virtual interfaces. A multihomed machine, for example, can have two network cards with IPs 192.168.2.58 and 10.10.10.100. You can configure a website http://www.xyz.com/accounts on 192.168.2.178 and http://www.xyz.com/hr on 10.10.10.100. The following is a sample configuration of IP-based virtual hosts. The hostnames will be resolved to their respective IP addresses. <VirtualHost www.example1.com> DocumentRoot /var/www/html/example1 </VirtualHost> <VirtualHost www.example2.com> DocumentRoot /var/www/html/example2 </VirtualHost> Ensure that the entry NameVirtualHost in the main section is commented out. The above configuration specifies that when a request is made from the client to http://www.example1.com then first resolve the hostname, which returns to 192.168.2.58. This returns the contents in the directory specified by DocumentRoot. A similar operation can be performed by Apache for http://www.example2.com, where the IP address is 10.10.10.100. These hostnames, and their corresponding IP addresses, should be specified in the "/etc/hosts" file in the web server machine, in addition to creating entries in the DNS server. Otherwise, the client will need to specify http://www.example1.com/example1 instead of just www.example1.com. The above-mentioned configuration requires DNS name resolution, which will obviously slow down the entire process. Please refer to http://httpd.apache.org/docs/2.2/dns-caveats.html for more information. The recommended practice is to specify IP address instead of the hostname in the virtual host section. <VirtualHost 192.168.2.58> DocumentRoot /var/www/html/example1 ServerName www.example1.com </VirtualHost> <VirtualHost 10.10.10.100> DocumentRoot /var/www/html/example2 ServerName www.example2.com </VirtualHost> You need an additional directive, ServerName, so that the requests for example1 or example2 can be mapped. If no ServerName is specified, then Apache will try the reverse DNS in order to look up the hostname. 4.3.2. Name-Based Name-based virtual hosts allow multiple websites on a single IP address. This is in contrast to IP-based virtual hosts, where you need an IP address for each website. IP-based virtual hosts rely explicitly on IP addresses to determine the correct virtual host to the server. Name-

Open Source Software Training Toolkit

13

based virtual hosts rely on the client to specify the hostname in the HTTP headers. Namebased virtual hosts are easy to configure, and do not require multiple IP addresses, and can, therefore, work in situations in which you are short of IPs. Prefer name-based virtual hosting over IP-based virtual hosting unless you have very specific reasons for doing otherwise. The following is a sample configuration for name-based virtual hosts: NameVirtualHost 192.168.2.58:80 <VirtualHost 192.168.2.58:80> DocumentRoot /var/www/html/example1 ServerName www.example1.com </VirtualHost> <VirtualHost 192.168.2.58:80> DocumentRoot /var/www/html/example2 ServerName www.example2.com </VirtualHost> The directive NameVirtualHost specifies that IP 192.168.2.58 must listen on this specific IP for incoming requests. Normally, you can use * here, but in cases which require mixed types of settings, i.e. a host that supports both IP-based and name-based virtual hosts, you need to specify which IP address you want to configure for name-based virtual hosting. If you are planning to use multiple ports, such as SSL, for example, then specify the port here. The argument given in NameVirtualHost must match with the virtual host section for name-based virtual hosts: NameVirtualHost * <VirtualHost *> DocumentRoot /var/www/html/example1 ServerName www.example1.com </VirtualHost> <VirtualHost *> DocumentRoot /var/www/html/example2 ServerName www.example2.com </VirtualHost>

4.4. Authentication, Authorization and Access Control
Authentication refers to the verification of the identity of the requesting host and/or user i.e. the user/host is actually who/what they claim to be. Authorization is the process of granting someone access to the areas to which the user is allowed to go. Access control is also authorization, but it provides authorization at another layer i.e. based on an IP address, hostname or the characteristic of the request. Make sure that the requisite modules are installed and loaded in Apache beforehand. Please refer to http://httpd.apache.org/docs/2.2/howto/auth.html and http://httpd.apache.org/docs/2.2/howto/access.html for the list. In order to implement such security mechanisms, you first need to understand the Apache directory’s structure, and its configuration. Apache is normally configured using the main httpd.conf file, where the configuration parameters are applicable to all the published web

Linux Servers Configuraton

14

folders. Sometimes you need to customize configuration based on specific directories, URLs, files, hosts, or locations. You might, for example, want to restrict a particular section of the website to a few users, in which case Apache provides two options: either use <Directory> </Directory> in the main configuration file httpd.conf, or use the .htaccess special file by placing it in that directory. Conceptually, there is no difference in either of the abovementioned methods, as both have the same syntax and applicability. The difference between a directory, a file, and locations is as follows: <Directory /var/www/html/test> Order allow,deny Deny from all </Directory> This means denying access to the directory test and all its sub-directories. So, access to the URL http://www.test.com pointing to the directory /var/www/html/test is denied. Access to the URL http://www.test.com/public pointing to the directory /var/www/html/all is allowed. <File private.html> Order allow,deny Deny from all </File> This means that access to the file private.html located anywhere is denied. <Location /private> Order allow,deny Deny from all </Location> This means that access to any URL containing private is denied. Access to http://www.test.com/private/public is not allowed, whereas access to http://www.test.com/public is allowed. The .htaccess method is easy to configure. Place the contents of the .httaccess file in <Directory> </Directory> in the main configuration file. The name of the .htaccess file can be changed by using the AccessFileName directive in the main configuration file. Configure Apache to allow such configuration files for directories. This can be done by using AllowOverride AuthConfig in <Directory> </Directory>. If you want a special directory, /var/www/html/public/restricted to be restricted, for example, you must allow the use of the .htaccess file. Place the following configuration in Apache’s main configuration file: <Directory /var/www/html/public/restricted> AllowOverride AuthConfig </Directory> Define the users who are granted access to the restricted area. These users, and their passwords, will be defined in a special file, which should be placed somewhere which is inaccessible to the web. The file can be created with a special utility htpasswd that comes with Apache: # htpasswd -c /etc/httpd/conf/passwd user1 New password: Re-type new password: Adding password for user user1

Open Source Software Training Toolkit

15

Create the .htpasswd file in /var/www/html/public/restricted from where the Apache server will read the configuration about the password file and users in order to allow them access to the restricted area: .htaccess ---------------------------------------------AuthType Basic AuthName "Restricted Files" # Optional line: AuthBasicProvider file AuthUserFile /usr/local/apache/passwd/passwords AuthUserFile /etc/httpd/conf/passwd Require user user1 ---------------------------------------------AuthType specifies the type of authentication, and Basic is unencrypted. AuthName specifies the realm which is used as a temporary session identifier. AuthUserFile specifies the path of the password file, and Require user specifies the user to whom access must be granted. Sometimes access needs to be granted to more than one user. This can be achieved by using the Require valid-user, which will allow access to the restricted area to anyone listed in the password file. Please see the “References” section for more advanced techniques regarding configuring authentication/authorization, using groups, and databases. Now consider restricting access based on hostnames, IP addresses, or the characteristic of the request. Please refer to http://httpd.apache.org/docs/2.2/howto/access.html for a list of modules that require installing and loading in this regard. In order to customize access based on hosts/IPs, use Allow and Deny directives. The Order directive can also be used to specify the order in which the filters should be applied. The syntax is: Allow from HOST Deny from HOST Order Allow,Deny Order Deny, Allow Consider the examples given below:

1. 2. 3. 4.

Allow from 192.168.2.100 [Allow from this host only] Allow from 192.168.2.0/24 [Allow from this network 192.168.2 only] Allow from 192.168.2.100 192.168.2.200 [Allow from these hosts only] Allow from my.host.com

Order specifies the order of the filters, which can be: Deny,Allow: First Deny, and then the Allow directive is evaluated. Access is allowed by the default meaning that any client that matches neither the Deny nor the Access directive will be allowed to access the server. Allow,Deny: First Allow, and then the Deny directive is evaluated. Access is denied by the default meaning that any client that matches neither the Allow nor the Deny directive will be allowed to access the server. Consider a real example, a directory /var/www/html/localusers. You want only local users falling in the 192.168.2 network access to /var/www/html/localusers. Use the following configuration:

Linux Servers Configuraton

16

<Directory /var/www/html/localusers> Order Allow,Deny Allow from 192.168.2.0/24 </Directory> Consider the following configuration: <Directory /var/www/html/localusers> Order Allow,Deny Allow from 192.168.2.0/24 Deny from 192.168.2.178 </Directory> This will allow access to all hosts in the network 192.168.2.0/24 except 192.168.2.178. All other requests will be denied by default. Changing the order from Allow,Deny to Deny,Allow will only allow the host 192.168.2.178 to access, since Allow will override the Deny behavior.

4.5 Logging
Apache logs provide comprehensive information and customization for the purposes of security analysis and troubleshooting. Apache logs are located, by default, under the /var/log/httpd directory. There are two basic types of logs: Error Log: This log provides error information while processing requests for diagnostic purposes. The location of this log can be controlled by the ErrorLog directive in the main configuration file. Error logs cannot be customized. Access Log: This log records useful information, such as client IP, date/time, location accessed, client platform information, and so on. An access log can be customized, and its location and content can be controlled by the CustomLog directive.

5. An Example Set-up
Consider a real-world example to configure a static website. The configuration is given below: Routable Server IP Non-routable IP Domain name host name FQDN 203.215.183.11 192.168.2.178 www.testmachine.org osrc-test osrc-test.testmachine.org

The machine’s name is osrc-test, but the DNS alias for this configuration is www.testmachine.org. Steps

• • • •

Open the Apache configuration file httpd.conf Locate DocumentRoot and ensure that it is set to /var/www/html Set ServerName to testmachine.org:80 Put your web-publishing directory directly under /var/www/html. If you have all the data that is to be published under/home/user1/website, type:

Open Source Software Training Toolkit

17

$ mv /home/user1/website/* /var/www/html • Save the Apache configuration file with new changes, exit, and restart the Apache service.

Ensure that valid DNS entries exist for www.testmachine.org that should point to the IP of your machine. Test the website by pointing to www.testmachine.org.

6. Reference • http://httpd.apache.org/docs/2.2/mod/directives.html • http://httpd.apache.org/docs/2.2/configuring.html • http://httpd.apache.org/docs/2.2/sections.html • http://httpd.apache.org/docs/2.2/logs.html • http://httpd.apache.org/docs/2.2/howto/auth.html • http://httpd.apache.org/docs/2.2/vhosts/

Linux Servers Configuraton

18

Mail Server

Open Source Software Training Toolkit

19

1. How Electronic Mail Works
Let us begin by explaining the flow of information that typically takes place when two people want to communicate through Electronic Mail (e-mail). Let us suppose that Fraz, on his machine wonderland.com, wants to send mail to Omer, on his machine dobbs.com. Both machines are connected to the Internet. An Internet mail message consists of two parts: mail headers and a mail body, separated by a blank line. The mail headers contain the source and destination of the mail, a user-supplied subject line, the date it was sent, and various other kinds of useful information. The body is the actual content of the message. The following is an example: From: "Fraz" <fraz@wonderland.com> Message-Id: <200211131704.MAA18447@wonderland.com> Subject: Have you seen my white rabbit? To: omer@dobbs.com (Omer) Date: Thu, 13 Nov 2002 12:04:05 -0500 (EST) Content-Type: text I'm most concerned. I fear he may have fallen down a hole. ->>fraz>> The arrangement and meaning of Internet mail headers are defined by an Internet standard in RFC822.

1.1 Mail between full-time Internet machines
To send mail, Fraz will invoke a program called a Mail User Agent (MUA). The MUA is what users think of as 'the mailer'; it helps them compose the message, usually by calling out to a text editor of their choice. When Fraz hits the MUA 'Send' button, his part in the process is complete. The MUA he uses immediately hands his message over to a program known as a Mail Transport Agent (MTA). Usually this program will be sendmail, although some alternative MTAs are gaining popularity, and may appear in future Linux distributions. The MTA's job is to pass the mail to an MTA on Omer's machine. It determines Omer's machine by analyzing the ‘To’ header and by seeing the dobbs.com on the right-hand side of Omer's address. It uses that address to open an Internet connection to Omer's machine. The mechanics of making that connection is a separate topic. For the purposes of this tutorial, it is enough to know that that connection is a way for Fraz's MTA to send text commands to Omer's machine, and receive replies to those commands. The MTA's commands do not go to a shell. Instead, they go to a service port on Fraz's machine. A service port is a sort of rendezvous point, a known place where Internet service programs “listen” for incoming requests. Service ports are numbered, and Fraz's MTA knows that it needs to “talk” to port 25 on Omer's machine in order to pass on the mail.

Linux Servers Configuraton

20

+---------+ +-------+ +-------+ +-------+ types | sending | calls |sending| |fraz |--------->| MUA |--------->| MTA |::::>:::: +-------+ | | | | :: on the +---------+ +-------+ :: sending :: machine ....................................................................... SMTP :: ::::::::::::::::::::::::::::<:::::::::::::::::::::::::::: :: :: +---------+ +-----+ +-------+ :: |receiving| calls | | delivers to | omer's| ::::>| MTA |--------->| LDA |===============>|mailbox| on the | | | | | | receiving +---------+ +-----+ +-------+ machine | | | | +----------------<-------------+ | | | +---------+ +-------+ | | omer’ s | | omer's|<----------+ | notifier| | MUA | +---------+ +-------+ | | | +-----+ | +----->| omer|<----+ +-----+

On port 25, Omer's machine has its own MTA listening for commands. Fraz's MTA will go through a dialogue with Omer's, using Simple Mail Transfer Protocol (SMTP). This is what an SMTP dialogue looks like. Lines sent by Fraz's machine are identified by an “S”; responses from Omer's machine are identified by an “R”: S: MAIL FROM:<fraz@wonderland.com> R: 250 OK S: RCPT TO:<omer@dobbs.com> R: 250 OK S: DATA R: 354 Start mail input; end with <CRLF>.<CRLF> S: From: "Fraz" <fraz@wonderland.com> S: Message-Id: <200211131704.MAA18447@wonderland.com> S: Subject: Have you seen my white rabbit? S: To: omer@dobbs.com (Omer) S: Date: Thu, 13 Nov 2002 12:04:05 -0500 (EST) S: Content-Type: text S: S: I'm most concerned. I fear he may have fallen down a hole. S: -S: >>Fraz>> S: . R: 250 OK Usually, an SMTP command is a single text line, and so is its response. The DATA command is an exception; after seeing that, the SMTP listener accepts message lines until it sees a period on a line by itself. (SMTP is defined by the Internet standard RFC821.) Now Omer's MTA has Fraz's message. It will add a header to the message that looks something like this: Received: (from fraz@wonderland.com) by mail.dobbs.com (8.8.5/8.8.5) id MAA18447 for omer@dobbs.com; Thu, 13 Nov 2002 12:04:05 –0500 This is for tracking purposes in case of mail errors (sometimes a message has to be relayed through more than one machine, and it will have several of these). dobb's MTA will pass the modified message to a Local Delivery Agent (LDA). On Linux systems, the LDA is usually a program called procmail, although others exist. The LDA's job is to append the message to Omer's mailbox. It is separate from the MTA so that both programs can be simpler, and then

Open Source Software Training Toolkit

21

the MTA can concentrate on performing Internet-related activities without worrying about local details, such as where the users’ mailboxes live, for example. Omer's mailbox will normally be a file called /usr/spool/mail/omer or /var/mail/omer. When he reads his mail, he runs his own MUA to look at, and edit, that file.

2. Notifiers
There is yet another kind of program that is important in the mail chain, although it does not itself read or transmit mail. It is a mail notifier, a program that watches your e-mail Inbox for activity, and alerts you to new mail when it arrives. The original notifiers were a pair of UNIX programs called biff(1) and comsat(8). The biff program is a front-end that enables you to turn on the comsat service. When this service is on, the header of new mail will be dumped onto your terminal as it arrives. This facility was designed for people using line-oriented programs on CRTs; it is not really a good idea in today's environment. Most UNIX shells have built-in mail check facilities that allow them to function as notifiers in a rather less intrusive way (by emitting a message just before the prompt when new mail is detected). Enable this facility by setting environment variables documented on the shell's manual page. Systems supporting X come with one of several little desktop gadgets that check for new mail periodically, and give you both visible and audible indications of new mail. The oldest and most widely used of these is called xbiff; if your Linux has a pre-configured X desktop setup, xbiff is probably on it. See the xbiff(1) manual page for details.

3. Mailbox formats
When incoming mail gets appended to a mailbox, it is up to the MTA to provide some kind of delimiters that indicate where one message stops, and the next one begins. Under UNIX, the convention almost all mailers use is that each line beginning with “From” (the space is significant) begins a new message. If “From” occurs at the beginning of a line in text, a UNIX MTA will generally prefix it with a greater-than sign, so it looks like “>From”. RFC822 headers follow this “From line” (which usually continues with the sender name and receipt date). This convention originated with UNIX Version 7, so this kind of mailbox is referred to as a “V7 mailbox”; it is also sometimes called an “mbox format”. It is not, however, quite universal, and tools expecting and generating different formats can confuse each other badly. The four other formats are BABYL, MMDF, MH, and qmail maildir. Of these, MMDF is the simplest; it uses a delimiter line consisting four control-As (ASCII 001) characters followed by CR-LF. MMDF was an early and a rather crude Internet mail transport; a descendant is still in use on SCO systems. BABYL is another survivor from an early mail system at MIT. It is still used by Emacs's mail-reader mode. MH and qmail maildir are 'mailbox' formats that actually burst each mailbox into a directory of files, one per message. Running grep on such a 'mailbox' is useless, since all grep will see are the directory bits. Microsoft Outlook Express .mbx mailboxes can be converted to RFC822 format with mbx2mbox app.

4. Choosing a Mail Transport Agent (MTA)
Mail Transport Agents (MTAs) are the software that transfers mail from your local system to remote systems. It is very seldom necessary to replace your MTA on modern Linux. Nevertheless, the following comparison survey will help you to understand what the benefits are if you decide you need more security or performance than your system's default can offer. (There are other UNIX MTAs besides these, but you are quite unlikely to encounter them in a Linux box.) Each has its own unique features, but the best compromise is qmail. It features high security (even if vmail is more secure), high speed (even if smail is faster for local use) and ease of configuration. Feel free to choose any mail software. The information provided here is intended to help you make an informed decision. Sendmail is suitable for many sites with complicated options, but its configuration is too hard for beginners. It is not very secure or very fast, so the following is really an outdated section

Linux Servers Configuraton

22

regarding sendmail. If you know what you are doing, choose sendmail; otherwise qmail is generally recommended.

4.1 Sendmail
BSD sendmail is the oldest of Internet MTAs. It has outlasted a few would-be successors. Most Linux distributions now use it and have it pre-installed. Sendmail has a long-standing reputation for being an administrator's nightmare - hard to understand, tricky to configure, rife with security holes. As Internet technology and standards have stabilized, however, many of sendmail’s options and configurable rules that gave rise to this reputation have ceased to require per-site tweaking (the demise of non-TCP/IP network layers like UUCP has helped a lot). Also, recent sendmail versions have an improved configuration system. Most importantly, Sendmail now normally comes pre-configured, and you should never need to touch it unless you have unusual requirements (such as needing to route mail over a non-TCP/IP network). Visit Sendmail’s official website at http://www.sendmail.org/. It includes references to extensive documentation regarding sendmail, should you actually need to custom-configure it.

4.2 smail v3.2
smail was the first serious attempt to replace sendmail. It has a simpler and much more comprehensible configuration system than sendmail's, and is fairly secure. Some Linux distributions pre-install smail rather than sendmail. At one time, smail's excellent support for mixed TCP/IP and UUCP sites was its major selling-point, but as UUCP has declined, so has smail. It is also less efficient than sendmail on high-volume connections. As with sendmail, it is unlikely that you will need to tweak a pre-installed smail configuration.

4.3 qmail
qmail is a secure, reliable and robust MTA. It is a popular choice as a replacement for sendmail. While sendmail is older than qmail, security was not considered a major issue during its designing and development stages. Although its code has been repeatedly modified to make it more secure, the whole design architecture of sendmail has to be replaced with a new one. qmail, on the other hand, was designed with high security as a goal. qmail is much more robust in terms of performance, and is reliable because of its internal architecture, to deliver mails. This is possible because of its clean and simple modular approach.

5. Local Delivery Agents (LDAs)
Unlike most operating systems, Linux did not have "built-in” mail: one needed a program to deliver the local mail, like "lmail", "procmail" or "deliver". Every recent distribution, however, now includes a local mailer sendmail.

6. User Agent Administration
6.1 Mutt
You should have no problem compiling, installing, or running Mutt. Users of qmail can either get the patch, or run it with -f flag to read their local mail folder. If mutt sends an "unknown terminal error" after a distribution upgrading, recompile it.

6.2 Elm
Elm compiles, installs and runs flawlessly under Linux. For more information, see its sources and installation instructions. Elm and its filter need to be in mode 2755 (group mail) with /var/spool/mail mode 775 and group mail. Qmail users can get a patch to use interesting qmail features, or run Elm with the -f flag to point to their local mail folder. If you have Elm compiled to be MIME-able, you need Metamail installed and in the standard path, or Elm will not be able to read the MIME mail that you have received. Metamail is available at thumper.bellcore.com and via "archie". If you use a binary distribution, you'll need to create a "/usr/local/lib/elm/elm.rc" file to override the compiled-in hostname and domain information:

Open Source Software Training Toolkit

23

replace "subdomain.domain" with your domain name replace "myhostname" with you un-domainized hostname replace #---------- /usr/local/lib/elm/elm.rc -----------------# # this is the unqualified hostname hostname = myhostname # # this is the local domain hostdomain = subdomain.domain # # this is the fully qualified hostname hostfullname = myhostname.subdomain.domain # #-------------------------------------------------------A distribution of Elm-2.4.24 is available that is "PGP-aware". In order to try it, obtain the file ftp://ftp.viewlogic.com/pub/elm-2.4pl24pgp3.tar.gz, which is elm2.4.24 with PGP hooks added. Configure and build it in the same way as normal Elm by adding the patches mentioned above. More recent versions include elm-ME+. While this item is not Linux-specific, it is, nevertheless, wrongly perceived to be a nagging Elm bug. Elm sometimes fails with a message that it is unable to malloc() massive numbers of bytes. The identified workaround is to remove the post-processed global mail aliases (aliases.dir and aliases.pag). This is not a bug in ELM; it is a configuration error. Elm has an enhanced and non-compatible format for aliases; ensure that the path Elm uses for aliases is different from the path that sendmail/smail uses. From the volume of reports regarding this problem, it is apparent that at least one major distribution has been misconfigured in the past. {From Scot at catzen.gun.de (Scot W. Stevenson)}. The current metamail package requires csh for some of its scripts. Failure to install csh (or tcsh) will cause errors.

6.3 Mailx
If you do not have a local mailx program, obtain a mailx kit from Slackware 2.1.0 or later, which contains an implementation of mailx 5.5. If you build from sources, mailx v5.5 compiles without patching under Linux if you have "pmake" installed. Remove the old "edmail" from SLS1.00 and replace it with mailx.

7. Sendmail - Step-by-step Configuration
As we are configuring a mail server that can send and receive mails from any domain, this means that we shall be using SMTP and POP3 as well. We are using sendmail as the MTA and qpopper as the POP3 server.

7.1. MTA (sendmail)
Begin by configuring Sendmail’s configuration file by the name of sendmail.cf. This file can found in the directory /etc/ Move to the directory /etc: cd /etc Open the configuration file: vi sendmail.cf The file will contain lines similar to the following: # override file safeties - setting this option compromises system security # need to set this now for the sake of class files #O DontBlameSendmail=safe ##################

Linux Servers Configuraton

24

# local info # ################## Cwlocalhost # file containing names of hosts for which we receive email Fw/etc/sendmail.cw Look for the line Cwlocalhost. At the end of this line, append the domain name for which you want to receive mails. Before any changes, the line will look like the following: Cwlocalhost In order to receive mails for the domain test.edu.pk, append the domain name after the mentioned line, and it will look like this: Cwlocalhost test.edu.pk In order to receive mails for other domains as well, like testing.com and flipflop.org, append these domain names after the previous one, and separate each domain name with a space. The line will look like: Cwlocalhost test.edu.pk testing.com flipflop.org Add as many domain names as necessary. Save the file and exit. Go to the directory /etc/mail/. Create a file named relay-domains and configure an alreadyexisting file access. relay-domains: This file will contain the hosts that will allow relaying. Open this file with the command: pico relay-domains Write the following lines in the file: ALLOW ALLOW ALLOW ALLOW

ALLOW test.edu.pk .test.edu.pk Save and exit.

Note: 210.56.18.203 is the real IP that has been assigned to the author’s machine against the domain name test.edu.pk. This will be different in each machine’s case. 192.168.1 is the local IP of the author’s machine. test.edu.pk is the domain name. Access: Open the file named access in the same directory i.e. /etc/mail and write the following lines in it: ops-isb.test.edu.pk 210.56.18 1. RELAY 192.168.1 RELAY RELAY RELAY

Note: Where ops-isb is the machine or the hostname on which the domain exists.

Open Source Software Training Toolkit

25

7.2. POP3
To configure the POP3 server, download qpopper from: ftp://ftp.qualcomm.com/eudora/servers/unix/popper/qpopper3.1.tar.gz Download it in the directory /usr/. Untar the qpopper3.1.tar.gz file with the command: tar zvxf qpopper3.1.tar.gz This will create directory /usr/qpopper3.1. Move into the directory: cd /usr/qpopper3.1 Type the following commands in a sequence: ./configure make ./configure --enable-specialauth make Go to the directory /etc/xinetd/. Create a file called pop3: pico pop3 Type the following in it: service pop3 { socket_type protocol wait user server server_args port }

= stream = tcp = no = root = /usr/qpopper3.1/popper/popper = qpopper –s = 110

Save the file and exit. Run the following commands to start the services:

7.3. Starting and Testing the Mail Server
/etc/rc.d/init.d/sendmail start /etc/rc.d/init.d/xinetd restart Telnet the localhost to check whether the pop3 is working properly or not: telnet localhost 110 You will see a response which will confirm that the qpopper is functioning smoothly. You can now make users on Linux, and assign them their e-mail addresses. If you have a user called bakar, for example, then his e-mail address will be bakar@test.edu.pk (test.edu.pk is the domain name).

8. Qmail - Step-by-step Configuration
qmail can be installed in a variety of ways. There are different How-To's on the Internet that briefly explain how to install and configure qmail. This guide is based on one of the How-Tos, qmailrocks, which describes qmail’s setup stepby-step, in addition to installing qmail add-ons. These additional packages include ezmlm, Autoresponder, Vpopmail, Vqadmin, maildrop, QmailAdmin, Courier-imap/imaps, Squirrel mail, Clam AV, and SpamAssasin. A brief introduction to all these packages is given below:

Linux Servers Configuraton

26

ezmlm ezmlm is a mailing list manager for qmail. It allows the users to setup their own mailing lists easily. Visit http://cr.yp.to/ezmlm.html Autoresponder A useful utility which automatically responds to e-mails. Vpopmail Vpopmail is a useful program that facilitates the creation and management of multiple virtual domains on a qmail server. Vqadmin Vqadmin is a web-based interface to manage Vpopmail at the root level. Maildrop Maildrop provides a mail-filtering service that can be used to filter incoming messages on the server. qmailAdmin qmailAdmin is a useful tool that allows users to administer their own domains, but cannot create new domains (Vqadmin can be used for this purpose). Courier-imap, Courier-authlib, Courierpassd Courier-imap is an IMAP server that allows IMAP connections to the server, and is required to install SquirrelMail. Courier-authlib provides authentication through courier-imap. Courierpassd allows the users to change their password using SquirrelMail. SquirrelMail SquirrelMail is a webclient for qmail with IMAP, which provides a web-based client interface on the server. Clam AV and SpamAssassin This is an antivirus and spam control program that can be integrated with qmail.

8.1. Pre-requisites/Pre-installation steps
8.1.1. Required software/packages 1. Apache, either 1.x or 2.x, should be installed 2. PHP, version 4.0.6 or higher, with IMAP and MySQL support. MySQL support may or may not be required, depending on the number of domains being hosted. 3. Perl, version 5.x. The following packages should be installed: 1 2 3 4 5 6 Digest::SHA1 Digest::HMAC Net::DNS Time::HiRes HTML::Tagset HTML::Parser

4. GCC 5. MySQL, version 3.x or higher, is only required if it is integrated with vpopmail. 6. OpenSSL, version 0.9.5a or higher 7. OpenSSL-devel 8. patch and patchutils To check whether Apache is installed on your machine, run: # rpm -qa | grep httpd

Open Source Software Training Toolkit

27

Note: For Fedora Core 3 users, disable SeLinux before proceeding any further. 8.1.2. Software/packages that should not be installed 1. Postfix 2. Any POP service 3. Any SMTP service. Leave Sendmail installed for the moment; it will be uninstalled later on in the tutorial Make sure that the following ports are not blocked in the firewall: Outbound Ports (TCP) 25 - SMTP 110 - POP services 143 - IMAP 783 - SpamAssassin 993 – IMAPS Inbound Ports (TCP) 25 - SMTP 80 - HTTP 110 - POP services 143 - IMAP 443 - HTTPS 783 - SpamAssassin 993 - IMAPS

8.2 qmail Installation and Configuration
8.2.1. Download qmail qmailrocks comes with a complete package to install and setup qmail. It also includes automated scripts to perform some functionalities e.g. creating users, directories etc. Follow the exact steps e.g. directory names, paths etc. because the scripts bundled with qmailrocks have all the paths hard-coded. All the installation must be done as root user, unless otherwise stated. # mkdir /downloads # cd /downloads Download the qmailrocks package in this directory: # wget http://www.qmailrocks.org/downloads/qmailrocks.tar.gz The above-mentioned package contains everything required for this tutorial. In order to download individual packages, visit http://downloads.qmailrocks.org/. An alternative mirror can be selected http://www.qmailrocks.org/mirror_list.htm. Unpack the packages in the “Downloads” directory: # tar zxvf qmailrocks.tar.gz 8.2.2. Installing qmail This step will demonstrate qmail installation along with ucspi-tcp and daemon tools, which form the core components of a qmail server. You will also need to create some directories, users and set permissions. qmailrocks has combined all these steps in a single script, available at to speed up downloading at

Linux Servers Configuraton

28

“/downloads/qmailrocks/scripts/install/qmr_install_linux-s1.script” Run this script in “/downloads”: # /downloads/qmailrocks/scripts/install/qmr_install_linux-s1.script You should see “All steps completed!” in the end. Apply patches to qmail in order to enhance its functionality. qmailrocks comes up with another script to apply them. Details regarding these patches can be found at the qmailrocks website. Run the following script in “/downloads”: # /downloads/qmailrocks/scripts/util/qmail_big_patches.script You should see “All done!” in the end. Install qmail, ucspi-tcp and daemon tools. Run the following steps in “/downloads”: # cd /usr/src/qmail/qmail-1.03 # make man # make setup check # ./config The config script will try to perform a reverse DNS against all local IP addresses. If the DNS server on your network is working correctly, this should run smoothly. In case the DNS server is not configured or setup, use config-fast: # ./config-fast your_fqdn_hostname [your_fqdn_hostname is your full host name ex: ./config-fast mail.osrc.org.pk where mail is the hostname and osrc.org.pk is the domain name] qmail is now installed. Generate a certificate to communicate over TLS with the server. Run the following command: # make cert This will ask some questions, you can fill in any value. The following is a sample: Country Name (2 letter code) [GB]:PK State or Province Name (full name) [Berkshire]:Capital Locality Name (eg, city) [Newbury]:Islamabad Organization Name (eg, company) [My Company Ltd]:osrc.org.pk Organizational Unit Name (eg, section) []:mail Common Name (eg, your name or your server's hostname) []:mail.osrc.org.pk Email Address []:postmaster@osrc.org.pk This will install the certificate at “/var/qmail/control/servercert.pem” along with a symbolic link to that certificate at “/var/qmail/control/clientcert.pem”. Set the right ownership for the certificate: # chown -R vpopmail:qmail /var/qmail/control/clientcert.pem \ /var/qmail/control/servercert.pem Compile and setup ucspi-tcp and daemon tools: # cd /usr/src/qmail/ucspi-tcp-0.88/ # patch < /downloads/qmailrocks/patches/ucspi-tcp-0.88.errno.patch # make # make setup check Install the daemon tools:

Open Source Software Training Toolkit

29

# cd /package/admin/daemontools-0.76/src # patch < /downloads/qmailrocks/patches/daemontools-0.76.errno.patch # cd /package/admin/daemontools-0.76 # package/install You should be able to see svscanboot running at this moment. Run the following command to confirm it: # ps -aux | grep svscanboot qmail is now installed. Now install some useful qmail add-ons.

8.3. qmail additional tools and utilities
8.3.1. ezmlm # cd /downloads/qmailrocks/ # tar zxvf ezmlm-0.53-idx-0.41.tar.gz # cd ezmlm-0.53-idx-0.41 # make # make setup 8.3.2. Autoresponder # cd /downloads/qmailrocks # tar zxvf autorespond-2.0.5.tar.gz # cd autorespond-2.0.5 # make # make install 8.3.3. Vpopmail Vpopmail can be installed with or without MySQL support. This guide will demonstrate setting up Vpopmail without MySQL support, since MySQL integration will complicate matters, and is required only when hosting a large number of domains. # cd /downloads/qmailrocks # tar zxvf vpopmail-5.4.9.tar.gz # cd vpopmail-5.4.9 # ./configure –enable-logging=p # make # make install-strip Vpopmail is now installed. 8.3.4. Vqadmin # cd /downloads/qmailrocks # tar zxvf vqadmin-2.3.6.tar.gz # cd vqadmin-2.3.6 We need to know the location of the cgi-bin and web server publishing directory. On most systems, it is “/var/www/cgi-bin” and “/var/www/html”. # ./configure –enable-cgibindir=/var/www/cgi-bin \ --enable-htmldir=/var/www/html/ # make # make install-strip

Linux Servers Configuraton

30

This should install Vqadmin in “/var/www/cgi-bin”. In order to configure Apache i.e. httpd.conf, add the following configuration lines: <Directory "/var/www/cgi-bin/vqadmin/"> deny from all Options ExecCGI AllowOverride AuthConfig Order deny,allow </Directory> # cd /var/www/cgi-bin/vqadmin # chown apache .htaccess # chmod 644 .htaccess Configure the vqadmin directory to restrict access to the Vqadmin interface to authorized users only. Edit the “.httaccess” file: AuthType Basic AuthUserFile /path/to/where/you/want/to/store/the/password/file/vqadmin.passwd AuthName vQadmin require valid-user satisfy any The recommended path to store “vqadmin.passwd” is “/etc/httpd/conf/passwds”; storing it at any other location does not make any difference. Create the “/etc/httpd/conf/passwds” directory. The “/path/to/where/you/want/to/store/the/password/file/.htpasswd” should now read as “/etc/httpd/conf/passwds/vqadmin.passwd” Create the “vqadmin.passwd” file. [Make sure that the password file name is the same as has been specified in the “.htaccess” file] # htpasswd -bc /etc/httpd/conf/passwds/vqadmin.htpasswd admin \ YOUR_PASSWORD_HERE # chmod 644 /etc/httpd/conf/passwds/vqadmin.passwd Browse to http://www.yourdomain.com/cgi-bin/vqadmin/vqadmin.cgi to check the configuration. If all goes well, you should be prompted with a login password, and to enter the credentials created earlier. You will see the Vqadmin configuration page. Create a test domain. This will prompt you for a new domain name and a postmaster password. The user postmaster user will be used later in Qmailadmin. 8.3.5. Maildrop # cd /downloads/qmailrocks # tar zxvf maildrop-1.6.3.tar.gz # cd maildrop-1.6.3 # ./configure --prefix=/usr/local --exec-prefix=/usr/local \ --enable-maildrop-uid=root --enable-maildrop-gid=vchkpw –enable-maildirquota # make # make install-strip # make install-man Maildrop should be installed now. 8.3.6. Qmailadmin # cd /downloads/qmailrocks # tar zxvf qmailadmin-1.2.3.tar.gz # cd qmailadmin-1.2.3

Open Source Software Training Toolkit

31

# ./configure --enable-cgibindir=/path/to/your/cgi-bin --enablehtmldir=/path/to/your/html/directory The path to your cgi-bin is “/var/www/cgi-bin”, and the path to your HTML directory is “/var/www/html”. # make # make install-strip Browse to http://www.yourdomain.com/cgi-bin/qmailadmin and enter the domain and the password created earlier using Vqadmin.

8.4. qmail Configuration
Create system scripts for qmail. qmailrocks has already automated the process of creating scripts and setting up the permissions in a script. Run the script: # /downloads/qmailrocks/scripts/finalize/linux/finalize_linux.script If the instructions have been followed until now, the script should not return any error. Edit “/var/qmail/supervise/qmail-pop3d/run” and “/var/qmail/supervise/qmail-smtpd/run”. Find “mail.example.com” and replace it with your server's hostname e.g. mail.osrc.org.pk. Prevent any qmail process from running: # qmailctl stop # echo '127.:allow,RELAYCLIENT=""' >> /etc/tcp.smtp # qmailctl cdb Create common system aliases to redirect bounced mails to a specific address: # echo postmaster@osrc.org.pk > /var/qmail/alias/.qmail-root # echo postmaster@osrc.org.pk > /var/qmail/alias/.qmail-postmaster # echo postmaster@osrc.org.pk > /var/qmail/alias/.qmail-mailer-daemon Any address can be used instead of postmaster@osrc.org.pk # ln -s /var/qmail/alias/.qmail-root /var/qmail/alias/.qmail-anonymous # chmod 644 /var/qmail/alias/.qmail* Before using qmail, uninstall sendmail. On Red Hat systems, sendmail is usually installed as an “rpm”. # rpm -qa | grep sendmail This should indicate whether any sendmail packages have been installed or not. Uninstall using the following commands, but first stop any sendmail processes that might be running: # /etc/rc.d/init.d/sendmail stop # rpm -e --nodeps SENDMAIL_PACKAGE Create a dummy sendmail symbolic link: # ln -s /var/qmail/bin/sendmail /usr/lib/sendmail # ln -s /var/qmail/bin/sendmail /usr/sbin/sendmail qmail is configured and is now ready for use. qmailrocks presents a script that can be used to test the installation and configuration process performed until now: # /downloads/qmailrocks/scripts/util/qmr_inst_check “Congratulations” indicates that the procedure has been successful so far.

Linux Servers Configuraton

32

8.5. Testing qmail Installation and Configuration
The following methods are used to test qmail’s installation and configuration: # qmailctl stop # qmailctl start The qmail status can be checked by running: # qmailctl stat You should see the following: /service/qmail-send: up (pid 19868) 3 seconds /service/qmail-send/log: up (pid 19873) 3 seconds /service/qmail-smtpd: up (pid 19876) 3 seconds /service/qmail-smtpd/log: up (pid 19878) 3 seconds /service/qmail-pop3d: up (pid 19881) 3 seconds /service/qmail-pop3d/log: up (pid 19882) 3 seconds messages in queue: 0 messages in queue but not yet preprocessed: 0 Test the POP service: # telnet localhost 110 You should see the following: Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'. +OK <19917.1138776306@mail.osrc.org.pk> user postmaster@osrc.org.pk +OK pass 123 +OK quit +OK Connection closed by foreign host. The italicized letters display the input to be entered. The above output shows that the POP service is running successfully. Send a mail to postmaster@osrc.org.pk. Ensure that the DNS is properly configured; otherwise you will receive a delivery failure message. Connect again to post 110 using the same credentials entered above: Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'. +OK <21886.1138852777@mail.osrc.org.pk> user postmaster@osrc.org.pk +OK pass 123 +OK list +OK 1 859 . quit +OK Connection closed by foreign host.

Open Source Software Training Toolkit

33

The italicized letters display the input to be entered. The number displayed after entering the command list indicates the number of messages in the user mailbox. Test the SMTP service: # telnet localhost 25 Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'. 220 mail.osrc.org.pk ESMTP ehlo localhost 250-mail.osrc.org.pk 250-AUTH LOGIN CRAM-MD5 PLAIN 250-AUTH=LOGIN CRAM-MD5 PLAIN 250-STARTTLS 250-PIPELINING 250 8BITMIME starttls 220 ready for tls quit quit Connection closed by foreign host. If you get the “220 ready for tls” message after entering the command starttls, it means that the SMTP connection is good enough to go onto TLS encryption. If you receive an error message, ensure that you have created certificates first. At this point, qmail is setup and can be used. Functionalities, however, are still required in order to remotely check mails, scan for viruses and spam. The next few sections will guide you towards installing and setting them up.

8.6. Courier-imap/imaps and Courierpassd
# cd /downloads/qmailrocks/ # tar jxvf courier-authlib-0.55.tar.bz2 # cd courier-authlib-0.55 # ./configure --prefix=/usr/local --exec-prefix=/usr/local \ --with-authvchkpw --without-authldap --without-authmysql \ --disable-root-check --with-ssl \ --with-authchangepwdir=/usr/local/libexec/authlib –with-redhat # make # make check # make install-strip # make install-configure Edit the “/etc/rc.local” file to start authdemon automatically on boot: # vi /etc/rc.local Add the following line /usr/local/sbin/authdaemond start Install courier-imap, which has to be compiled by a non-root user. Create a temporary user on the system: # useradd tempuser # cd /downloads/qmailrocks/

Linux Servers Configuraton

34

# tar jxvf courier-imap-4.0.2.tar.bz2 # chown -R tempuser:wheel courier-imap-4.0.2 # cd /downloads/qmailrocks/courier-imap-4.0.2 Switch to a non-root user: # su tempuser $ ./configure --prefix=/usr/local --exec-prefix=/usr/local --with-authvchkpw --without-authldap --without-authmysql --disable-root-check --with-ssl --withauthchangepwdir=/usr/local/libexec/authlib --with-redhat $ make $ make check Swtich back to a root user: $ exit # make install-strip # make install-configure Create an SSL certificate: # /usr/local/sbin/mkimapdcert Edit some files to change some values: # vi /usr/local/etc/imapd.cnf Change postmaster@example to postmaster@osrc.org.pk # vi /usr/local/etc/imapd Change IMAPDSTART=NO to IMAPDSTART=YES # vi /usr/local/etc/imapd-ssl Change IMAPDSTART=NO to IMAPDSTART=YES and make sure TLS_CERTFILE=/usr/local/share/imapd.pem # vi /usr/local/etc/authlib/authdaemonrc “authmodulelist” should contain only authvchkpw i.e. authmodulelist="authvchkpw” Create the start-up scripts: # cp /usr/local/libexec/imapd.rc /etc/rc.d/init.d/imap # cp /usr/local/libexec/imapd-ssl.rc /etc/rc.d/init.d/imaps Start authdaemon, the IMAP and IMAPS server: # /usr/local/sbin/authdaemond stop # /usr/local/sbin/authdaemond start # /etc/rc.d/init.d/imap stop # /etc/rc.d/init.d/imaps stop # /etc/rc.d/init.d/imap start # /etc/rc.d/init.d/imaps start The system should be listening on port 143 and 993. Use the nmap command to check it: # namp localhost

Open Source Software Training Toolkit

35

Starting nmap 3.70 ( http://www.insecure.org/nmap/ ) at 2006-02-02 09:49 PKT Interesting ports on localhost.localdomain (127.0.0.1): (The 1650 ports scanned but not shown below are in state: closed) PORT STATE SERVICE 22/tcp open ssh 25/tcp open smtp 80/tcp open http 110/tcp open pop3 111/tcp open rpcbind 113/tcp open auth 143/tcp open imap 443/tcp open https 631/tcp open ipp 993/tcp open imaps Nmap run completed -- 1 IP address (1 host up) scanned in 0.227 seconds Test the server using Telnet: # telnet localhost 143 Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'. * OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION STARTTLS] Courier-IMAP ready. Copyright 1998-2005 Double Precision, Inc. See COPYING for distribution information. a login postmaster@osrc.org.pk 123 a OK LOGIN Ok. a logout * BYE Courier-IMAP server shutting down a OK LOGOUT completed Connection closed by foreign host. The italicized letters display the input. The output shows a successful connection to the server. Install courierpassd: # cd /downloads/qmailrocks # tar zxvf courierpassd-1.1.0-RC1.tar.gz # cd courierpassd-1.1.0-RC1 # ./configure # make # make install Configure Xinetd to run courierpassd: # cd /etc/xinetd.d # vi courierpassd Add the following lines to the “courierpass” file: service courierpassd { port = 106 socket_type = stream protocol = tcp user = root server = /usr/local/sbin/courierpassd server_args = -s imap wait = no

Linux Servers Configuraton

36

only_from = 127.0.0.1 instances = 4 disable = no } # vi /etc/services Append the following line: courierpassd 106/tcp #for /etc/xinetd.d/courierpassd Restart the xinetd server: # /etc/rc.d/init.d/xinetd restart Test courierpassd using Telnet: # telnet localhost 106 Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'. 200 courierpassd v1.1.0-RC1 hello, who are you? user postmaster@osrc.org.pk 200 Your password please. pass 123 200 Your new password please. newpass 1234 200 Password changed, thank-you. quit 200 Bye. Connection closed by foreign host. The italicized letters display the input. The above output shows that the service is running smoothly

8.7. SquirrelMail
Edit the “php.ini” file and make sure that the variable “file_uploads” is “on”: # vi /etc/php.ini [php.ini path can vary] file_uploads = on # cd /downloads/qmailrocks Download the latest version of SquirrelMail from http://www.squirrelmail.org/download.php Move it to the web directory, which is usually /etc/var/www/html # tar zxvf /path/to/squirrelmail-x.x.x.tar.gz # mv squirrelmail-x.x.x webmail # mkdir /var/sqattachements # chown -R apache:apache /var/sqattachements # cd webmail # chown -R apache:apache data # cd config Configure SquirrelMail:

Open Source Software Training Toolkit

37

# ./conf.pl You should see something like this: SquirrelMail Configuration: Read: config_default.php (1.4.0) --------------------------------------------------------Main Menu -1. Organization Preferences 2. Server Settings 3. Folder Defaults 4. General Options 5. Themes 6. Address Books 7. Message of the Day (MOTD) 8. Plugins 9. Database 10. Languages D. Set pre-defined settings for specific IMAP servers C Turn color on S Save data Q Quit Command >> Enter 2 at the prompt to change the server settings. The following settings are recommended: General ------1. Domain : 192.168.2.66 2. Invert Time : false 3. Sendmail or SMTP : SMTP IMAP Settings -------------4. IMAP Server : localhost 5. IMAP Port : 143 6. Authentication type : login 7. Secure IMAP (TLS) : false 8. Server software : other 9. Delimiter : detect SMTP Settings ------------4. SMTP Server : localhost 5. SMTP Port : 25 6. POP before SMTP : false 7. SMTP Authentication : login 8. Secure SMTP (TLS) : false 9. Header encryption key : Configure the Apache web server. Edit the Apache configuration file and add the following line: NameVirtualHost 192.168.2.178:80 Add the following configuration lines:

Linux Servers Configuraton

38

<VirtualHost 192.168.2.178:80> ServerName mail.osrc.org.pk ServerAlias mail.* ServerAdmin postmaster@osrc.org.pk.com DocumentRoot /var/www/html </VirtualHost> Restart Apache and browse to http://www.yourdomain.com/webmail Enter “postmaster@osrc.org.pk” and the password “1234”. You should now be able to use the web interface for qmail, and be able to send and receive e-mails. Install the “change_pass” plug-in to SquirrelMail to change the password from the web interface: # cd /var/www/html/webmail/plugins/ Download the change_passwd plug-in from http://www.squirrelmail.org/plugins_category.php?category_id=5 # tar zxvf change_pass-xxx.tar.gz # rm -rf change_pass-xxx.tar.gz # cd /var/www/html/webmail/config # ./config.pl Enter option 8 and you should see change_pass under the available plug-ins. Enter the change_pass module number in order to activate it. Save the configuration and quit. SquirrelMail is now fully configured.

8.8. ClamAntivirus and SpamAssasin
Ensure that you have the following PERL modules installed: Digest::SHA1 Digest::HMAC Net::DNS Time::HiRes HTML::Tagset HTML::Parser Pod::Usage Parse::Syslog Statistics::Distributions Other required packages include: perl-suidperl unzip qmailrocks provides a script to check PERL modules. Run the script as a non-root user: # su tempuser $ /downloads/qmailrocks/scripts/util/check_perlmods.script # exit If you see “/usr/lib/perl5/vendor_perl/5.8.3/i386-linux-thread-multi/Time/HiRes.pm” it means that the package has been installed. Usually, “Statistics::Distributions” and “Parse::Syslog” are not installed by default. They can be installed by following the instructions given below: # cd /downloads/qmailrocks/perlmods # tar zxvf Parse-Syslog-xxx.tar.gz # cd Parse-Syslog-xxx # perl Makefile.PL # make

Open Source Software Training Toolkit

39

# make install # tar zxvf Statistics-Distributions-xxx.tar.gz # cd tar Statistics-Distributions-xxx # perl Makefile.PL # make # make install Run the script again as a non-root user to confirm that the missing packages have been installed. Use rpm -qa |grep unzip and rpm -qa |grep perl-suidperl. Install clamav. Make sure you are logged in as a root user: # cd /downloads/qmailrocks/ # rpm -Uvh clamav-x.x-x.x.rpm # rpm -Uvh clamav-devel-x.x-x.x.rpm Edit the clamav configuration file: # vi /etc/clamd.conf Ensure the following configuration: "Example" – should be commented out "LogFile" – should be set to /var/log/clamav/clamd.log "LogTime" - should not be commented "LogSyslog" - should not be commented "User" - should be set to qscand "ScanMail" - should not be commented Create the qscand user: # useradd -s /sbin/nologin qscand # /etc/init.d/clamd stop # /etc/init.d/clamd start The antivirus must be continuously updated with new virus definitions: # /usr/bin/freshclam -l /var/log/clamav/clam-update.log This should update the virus definitions immediately. Schedule the automatic updates. The following is a sample configuration; use whatever fulfills your requirements: # crontab –e Add the following sample schedule: 25 1 * * * /usr/bin/freshclam --quiet -l /var/log/clamav/freshclam.log Install SpamAssassin: # cd /downloads/qmailrocks/perlmods/rpms/ # rpm -Uvh perl-Mail-SpamAssassin-3.0.2-1.i386.rpm # cd /downloads/qmailrocks/ # rpm -Uvh spamassassin-3.0.2-1.i386.rpm spamassassin-tools-3.0.21.i386.rpm If you see the following message: error: Failed dependencies: perl(Parse::Syslog) is needed by spamassassin-tools-3.0.2-1.i386 perl(Statistics::Distributions) is needed by spamassassin-tools-3.0.2-1.i386 then use: # rpm -Uvh spamassassin-3.0.2-1.i386.rpm \ spamassassin-tools-3.0.2-1.i386.rpm –nodeps # groupadd spamd

Linux Servers Configuraton

40

# useradd -g spamd -s /home/spamd spamd # vi /etc/sysconfig/spamassassin Add/edit in the above file, and, in case there is no file, create a new one: SPAMDOPTIONS="-x -u spamd -H /home/spamd -d" Add the following line to “/etc/mail/spamassassin/local.cf” required_hits 5 # /etc/rc.d/init.d/spamassassin start SpamAssassin must be running, use ps # ps -aux | grep spamd Use the setup command to start the SpamAssassin service at boot time. The qmail configuration is now complete, and the mail server can be used to send and receive e-mails. For a production server, install some additional tools and configure the mails server to secure it over the Internet. The services that are required include: # qmailctl stat # /etc/rc.d/init.d/imap start # /etc/rc.d/init.d/imaps start # /etc/rc.d/init.d/spamd start # /etc/rc.d/init.d/httpd start

9. References • Qmailrocks.org: http://www.qmailrocks.org/

Open Source Software Training Toolkit

41

Dynamic Host Configuration Protocol (DHCP)

Linux Servers Configuraton

42

1. Introduction
The Dynamic Host Configuration Protocol (DHCP) provides configuration parameters to the Internet hosts. On a typical LAN, a DHCP server allocates network addresses and delivers network configuration parameters such as the gateway, netmask, DNS, etc. DHCP supports three mechanisms to allocate IP addresses:
• • •

Automatic allocation: A permanent IP address is allocated to a client. Dynamic allocation: An IP address is assigned for a limited period of time by the DHCP server. Manual allocation: The network administrator explicitly assigns an IP address to a particular client and DHCP is used to convey the assigned address.

This guide will demonstrate how to set up a DHCP server and client. More information regarding the protocol can be found in the “References” section.

2. Installtion
Many distributions come with a dhcpd server and client. In case you would like to install it manually, however, you can use rpm -ivh dhcp-VERSION.rpm to install the rpm. The DHCP server can be downloaded from "http://people.redhat.com/~jvdias/DHCP/". DHCP reads from a configuration /etc/dhcpd.conf. The rpm package does not install this file, but you can use the sample DHCP configuration file that can be found under /usr/share/doc/dhcp-<versionnumber>/dhcpd.conf.sample. Copy this file to /etc and rename it to dhcpd.conf. # cp /usr/share/doc/dhcp-3.0.1/dhcpd.conf.sample /etc/dhcpd.conf

2.1. Server Configuration
The sample dhcpd.conf file is shown below: ddns-update-style interim; ignore client-updates; subnet 192.168.0.0 netmask 255.255.255.0 { # --- default gateway option routers option subnet-mask 192.168.0.1; 255.255.255.0;

option nis-domain "domain.org"; option domain-name "domain.org"; option domain-name-servers 192.168.1.1; option time-offset -18000; # Eastern Standard Time # option ntp-servers 192.168.1.1; # option netbios-name-servers 192.168.1.1; # --- Selects point-to-point node (default is hybrid). Don't change this unless # -- you understand Netbios very well # option netbios-node-type 2; range dynamic-bootp 192.168.0.128 192.168.0.254; default-lease-time 21600; max-lease-time 43200; # we want the nameserver to appear at a fixed address host ns { next-server marvin.redhat.com; hardware ethernet 12:34:56:78:AB:CD; fixed-address 207.175.42.254; } }

Open Source Software Training Toolkit

43

A DHCP configuration file contains the configuration parameters for the clients. The important section in a DHCP client is "subnet 192.168.0.0 netmask 255.255.255.0" that specifies the subnet and netmask for which the address will be allocated. Other important options are: option routers ---> specifies default gateway for clients option subnet-mask ---> netmask for clients option domain-name-servers ---> DNS server to be used by the clients range ---> Range of IP addresses that will be allocated to clients The working DHCP configuration file is given below. ddns-update-style interim; ignore client-updates; subnet 10.0.0.0 netmask 255.0.0.0 { option routers option subnet-mask 10.10.10.1; 255.0.0.0;

option broadcast-address 10.255.255.255; option domain-name-servers 10.10.10.10; range 10.10.10.10 10.10.10.50; default-lease-time 21600; max-lease-time 43200; } Make sure to include "option broadcast-address". The above configuration file specifies that the clients will be given an IP address in the range 10.10.10.10 to 10.10.10.50. The default lease time, in case the client does not explicitly ask for it, will be 21600 seconds; otherwise the maximum allowed lease time is 43200 sconds. The server also specifies that the client should use the subnet mask 255.0.0.0, 10.255.255.255 as its broadcast address, 10.10.10.1 as the default gateway and 10.10.10.10 as the DNS server. The network diagram for this scenario is illustrated below: Client 1

Client 2 DHCP Server 10.10.10.100/8 switch

Client n

Once you have edited the dhcpd.conf file, start the server. If you get a failure message regarding lease file being missing, create the following file: # touch /var/lib/dhcp/dhcpd.leases

Linux Servers Configuraton

44

# service dhcpd start You can check whether DHCP is running by pgrep command # pgrep dhcpd The above configuration file dynamically allocates an IP address. DHCP can also be configured as a mixed environment that can allocate IP addresses dynamically and statically. The "host" section in the sample configuration file allocates an IP, based on the hardware address. Please see the “References” section for more advanced DHCP configurations. While running, DHCP server creates the client entries in /var/lib/dhcp/dhcpd.leases.

2.2. Client Configuration
The client side requires very little configuration. Most distributions come with a pre-installed version of a DHCP client. As an alternative, you can install rpm package, dhclient from "http://people.redhat.com/~jvdias/DHCP/". For RedHat, you can use netconfig to configure the DHCP host. # netconfig This will ask for a couple of options. Click on "Use dynamic IP configuration (BOOTP/DHCP)". Select "OK" and restart the network services. # service network restart If the DHCP server has been configured properly, the client should be able to get an IP address. Use ipconfig to check the IP. # ifconfig

3. References • DHCP Server Setup: • Configuring the DHCP Server:

http://www.tldp.org/HOWTO/DHCP/x369.html http://www.linuxhomenetworking.com/linux-hn/dchp.htm

Open Source Software Training Toolkit

45

Lightweight Directory Access Protocol (LDAP)
Theory taken from http://www.tldp.org, under the GNU Free Documentation License (FDL). While this step-by-step guide is a result of in-house implementation of a given scenario.

Linux Servers Configuraton

46

1. Overview:
The Lightweight Directory Access Protocol (LDAP) is a lightweight client-server protocol for accessing directory services, specifically X.500-based directory services. LDAP runs over TCP/IP or other connection-oriented transfer services. LDAP is defined as RFC2251. A directory is similar to a database, but it tends to contain more descriptive, attribute-based information. The information in a directory is generally read much more often than it is written. Directories are tuned to give a quick response to high-volume search operations. They may have an ability to replicate information widely in order to increase availability and reliability, while reducing response time. When directory information is replicated, temporary inconsistencies between the replicas may be considered acceptable as long as they eventually get synchronized. There are many different ways of providing a directory service. Different methods allow different kinds of information to be stored in the directory; place different requirements on how that information can be referenced, queried and updated; and how it can be protected from unauthorized access, etc. Some directory services are local, providing services within a restricted context (e.g., the finger service on a single machine). Other services are global, providing services within a much broader context.

2. How does LDAP work?
It is often convenient to share system information among workstations. Users, for example, like to be able to login to multiple machines with the same password; this requires that the machines share the data conventionally stored in /etc/passwd and /etc/shadow. Using NFS is usually not an option, since that will share all of /etc/, and you might want some elements configured differently on each machine. NIS used to be a common answer to this dilemma, but LDAP databases, being more flexible and scalable, have now become the preferred solution. The LDAP directory service is based on a client-server model. One or more LDAP servers contain the data making up the LDAP directory tree, or the LDAP back-end database. An LDAP client connects to an LDAP server, and asks it a question. The server responds with an answer or with a pointer to where the client can get more information (typically, another LDAP server). No matter what LDAP server a client connects to, it sees the same view of the directory; a name presented to one LDAP server references the same entry it would at another LDAP server. This is an important feature of a global directory service such as LDAP. LDAP databases are object-oriented, as opposed to relational databases. An LDAP database is filled with objects, each of which has associated attributes. The following example is a typical object representing a user account. dn: uid=abubakar,ou=people,dc=example,dc=com cn: Abubakar Shoaib uid: abubakar uidNumber: 1001 gidNumber: 100 homeDirectory: /home/abubakar loginShell: /bin/bash objectClass: top objectClass: posixAccount Each object has a unique Distinguished Name (DN) attribute for identification purposes. Each object is a member of one or more object classes, which determine which attributes it may and must have according to a well-defined schema. Objects in an LDAP database are organized into a tree hierarchy, based on their DN. By tradition, the organization example.com uses dc=example,dc=com for its root object (but nothing enforces this tradition). Below the root are objects representing different organizational units, such as people or hosts. The children of these objects are the people and hosts themselves.

Open Source Software Training Toolkit

47

3. LDAP back-ends, objects and attributes
The LDAP server daemon is known as Slapd. It supports a variety of different database backends which you can use. These include the primary choice BDB, a high-performance transactional database back-end; LDBM, a lightweight DBM-based back-end; SHELL, a back-end interface to arbitrary shell scripts; and PASSWD, a simple back-end interface to the passwd(5) file. The BDB utilizes Sleepycat Berkeley DB 4. LDBM utilizes either Berkeley DB or GDBM. The BDB transactional back-end is best-suited for multi-user read and write database access, with any mix of read and write operations. BDB is used in applications that require:
• •

Transactions, including making multiple changes to the database atomically, and rolling back uncommitted changes when necessary An ability to recover from system crashes and hardware failure without losing any committed transactions

A file format known as the LDAP Data Interchange Format (LDIF) is typically used in order to import and export directory information between LDAP-based directory servers, or to describe a set of changes which are to be applied to a directory. An LDIF file stores information in object-oriented hierarchies of entries. The LDAP software package comes with a utility to convert LDIF files into the BDB format. A common LDIF file looks like this: dn: o=TUDelft, c=NL o: TUDelft objectclass: organization dn: cn=Qandeel Aslam, o=TUDelft, c=NL cn: Qandeel Aslam sn: Aslam mail: qaslam@yahoo.com objectclass: person As you can see, each entry is uniquely identified by a DN. The DN consists of the name of the entry, plus a path of names tracing the entry back to the top of the directory hierarchy. In LDAP, an object class defines the collection of attributes that can be used to define an entry. The LDAP standard provides the following basic types of object classes: 1. Groups in the directory, including unordered lists of individual objects, or groups of objects 2. Locations, such as a country’s name and description 3. Organizations in the directory 4. People in the directory An entry can belong to more than one object class. The entry for a person, for example, is defined by the person object class, but can also be defined by attributes in the inetOrgPerson, groupOfNames, and organization objectclasses. The server's object class structure (its schema) determines the total list of required and allowed attributes for a particular entry. Directory data is represented in the form of attribute-value pairs. Any specific piece of information is associated with a descriptive attribute. The Common Name (CN) attribute is used to store a person's name. A person named Abubakar Shoaib can be represented in the directory as: cn: Abubakar Shoaib Each person entered in the directory is defined by the collection of attributes in the person object class. Other attributes used to define this entry can include:

Linux Servers Configuraton

48

givenname: Abubakar surname: Shoaib mail: ashoaib@airius.com Required attributes include the attributes that must be present in entries using the object class. All entries require the objectClass attribute, which lists the object classes to which an entry belongs. Allowed attributes include the attributes that may be present in entries using the object class. In the person object class, for example, the CN and SN attributes are required. The description, telephoneNumber, seeAlso, and userpassword attributes are allowed, but are not required. Each attribute has a corresponding syntax definition, which describes the type of information provided by an attribute. Examples include: 1. BIN binary 2. CES Case Exact String (case must match during comparisons) 3. CIS Case Ignore String (case is ignored during comparisons) 4. TEL telephone number string (like CIS, but blanks and dashes "-" are ignored during comparisons) 5. DN Distinguished Name Note: Objectclass and attribute definitions generally reside on schema files, on the subdirectory schema, under the OpenLDAP installation home.

4. Step-by-step Configuration Guide
4.1. Scenario
• • • • • • • A company wants a simple, secure, centralized login scheme for all its servers/clients. It has decided to use the LDAP domain “tdomain.com” for its LDAP database, in which one Domain Component (DC) will be “tdomain”, and the other will be “com”. The database will have only one organizational unit known as “People”, which is an LDAP default. Each person will have attributes, such as a username (User ID or UID), password, Linux home directory, and login shell. The Fedora Linux server known as Dman, with the IP address 192.168.2.79, will act as the LDAP server containing the database. The Fedora Linux server known as smallfry will be used to test the system as the LDAP client. It has the IP address 192.168.2.69. The server Dman has a special user account named ldapuser. It will be used to test the LDAP logins.

4.2. Downloading and Installing the LDAP Packages
Most Red Hat and Fedora Linux software products are generally available in the RPM format. When searching for the file, remember that the FreeRADIUS RPM's filename usually starts with “openldap”, followed by a version number, as in openldap-servers-2.1.22-8.i386.rpm. 4.2.1. Required LDAP Server RPMs Ensure that the following packages are installed on your LDAP server: 1. openldap 2. openldap-clients

Open Source Software Training Toolkit

49

3. openldap-devel 4. nss_ldap 5. openldap-servers 4.2.2. Required LDAP Client RPMs Ensure that the following packages are installed on your LDAP client: 1. openldap 2. openldap-clients 3. openldap-devel 4. nss_ldap

4.3. Configuring the LDAP Server
The first stage of the project is to correctly configure the LDAP server. Create an LDAP database into which you will import the /etc/passwd file: 4.3.1. Create a database directory Fedora LDAP defaults to putting all databases in the /var/lib/ldap directory. For the tdomain, create a dedicated tdomain.com directory owned by the user ldap. (The ldap user is always created during the RPM installation process): [root@Dman tmp]# mkdir /var/lib/ldap/tdomain.com [root@Dman tmp]# chown ldap:ldap /var/lib/ldap/tdomain.com 4.3.2. Create an LDAP "root" password Only an LDAP root user can create, import, and export data into an LDAP database. This user requires an encrypted password. Create it with the slappasswd command, and use the result in the LDAP configuration file: [root@Dman tmp]# slappasswd New password: Re-enter new password: {SSHA}v4qLq/qy01w9my60LLX9BvfNUrRhOjQZ [root@Dman tmp]# 4.3.3. Edit the slapd.conf file The main LDAP server configuration file is /etc/openldap/slapd.conf. Update it with: 1. A database of the default type ldbm, using the domain suffix tdomain.com, made up of the Domain Components (DCs) tdomain and com. 2. The root user with a Common Name (CN), or nickname, of “Manager” who is a part of the tdomain and com DCs. 3. An encrypted version of the LDAP root password, as well as the location of the LDAP database. The configuration file syntax to do this is: database suffix rootdn ldbm "dc=tdomain,dc=com" "cn=Manager,dc=tdomain,dc=com"

Linux Servers Configuraton

50

rootpw directory

{SSHA}v4qLq/qy01w9my60LLX9BvfNUrRhOjQZ /var/lib/ldap/tdomain.com

4.3.4. Start the LDAP daemon The service command uses the options “start”, “stop”, and “restart” to control the LDAP server's operation. Use the “start” option to load the contents of the slapd.conf file. [root@Dman tmp]# service ldap start Starting slapd: [ OK ] [root@Dman tmp]# 4.3.5. Convert the /etc/passwd file into LDIF format The data on the server's /etc/passwd file now needs to be converted into the LDAP Data Interchange Files (LDIF) format before it can be imported into the LDAP database. You do not need to import all of the usernames, only the ones you need. 4.3.6. Create the ldapuser test account To create the ldapuser account you will use for testing, type: [root@Dman tmp]# useradd -g users ldapuser [root@Dman tmp]# passwd ldapuser Changing password for user ldapuser. New password: Retype new password: passwd: all authentication tokens updated successfully. [root@Dman tmp]# 4.3.7. Extract the required records from /etc/passwd Extract the ldapuser information from the /etc/passwd file using the grep command. Save it by appending the information to the /etc/openldap/passwd.ldapusers file, with the > character: [root@Dman tmp]# grep ldapuser /etc/passwd > \ /etc/openldap/passwd.ldapusers [root@Dman tmp]# If this is your first time creating an LDAP database, extract the information for the Linux root account from the /etc/passwd file to a new file known as /etc/openldap/passwd.root. [root@Dman tmp]# grep root /etc/passwd > \ /etc/openldap/passwd.root [root@Dman tmp]# 4.3.8. Find the conversion script The /etc/passwd conversion program is called migrate_passw.pl; find it by using the “locate” command. This utility updates its database every night, and might be unable to find newlyinstalled files. Use the locate command to update ahead of schedule: [root@Dman tmp]# locate -u [root@Dman tmp]# locate migrate

Open Source Software Training Toolkit

51

... /usr/share/openldap/migration/migrate_passwd.pl ... [root@Dman tmp]# 4.3.9. Convert the ".ldapuser" file Convert the extracted /etc/passwd data into an LDIF, which will then be imported into the database. Give the file used by regular users the name /etc/openldap/ldapuser.ldif and the one for the root user the name /etc/openldap/root.ldif. [root@Dman tmp]# /usr/share/openldap/migration/migrate_passwd.pl \ /etc/openldap/passwd.ldapusers /etc/openldap/ldapusers.ldif [root@Dman tmp]# [root@Dman tmp]# /usr/share/openldap/migration/migrate_passwd.pl \ /etc/openldap/passwd.root /etc/openldap/root.ldif [root@Dman tmp]# 4.3.10. Modify the LDIF files With your two new LDIF files, the next step is to import this data into the LDAP database. In order to prepare for this, you must do some editing, and create a new LDIF file that defines an organizational unit. 4.3.11. Edit the user LDIF file The Fedora migrate_passwd.pl script creates users that are all a part of an organizational unit known as “People”, but everyone belongs to the padl.com domain. Edit both the LDIF files, and convert the string "padl" into "tdomain" in each record. A text editor is suitable for this purpose. For tdomain, at the vi editor's : prompt, use the following command to perform a global substitution of “tdomain” for “padl”: %s/padl/tdomain/g In the slapd.conf file, you gave the root user a Common Name (CN) of Manager. Add this information to the root LDIF file by inserting the following line under the UID line in the file: cn: Manager 4.3.12. Create an LDIF file for the "tdomain.com" domain The LDIF files which you have created from /etc/passwd refers to users only. The attributes of the tdomain.com domain, and the organizational unit known as “People”, have not yet been defined. This can be done using a third LDIF file known as /etc/openldap/tdomain.com.ldif, which should look like this: dn: dc=tdomain,dc=com dc: tdomain description: Root LDAP entry for tdomain.com objectClass: dcObject objectClass: organizationalUnit ou: rootobject

Linux Servers Configuraton

52

dn: ou=People, dc=tdomain,dc=com ou: People description: All people in organization objectClass: organizationalUnit 4.3.13. Import the LDIF files into the database Use the LDAP add command to import all three LDIF files into the database, starting with the tdomain.com.ldif file, followed by root.ldif, and lastly by ldapusers.ldif. When you are prompted, enter the LDAP root password you created: [root@Dman tmp]# ldapadd -x -D "cn=Manager,dc=tdomain,dc=com" \ -W -f /etc/openldap/tdomain.com.ldif [root@Dman tmp]# ldapadd -x -D "cn=Manager,dc=tdomain,dc=com" \ -W -f /etc/openldap/root.ldif [root@Dman tmp]# ldapadd -x -D "cn=Manager,dc=tdomain,dc=com" \ -W -f /etc/openldap/ldapusers.ldif [root@Dman tmp]# 4.3.14. Test the LDAP database View all the LDAP database entries all at once with the “ldapsearch” command; this test confirms that you have all the correct functionality: [root@Dman tmp]# ldapsearch -x -b 'dc=tdomain,dc=com' \ '(objectclass=*)' [root@Dman tmp]#

4.4. Configuring the LDAP Client
Now that the LDAP server has been configured properly, you can begin to configure and test the clients. 4.4.1. Edit the ldap.conf configuration file LDAP clients are configured using the /etc/openldap/ldap.conf file. Make sure that the file refers to the LDAP server's IP address for the domain tdomain.com. The file should look like this: HOST 192.168.2.79 BASE dc=tdomain,dc=com 4.4.2. Edit the /etc/nsswitch file The /etc/nsswitch.conf file defines the order in which the Linux operating system searches login databases for login information. Configure it to first search its /etc/passwd file. If it does not find the user password information here, it goes to the LDAP server. Set this up by using the /usr/bin/authconfig command: • • Run /usr/bin/authconfig Select LDAP

Open Source Software Training Toolkit

53

• • • •

Give the LDAP server's IP address, which is 192.168.2.79 in this case Give the base DN as dc=tdomain,dc=com Do not select TLS Use MD5 and shadow passwords

The screen should look like this: [*] Use Shadow Passwords [*] Use MD5 Passwords [*] Use LDAP [ ] Use TLS Server: 192.168.2.79 Base DN: dc=tdomain,dc=com When finished, look at the /etc/nsswitch.conf file, and make sure that it has references to LDAP. 4.4.3. Create Home Directories on the LDAP Client You previously created a user known as ldapuser in the group users on server Dman. Ensure that this user has a home directory on the LDAP client smallfry. The tdomain in this section creates the directory, and makes ldapuser the owner. The server smallfry correctly gets its user information about ldapuser from Dman; the chosen command does not complain about ldapuser not existing in smallfry's /etc/passwd file. 4.4.4. Check if ldapuser is missing from the /etc/passwd file Look for ldapuser by searching the /etc/passwd file with the grep command. There should be no response: [root@smallfry tmp]# grep ldapuser /etc/passwd [root@smallfry tmp]# 4.4.5. Create the Home Directory for ldapuser on the LDAP Client Create the home directory, copy a BASH login profile file into it, and modify the ownership of the directory, and all the files, to user ldapuser. Note: If the chosen command fails, it is probably because of an incorrect LDAP configuration, in which the LDAP client cannot read the user information from the LDAP server. In some cases, you might want to use NFS mounts to provide home directories for your users, which will significantly reduce the need to perform this procedure: [root@smallfry tmp]# mkdir /home/ldapuser [root@smallfry tmp]# chmod 700 /home/ldapuser/ [root@smallfry tmp]# chown ldapuser:users /home/ldapuser/ [root@smallfry tmp]# ll /home total 2 drwx-----2 ldapuser users 1024 Aug 4 08:05 ldapuser [root@smallfry tmp]# [root@smallfry tmp]# cp /etc/skel/.* /home/ldapuser/ cp: omitting directory `/etc/skel/.' cp: omitting directory `/etc/skel/..' cp: omitting directory `/etc/skel/.kde'

Linux Servers Configuraton

54

[root@smallfry tmp]# chown ldapuser:users /home/ldapuser/.* [root@smallfry tmp]#

4.5. Testing
Login to smallfry using the username ldapuser.

Open Source Software Training Toolkit

55

SAMBA

Linux Servers Configuraton

56

1. Overview
Samba is a suite of UNIX applications that communicate via the Server Message Block (SMB) protocol. Many operating systems, including Microsoft (MS) Windows and Macintosh OS/2, use SMB to perform client-server networking. By supporting this protocol, Samba allows UNIX servers to communicate with the same networking protocol as MS Windows products. A Samba-enabled UNIX machine can masquerade as a server on your MS network, and offer the following services: Table 1: Samba Roles (as of Version 2.0.4b) Role File Server Printer Server Primary Domain Controller Back-up Domain Controller Windows 2000/95/98 Authentication Local Master Browser Local Back-up Browser Domain Master Browser Primary WINS Server Secondary WINS Server Yes Yes Yes Yes Yes Yes No Yes Yes No Can Perform

The Samba suite revolves around a pair of UNIX daemons that provide shared resources. These daemons are:

smbd: The smbd daemon is responsible for managing the shared resources between the Samba server machine and its clients. It provides file, print, and browser services to SMB clients across one or more networks. smbd handles all the notifications between the Samba server and the network clients. It is also responsible for user authentication, resource-locking, and data-sharing through the SMB protocol.nmbd. nmbd: The nmbd daemon is a nameserver that mimics the WINS and NetBIOS name server functionality, as you might expect to encounter with a LAN Manager package. This daemon listens for nameserver requests, and, when called upon, provides the appropriate information. It also provides browsing lists for the Network Neighborhood, and participates in browsing elections.

Samba also comes with a small set of UNIX command-line tools:

• • • • • • •

nmblookup: A program that provides NetBIOS over TCP/IP name look-ups smbclient: An FTP-like UNIX client that can be used to connect to Samba shares smbpasswd: A program that allows an administrator to change the encrypted passwords used by Samba smbstatus: A program for reporting the current network connections to the shares on a Samba server smbtar: A program for backing up the data in the shares, similar to the UNIX tar command testparm: A program to validate the Samba configuration file testprns: A program that tests whether various printers are recognized by the smbd daemon

Open Source Software Training Toolkit

57

2. Configuring Samba
smb.conf is at the heart of the Samba server. When the Samba package is installed, a default configuration file is installed in /etc/samba/smb.conf. The smb.conf file is divided into two main sections: 1. Global Settings – Defines connection parameters. 2. Share Definitions – Defines shares. A share is a directory on the server that is accessible over the network, and which is shared among users. This section has three sub-sections: 1. Homes - Defines the user’s home directories 2. Printers - Defines the available printers 3. Shares - Have an entry for each share you would like to define

2.1. Setting the NetBIOS parameters
The smb.conf file begins with the global settings for setting up the NetBIOS parameters of the Samba server: #=================== Global Settings ===================== [global] netbios name = NF5000 workgroup = LINUX server string = Samba Server The parameters are described in Table 2. Table 2. NetBIOS parameters Description This is the name by which the Samba server is known on the network. This parameter has the same meaning as a Windows NT computer’s name. If you do not specify its name, it defaults to the server’s hostname. This parameter specifies in which Windows NT workgroup the Samba server will participate. It is equivalent to the Windows NT domain or workgroup’s name. This is the description string of the Samba server. It performs the same role as the Windows NT description’s field.

Parameter netbios name workgroup server string

2.2. Global printing settings
The global printing parameters are given below: load printers = yes printcap name = /etc/printcap printing = lprng The parameters are described in Table 3. Table 3. Printing parameters Description This parameter controls if Samba loads all the printers in the printcap file for browsing. This parameter tells Samba the location of the printcap file. The default value is /etc/printcap. This parameter tells Samba which printing style to use on your server. Samba uses the LPRNG printing style by default.

Parameter load printers Printcap name Printing

2.3. Global security settings
The global security parameters are given below:

Linux Servers Configuraton

58

security = user ; password server = <NT-Server-Name> encrypt passwords = yes smb passwd file = /etc/samba.d/smbpasswd Table 4. Printing parameters Description This parameter has four possible values: domain, server, share, and user. This server is used for authorization at the server or domain security level. Use the server’s NetBIOS name for the parameter value. Setting this parameter to “Yes” will enable Samba to use an encrypted password protocol. This is used in the MS Windows NT Service Pack 3, and in MS Windows 98, and is required in order to communicate with these clients. This parameter tells Samba the location of the encrypted password file.

Parameter Security Password server encrypt passwords Smb passwd file

2.4. Global name resolution settings
The global name resolution parameters are given below: name resolve order = wins lmhosts bcast wins support = yes ; wins server = w.x.y.z These parameters are described in Table 5. Table 5. Name resolution parameters Description This parameter specifies how the Samba server will resolve NetBIOS names into IP addresses. The preferred value is wins lmhosts bcast. If this option is enabled, the Samba server will also act as a WINS server. This parameter tells Samba which WINS server to use.

Parameter name resolve order wins support wins server

Note: Samba can be either a WINS server or a WINS client, but not both. Only one of the WINS support and WINS server parameters can be set at a time. If you specify the IP address of a WINS server, then the WINS support must be set to “No”.

2.5. Creating shares
A share can be defined in the smb.conf file as given below: [redbook] comment = Redbook files path = /redbook browseable = yes printable = no writable = yes write list = @users Table 6 explains some of the parameters used for creating shares. Table 6. Share parameters

Open Source Software Training Toolkit

59

Parameter comment admin users Path Browseable Printable

Description This parameter describes the function of a share. This parameter is used to specify the users who have administrative privileges to the share. When they access the share, they perform all operations as root. Defines the full path to the directory you are sharing. If this parameter is set to “Yes”, you can see the share when you are browsing the resources on the Samba server. The value can be “Yes”, or “No”. This parameter is used to specify if the share is a print share. The value can be “Yes”, or “No”.

write list Writable

Users specified in this list have write access to the share. If the name begins with @ it indicates a group name. This parameter specifies if the share is writable. The value can be “Yes”, or “No”.

read list read only

Users specified in this list have read access to the share. If the name begins with @ it indicates a group name. If this parameter is set to “Yes”, the share is read-only. The value can be “Yes”, or “No”.

valid users

This parameter specifies which users can access the share.

2.6. Share permissions
Although you can control the share permissions with share parameters, UNIX permissions are applied before share permissions. Ensure that the UNIX permissions let the users access the share directory in the UNIX environment. When a user creates a new file on the shared directory, the default create mask used is 0744. For directory creation, the default create mask is 0755. You can force a different creation mask by using the parameters explained in Table 7: Table 7. Create mask parameters Description This is used for file creation to mask against the UNIX mask calculated from the DOS mode. This is used for directory creation to mask against the UNIX mask calculated from the DOS mode.

Parameter create mask directory mask

2.7. Creating shares for home directories
smb.conf has a special share section called [homes] for handling home directories. This share definition is used for all home directories, so you will need to create separate shares for each user. When a client requests a connection to a share, the existing shares are scanned. If a match is found, that share is used. If no match is found, the requested share is treated as the username, and is validated by security. If the name exists and the password is correct, a share with that name is created by cloning the [homes] section. Home share definitions use the same parameters as normal shares. The following is an example of a [homes] share definition in the smb.conf file: [homes] comment = Home Directories path = %H valid users = %S

Linux Servers Configuraton

60

browseable = no writable = yes create mode = 0700 directory mode = 0700 Table 8 explains the use of certain variables in the [homes] share definition: Table 8. Variable description Description This variable represents the user’s home directory. The name of the current service, which is, in the case of [home] shares, equal to the username.

Parameter %H %S

2.8. Creating a printer share
A Samba server follows the same procedure for [printer] shares that applies to [home] shares. The share definitions and user names are tested against the requested share name. If a match is found in the [printers] share section, a share with that name is cloned with the name of the requested service. The following is an example of a [printers] definition in the smb.conf file: [printers] comment = All Printers path = /var/spool/samba browseable = no # Set public = yes to allow user ’guest account’ to print guest ok = no writable = no printable = yes create mask = 0700 The [printers] section is just like the other share definitions. When a user prints, Samba copies the data into the spool directory, after which it is handled by the local printing system. The only major difference between a printer share and other share definitions is that the printable parameter is set to “Yes”. This means that a user can write a spool file to the directory specified under the share definition. If the share is printable, then it is also writable by default.

3. Starting and stopping the Samba server
Start the Samba server by executing the following command: /etc/rc.d/init.d/smb start You will see: Starting SMB services: Starting NMB services: Two daemons have been started: smbd and nmbd. smbd is the Samba server, and nmbd is the WINS server. The Samba server can be stopped by executing the command: /etc/rc.d/init.d/smb stop Restart the Samba server whenever you modify the smb.conf configuration file.

Open Source Software Training Toolkit

61

4. Step-by-step Configuration Guide
4.1. Samba as Primary Domain Controller
Add the following lines to the global section of the smb.conf file: # The domain you want to be a PDC for workgroup = osrc encrypt passwords = yes smb passwd file = /etc/samba/smbpasswd # Tell Samba to use domain logons domain logons = yes # User-level security. Users must # authenticate themselves with # valid username and password security = user # Set to yes so that nmbd participates # in local master browser # elections local master = yes # Set Os level value to make sure nmbd # wins local browse master # elections. 65 should beat everyone # according to the man page os level = 65 # Give nmbd an advantage in local # master browser elections preferred master = yes # Set so that nmbd claims a unique # NetBIOS name identifying it as # a domain master domain master = yes # run a specific logon batch file per username logon script = %U.bat [homes] comment = Home Directories browseable = no writeable = yes # The following share is required to support # domain logons. The directory may be # created anywhere on your system. Make # sure the share is non-writeable and also # not a public share. [netlogon] comment = The domain logon service path = /usr/local/samba/netlogon public = no writeable = no Add Samba password for the user root: # smbpasswd -a root

Linux Servers Configuraton

62

Create a MS Windows machine account. The name of your Windows workstation, for example, which is to join this domain, is “ws01”. # groupadd machines # useradd -g machines –d /dev/null –s /bin/false ws01$ # smbpasswd –a –m ws01 Note: Domain users are created in two steps: • Add a Linux user # useradd bakar • Add this user to smbpasswd # smbpasswd -a bakar

4.2. Join Domain
Logging in as an administrator in MS Windows, right-click “My Computer”. Go to “Properties” -> “Computer Name” -> “Change”. In “Domain”, type the domain name you want to join. In this example, that would be osrc, and press the “Enter” key. When asked for authentication, enter root and its password, which you kept with the smbpasswd command. A message window, “Welcome to osrc”, will pop-up. Click “OK”, and restart the machine. On the login screen, select the domain, osrc, from the drop-down menu, and login with the domain user.

Open Source Software Training Toolkit

63

Squid Cache Server

Linux Servers Configuraton

64

1. An Overview
Squid acts as an agent, accepting requests from clients such as browsers, and passing them onto an appropriate Internet server. It stores a copy of the returned data in an on-disk cache. Squid’s real benefit emerges when the same data is requested multiple times, and a copy of the on-disk data is returned to the client, speeding up Internet access, and saving bandwidth. Small amounts of disk space can significantly impact bandwidth usage and browsing speed. Internet firewalls, which are used to protect company networks, often have a proxy component. The Squid proxy is different from a firewall proxy in that most firewall proxies do not store copies of the returned data; they re-fetch requested data from the remote Internet server each time. Squid differs from firewall proxies in other ways as well: • It supports many protocols (firewalls often have specific proxies for specific protocols; it is difficult to ensure the code security of a large program) • Hierarchies of proxies, arranged in complex relationships, are possible A 'cache', actually refers to a 'caching proxy' - something that keeps copies of returned data. A 'proxy', on the other hand, is a program which does not cache replies. The web consists of HTML pages, graphics, and sound files, etc. Since only a very small portion of the web constitutes text, referring to all cached data as pages is misleading. Caches store objects, not pages. Many Internet servers support more than one protocol. A given server can support more than one type of query protocol. A web server uses the HyperText Transfer Protocol (HTTP) to serve data. An older protocol, the File Transfer Protocol (FTP) often runs on web servers as well. Caching an FTP response and returning the same data to the client on a subsequent HTTP request can cause confusion, and should, therefore, be avoided. Squid uses the complete Universal Resource Locator (URL) to uniquely identify everything stored in the cache. Objects must be expired in order to avoid returning outdated data to clients. Squid allows you to set refresh times for objects, ensuring that this does not happen.

2. Why cache?
Small Internet Service Providers (ISPs) cache in order to reduce their line costs, since a large portion of their operating costs is infrastructural rather than staff-related. Large organizations are usually not short of bandwidth, but their customers occasionally experience slow response times. There are many reasons for this:

2.1. Origin Server Load
Raw bandwidth is increasing faster than overall computer performance. Many servers act as a back-end for one site, load-balancing incoming requests. Where this is not done, the result is a slow response. Caches prevent slow response times.

2.2. Quick Abort
Squid can be configured to continue fetching objects, within certain size limits, even if a user who has initiated a download aborts it midway. Since there is a chance of more than one user requesting the same file, it is useful to have the object’s copy in your cache, even if the first user aborts. Where you have access to plenty of bandwidth, this continuous fetching process ensures that you will have a local copy of the object available, just in case someone else requests it. This can drastically reduce latency at the cost of higher bandwidth usage.

2.3. Peer Congestion
Router speed needs to increase at the same rate as bandwidth increases. Many peering points - where huge volumes of Internet traffic are exchanged - often do not have the router horsepower to support their ever-increasing load.

Open Source Software Training Toolkit

65

2.4. Traffic spikes
Large sport, television and political events can cause spikes in Internet traffic. Plan ahead for sports events, but it is difficult to estimate the load that they will eventually cause. If you are a local ISP, and your local team reaches the finals, you are likely to experience a huge peak in traffic. Companies can also be adversely affected by traffic spikes, with the bulk transfer of large databases or presentations flooding the lines at random intervals. Caching cannot completely solve this problem, but it can reduce its impact.

2.5. Unreachable sites
If Squid attempts to connect to an origin server, only to find that it is down, it will log an error and return the object from a disk, even if there is a chance of sending outdated data to the client. This reduces the impact of large-scale Internet outage, and can help when a backhoe digs up a major segment of your network backbone.

2.6. Costs
Since Internet connectivity is so expensive, ISPs and their customers reduce their bandwidth requirements with caches.

3. Supported Protocols
3.1. Supported Client Protocols
Squid supports the following incoming protocol request types, when the proxy requests are sent in HTTP format: • • • • • File Transfer Protocol (FTP) Gopher HyperText Transfer Protocol (HTTP) Secure Socket Layer (SSL) Wide Area Information Server (WAIS)

3.2 Inter-cache and Management Protocols

• • • • •

Cache Digests: Used to retrieve an index of objects in another cache's store HyperText Transfer Protocol (HTTP): Used for retrieving copies of objects from other caches Hyper Text Caching Protocol (HTCP): Internet Cache Protocol (ICP): Used to find out if a specific object is in another cache's store Simple Network Management Protocol (SNMP): Can be used to retrieve information about your cache

3.3 Inter-cache Communication Protocols
Squid enables you to share data between caches. Just as there is a benefit to connecting individual PCs to a network, and this network to the Internet, there is also an advantage to linking your cache to other people's networks of caches. User Base: The larger your user base, the more objects requested, the higher the chances of an object being requested twice. In order to increase your hit rate, add more clients. Reduced Load: If you have a large network, one cache might be unable to handle all incoming requests. Rather than having to continuously upgrade one machine, it makes sense to divide the load between multiple servers. This reduces an individual server’s load, while increasing the overall number of queries your cache system can handle. Squid implements inter-cache protocols very efficiently, through ICP multi-cast queries and cache digests, which allow for large networks of caches (hierarchies). Disk Space: If you load-balance between multiple caches, avoid duplication of data. Duplicated objects reduce the quantity of objects in the overall store, which reduces your

Linux Servers Configuraton

66

chances of a hit. Using the Cache Array Routing Protocol (CARP) or other inter-cache communication protocols reduces duplication. Raw bandwidth is not the only issue affecting the efficiency and speed of your cache system. Choosing the right hardware and software also presents its own challenges.

4. Squid Configuration
4.1 The Configuration File
All Squid configuration files are kept in the directory /usr/local/squid/etc. Although there is more than one file in this directory, the squid.conf file is of primary importance to most administrators. Although there are hundreds of option tags in this file, change only eight options in order to get Squid up and running. The other options provide amazing flexibility, but you can learn more about them once you have Squid functioning smoothly, by experimenting with the options. Squid assumes that you wish to use the default value if there is no occurrence of a tag in the squid.conf file. Theoretically, you can even run Squid with a zero-length configuration file.

4.2 Setting Squid's HTTP Port
The first option in the squid.conf file sets the HTTP port(s) that Squid will listen to for incoming requests. Squid's default HTTP port is 3129. You can also use multiple ports, appending a second port number to the http_port variable. Consider the following example: http_port 3128 8080

4.3 Storing Cached Data
The cache_dir operator in the squid.conf file is used to configure specific storage areas. If you use more than one disk for the cached data, you may need more than one mount point (/usr/local/squid/cache1 for the first disk, /usr/local/squid/cache2 for the second, for example). Squid allows you to have more than one cache_dir option in your config file: cache_dir /usr/local/squid/cache/ 100 16 256 The first option for the cache_dir tag sets the directory where the data will be stored. The prefix value simply has /cache/ tagged onto the end, and it is used as the default directory. The second option for the cache_dir tag is a size value. Squid will store up the specified amount of data in that directory. The value is in megabytes, as is that of the cache store. The default is 100 megabytes. The other two options are more complex: they set the number of sub-directories (first and second-tier) to create in this directory.

4.4 E-mail for the Cache Administrator
If Squid dies, an e-mail notification is sent to the specified address with the cache_mgr tag. This address is also appended at the end of error pages returned to users if, for example, the remote machine is unreachable.

5. Access Control Lists and Access Control Operators
Squid cannot be used in an ISP environment without a sophisticated access control system. Indeed, Squid should not be used in any environment without some kind of basic authentication system. It is amazing how fast other Internet users discover that they can relay requests through your cache, and then proceed to do so. Sometimes they do this in order to obfuscate their real identity, and at other times since they have a fast line to you, but a slow line to the remainder of the Internet.

Open Source Software Training Toolkit

67

5.1 Simple Access Control
Assume that you have a list of IP addresses that are allowed to have access to your cache. If you want them to be able to access it with both HTTP and ICP, you will have to enter the list of IP addresses twice: Example 1. Theoretical Access List http_access deny 10.0.1.0/255.255.255.0 http_access allow 10.0.0.0/255.0.0.0 icp_access allow 10.0.0.0/255.0.0.0 Rule sets like the ones given above are straightforward enough for small organizations. For large organizations, however, it is more convenient to create classes of users. You can then allow or deny classes of users in more complex relationships. Consider the following example, in which you duplicate the above-mentioned example with classes of users: Example 2. Access lists using Classes # classes acl mynetwork src 10.0.0.0/255.0.0.0 acl servernet src 10.0.1.0/255.255.255.0 # what HTTP access to allow classes http_access deny servernet http_access allow mynet # what ICP access to allow classes icp_access deny servernet icp_access allow mynet The squid.conf file that comes with Squid includes ACLs, which denies all HTTP requests. Explicitly allow incoming requests to use your cache from an appropriate range. The squid.conf file includes text that reads: # # INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS # In order to allow access to your client machines, add rules similar to the ones given below. The default access-control rules prevent users from exploiting your cache; it is advisable to leave them in. Example 3. Example Complete ACL list # # INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS # # acls for my network addresses acl my-iplist-1 src 192.168.1.0/24 acl my-iplist-2 src 10.0.0.0/255.255.0.0 # Check that requests are from users on our network http_access allow my-iplist-1 http_access allow my-iplist-2 icp_access allow my-iplist-1 icp_access allow my-iplist-2 # allow requests from the local machine (for testing and the like) http_access allow localhost # End of locally-inserted rules http_access deny all

Linux Servers Configuraton

68

6. Step-by-step Configuration Guide
Note: The following configuration will enable you to run a cache with base-line configuration. To learn more about advanced options, please visit http://www.squid-cache.org. Install the Squid rpm from the Red Hat CD. This will install its configuration file (squid.conf) in the directory /etc. Open the file /etc/squid.conf and follow the steps given below:

Search for the line http_port, and change the port if required: http_port 8080 This is the port that your users will use in order to access the Internet.

Look for the line: cache_mem 8 MB

Assign the value to cach_mem in MBs according to your resources. • Look for the lines: cache_swap_low 90 cache_swap_high 95 Uncomment these lines if they are commented, and leave the values unchanged. • ip_cache_size ipcache_low ipcache_high 1024 90 95

Uncomment these lines, and leave their default values. • cache_dir ufs /var/spool/squid 100 16 56

Uncomment this line, and leave its default values. • cache_access_log /var/log/squid/access.log access.log is used to see the web requests going through your proxy server, as in winproxy in MS Windows. Uncomment it. • cache_log /var/log/squid/cache.log Uncomment it. • cache_store_log /var/log/squid/store.log Uncomment it. • pid_filename /var/run/squid.pid Uncomment it. • log_fqdn off Uncomment it, and change it into its “On” state, so that it looks like this: log_fqdn on • Search for the line:

Open Source Software Training Toolkit

69

acl localhost src 127.0.0.1/255.255.255.255 Assume that your network ID is 192.168.1 with a sub-net mask of 255.255.255.0. Name your network; “lan”, for example. Enter the following line next to the abovementioned line: acl • lan src 192.168.1.0/255.255.255.0

Search for the line: http_access allow localhost http_access deny all Add permissions to your group, i.e. lan http_access allow localhost http_access allow lan http_access deny all

Start the proxy server with the following command: /etc/rc.d/init.d/squid start

Open a browser on any workstation, and enter the proxy address along with the port, i.e. 8080. You are now ready to browse the Internet.

Linux Servers Configuraton

70

Firewalls

Open Source Software Training Toolkit

71

1. Introduction
Firewalls make it possible to filter incoming and outgoing traffic that flows through your system. A firewall can use one or more sets of “rules” to inspect the network packets as they come in or go out of your network connections, and either allows the traffic through, or blocks it. The rules of a firewall can inspect one or more characteristics of the packets, including, but not limited to, the protocol type, the source or destination host address, and the source or destination port. Firewalls can greatly enhance the security of a host or a network. They can be used to perform one or more of the following actions: • • To protect and insulate the applications, services and machines of your internal network from unwanted traffic coming in from the public Internet. To limit or disable access from hosts of the internal network to services of the public Internet. To support Network Address Translation (NAT), which allows your internal network to use private IP addresses and share a single connection to the public Internet (either with a single IP address or by a shared pool of automatically assigned public addresses).

2. Concepts
There are two basic ways to create firewall rulesets: “inclusive” or “exclusive”. An exclusive firewall allows all traffic through, except for the traffic matching the ruleset. An inclusive firewall does the reverse. It only allows traffic matching the rules through, and blocks everything else. Inclusive firewalls are generally safer than exclusive firewalls because they significantly reduce the risk of allowing unwanted traffic to pass through the firewall. Security can be further tightened using a “stateful firewall”. This firewall keeps track of which connections are opened through the firewall, and will only allow traffic through which either matches an existing connection, or opens a new one. The disadvantage of a stateful firewall is that it can be vulnerable to Denial of Service (DoS) attacks if a lot of new connections are opened very quickly. It is generally possible to use a combination of stateful and non-stateful behavior to make an optimal firewall for a website. Many firewall packages are available for UNIX-flavored systems. IPFW is the easiest and most efficient IP-based firewall system currently running on FreeBSD OS.

3. IPFIREWALL (IPFW)
The IPFIREWALL (IPFW) is a FreeBSD-sponsored firewall software application, authored and maintained by FreeBSD volunteer staff members. It uses the legacy stateless rules and a legacy rule coding technique to achieve what is referred to as Simple Stateful logic. The IPFW sample rule set (found in /etc/rc.firewall) in the standard FreeBSD install is rather simple and it is not expected that it used directly without modifications. The example does not use stateful filtering, which is beneficial in most setups, so it will not be used as base for this section. The IPFW stateless rule syntax is empowered with technically sophisticated selection capabilities, which far surpass the knowledge level of the customary firewall installer. IPFW is targeted at professional users and at advanced technical computer hobbyists who have advanced packet selection requirements. A high degree of detailed knowledge into how different protocols use and create their unique packet header information is a prerequisite. Providing that level of explanation is out of the scope of this tutorial. IPFW is composed of seven components: 1. The primary component is the kernel firewall filter rule processor and its integrated packet accounting facility 2. The logging facility

Linux Servers Configuraton

72

3. The 'divert' rule which triggers the NAT facility
4. The advanced special purpose facilities 5. The dummynet traffic shaper facilities 6. The 'fwd rule' forward facility 7. The bridge facility 8. The ipstealth facility

3.1. Enabling IPFW
IPFW is included in the basic FreeBSD installation package as a separate run-time loadable module. The system dynamically loads the kernel module when the rc.conf statement firewall_enable="YES" is used. Do not compile IPFW into the FreeBSD kernel unless you want the NAT function enabled. After rebooting your system with firewall_enable="YES" in rc.conf the following message, highlighted in white, is displayed on the screen as part of the boot process: ipfw2 initialized, divert disabled, rule-based forwarding disabled, default to deny, logging disabled The loadable module already has logging ability compiled in it. To enable logging and set the verbose logging limit, there is a knob you can set in /etc/sysctl.conf by adding these statements; logging will be enabled on future reboots: net.inet.ip.fw.verbose=1 net.inet.ip.fw.verbose_limit=5 3.1.1. Kernel Options It is not a mandatory requirement to enable IPFW by compiling the following options into the FreeBSD kernel unless you need the NAT function. It is presented in this tutorial as background information: options IPFIREWALL

This option enables IPFW as part of the kernel. options IPFIREWALL_VERBOSE

Enables logging of packets that pass through IPFW and have the 'log' keyword specified in the rule set. options IPFIREWALL_VERBOSE_LIMIT=5

Limits the number of packets logged through syslogd on a per-entry basis. Use this option in hostile environments in which you want to log firewall activity. This will close a possible Denial of Service (DoS) attack via syslog flooding. options IPFIREWALL_DEFAULT_TO_ACCEPT

This option will allow everything to pass through the firewall by default, which is a good idea when you are first setting up your firewall. options options options options IPV6FIREWALL IPV6FIREWALL_VERBOSE IPV6FIREWALL_VERBOSE_LIMIT IPV6FIREWALL_DEFAULT_TO_ACCEPT

These options are exactly the same as the IPv4 options, but they are for IPv6. If you do not use IPv6, you might want to use IPV6FIREWALL without any rules to block all IPv6.

Open Source Software Training Toolkit

73

options

IPDIVERT

This enables the use of the NAT functionality. Note: If you do not include IPFIREWALL_DEFAULT_TO_ACCEPT or set your rules to allow incoming packets, you will block all packets going to, and from, your machine. 3.1.2. /etc/rc.conf Options If you do not have IPFW compiled into your kernel, you will need to load it with the following statement in /etc/rc.conf: firewall_enable="YES" Set the script to run to activate your rules: firewall_script="/etc/ipfw.rules" Enable logging: firewall_logging="YES"

3.2. The IPFW Command
The IPFW command is the normal vehicle for making manual single rule additions or deletions to the firewall’s active internal rules while it is running. The problem with using this method is, once your system is shutdown or halted, all the rules you added, changed, or deleted, are lost. Writing all your rules in a file, and using that file to load the rules at boot time, or to replace, en masse, the currently running firewall rules with changes you made to the file’s content, is the recommended method used here. The IPFW command is very useful to display the running firewall rules to the console screen. The IPFW accounting facility dynamically creates a counter for each rule that counts each packet that matches the rule. During the process of testing a rule, listing the rule with its counter is one of the ways of determining if the rule is functioning. To list all the rules in sequence: # ipfw list To list all the rules with a time stamp of when the last time the rule was matched: # ipfw -t list To list the accounting information, packet-count the matched rules along with the rules themselves. The first column is the rule number, followed by the number of outgoing matched packets, followed by the number of incoming matched packets, and then the rule itself: # ipfw -a list List the dynamic rules in addition to the static rules: # ipfw -d list Show the expired dynamic rules: # ipfw -d -e list Zero the counters: # ipfw zero Zero the counters for just rule NUM:

Linux Servers Configuraton

74

# ipfw zero NUM

3.3. IPFW Rule Sets
A rule set is a group of IPFW rules coded to allow or deny packets based on the values contained in the packet. The bi-directional exchange of packets between hosts comprises a session conversation. The firewall rule set processes the packet twice: once on its arrival from the public Internet host, and again as it leaves for its return trip back to the public Internet host. Each TCP/IP service (i.e. Telnet, www, mail, etc.) is pre-defined by its protocol, and by its port number. This is the basic selection criteria used to create rules which will allow or deny services. When a packet enters the firewall, it is compared against the first rule in the rule set. It then progresses one rule at a time, moving from top to bottom of the set in an ascending rule number sequence order. When the packet matches a rule selection’s parameters, the rules action field value is executed, and the search of the rule set terminates for that packet. This is referred to as “the first match wins” search method. If the packet does not match any of the rules, it gets caught by the mandatory IPFW default rule, number 65535, which denies all packets, and discards them, without any reply, back to the originating destination. The instructions contained here are based on using rules that contain the stateful 'keep state', 'limit', 'in'/'out', and ‘via’ options. This is the basic framework for coding an inclusive type firewall rule set. An inclusive firewall only allows those services to come through which match the rules. In this way, you can control which services can originate behind the firewall destined for the public Internet, and also control the services which can originate from the public Internet accessing your private network. Everything else is denied by the default design. Inclusive firewalls are much more secure than exclusive firewall rule sets, and are the only rule set type covered in this tutorial. 3.3.1. Rule Syntax The rule syntax presented here has been simplified to include only that which is necessary to create a standard inclusive type firewall rule set. Rules contain keywords; these keywords have to be coded in a specific order from left to right on the line. Keywords are identified in bold type. Some keywords have sub-options, which may be keywords themselves, and also include more sub-options. # is used to mark the start of a comment and may appear at the end of a rule line, or on its own lines. Blank lines are ignored. CMD RULE_NUMBER ACTION LOGGING SELECTION STATEFUL CMD Each new rule has to be prefixed with add to add the rule to the internal table. RULE_NUMBER Each rule has to have a rule number to go with it. ACTION A rule can be associated with one of the following actions, which will be executed when the packet matches the selection criterion of the rule. allow | accept | pass | permit All these words mean the same thing, which is to allow packets that match the rule to exit the firewall rule processing. The search terminates at this rule. check-state It checks the packet against the dynamic rules table. If a match is found, execute the action

Open Source Software Training Toolkit

75

associated with the rule which generated this dynamic rule, otherwise move onto the next rule. The check-state rule does not have a selection criterion. If no check-state rule is present in the rule set, the dynamic rules table is checked at the first keep-state or limit rule. deny | drop Both words mean the same thing, which is to discard packets that match this rule. The search terminates. LOGGING log or logamount When a packet matches a rule with the log keyword, a message will be logged to syslogd with a facility name of SECURITY. The logging only occurs if the number of packets logged so far for that particular rule does not exceed the logamount parameter. If no logamount is specified, the limit is taken from the sysctl variable net.inet.ip.fw.verbose_limit. In both cases, a value of zero removes the logging limit. Once the limit is reached, logging can be re-enabled by clearing the logging counter or the packet counter for that rule; see the IPFW reset log command. SELECTION The keywords described below are used to describe the attributes of the packet to be interrogated when determining whether the rules match the packet or not. The following general-purpose attributes are provided for matching, and must be used in this order: udp | tcp | icmp or any protocol names found in /etc/protocols are recognized and may be used. The value specified has a protocol to be matched against. This is a mandatory requirement. from src to dst The ‘from’ and ‘to’ keywords are used to match against IP addresses. Rules must specify both the source and the destination parameters. ‘any’ is a special keyword that matches any IP address. ‘me’ is a special keyword that matches any IP address configured on an interface in your FreeBSD system to represent the PC the firewall is running on (i.e. this box) as in 'from me to any' or 'from any to me' or 'from 0.0.0.0/0 to any' or 'from any to 0.0.0.0/0' or 'from 0.0.0.0 to any' or 'from any to 0.0.0.0' or 'from me to 0.0.0.0'. IP addresses are specified as a dotted IP address numeric form/mask-length, or as a single-dotted IP address numeric form. This is a mandatory requirement. port number For protocols which support port numbers (such as TCP and UDP). It is mandatory that you code the port number of the service you want to match it with. Service names (from /etc/services) may be used instead of numeric port values. in | out The keywords ‘in’ and ‘out’ match incoming or outgoing packets, respectively; it is mandatory that you code one or the other as part of your rule-matching criterion. via IF Matches packets going through an interface specified by an exact name. The ‘via’ keyword causes the interface to always be checked as part of the matching process. setup This is a mandatory keyword that identifies the session start request for TCP packets. keep-state

Linux Servers Configuraton

76

This is a mandatory keyword. Upon a match, the firewall will create a dynamic rule, whose default behavior is to match bi-directional traffic between the source and the destination IP/port using the same protocol. limit {src-addr | src-port | dst-addr | dst-port} The firewall will only allow N connections with the same set of parameters as specified in the rule. One or more of the source and destination addresses and ports can be specified. Both 'limit' and 'keep-state' cannot be used on the same rule. Also, ‘limit’ provides the same stateful function as 'keep-state', plus its own functions. STATEFULL Rule Option Stateful filtering treats traffic as a bi-directional exchange of packets comprising a session conversation. It has the interrogation abilities to determine if the session conversation between the originating sender and the destination are following the valid procedure of a bidirectional packet exchange. Any packets that improperly fit the session conversation template are automatically rejected as impostors. 'check-state' is used to identify where, in the IPFW rules set, the packet is to be tested against the dynamic rules facility. Upon finding a match, the packet exits the firewall to continue on its way, and a new rule is dynamically created for the next anticipated packet being exchanged during this bi-directional session conversation. Upon not matching, the packet advances to the next rule in the rule set for testing. The dynamic rules facility is vulnerable to resource depletion from a SYN-flood attack, which can open a huge number of dynamic rules. To counter this attack, FreeBSD Version 4.5 has added another new option known as ‘limit'. This option is used to limit the number of simultaneous session conversations by interrogating the rules source or destinations fields as directed by the limit option and using the packet's IP address found there, in a search of the open dynamic rules counting the number of times this rule and IP address combination occurred, if this count is greater that the value specified on the limit option, the packet is discarded. Logging Firewall Messages Logging provides the ability to review, after the fact, the rules you activated logging on. This provides information such as which packets had been dropped, which addresses they had come from, and where they were going. This process provides a significant edge in tracking down attackers. Even with the logging facility enabled, IPFW does not generate any rule-logging on its own. The firewall administrator decides which rules in the rule set require logging, and adds the log verb to those rules. Normally only deny rules are logged, like the deny rule for incoming ICMP pings. It is customary to duplicate the IPFW default deny everything rule, with the log verb included as the last rule in the rule set. This way, the administrator gets to see all the packets that did not match any of the rules in the rule set. Logging is a two-edged sword; if you are not careful, you can lose yourself in an overabundance of log data, and fill up your disk with growing log files. A DoS attack that fills up disk drives is one of the oldest attacks around. These log messages are not only written to syslogd, but are also displayed on the root console screen, and soon become very annoying. The IPFIREWALL_VERBOSE_LIMIT=5 kernel option limits the number of consecutive messages sent to the system logger syslogd concerning the packet-matching of a given rule. When this option is enabled in the kernel, the number of consecutive messages concerning a particular rule is capped at the number specified. There is nothing to be gained from 200 log messages saying the same thing. Five consecutive messages concerning a particular rule, for example, will be logged to syslogd, the remaining identical consecutive messages will be counted, and posted to syslogd with a phrase like this: last message repeated 45 times All logged packets’ messages are written by default to the /var/log/security file, which is

Open Source Software Training Toolkit

77

defined in the /etc/syslog.conf file.

3.4. Building a Rule Script
Most experienced IPFW users create a file containing the rules, and code them in a manner compatible with running them as a script. The major benefit of doing this is that the firewall rules can be refreshed en masse without the need to reboot the system to activate the new rules. This method is very convenient in testing new rules, as the procedure can be executed as many times as is necessary. Being a script, you can use symbolic substitution to code frequently used values and substitute them in multiple rules. Consider the following example. The script syntax used here is compatible with the 'sh', 'csh', 'tcsh' shells. Symbolic substitution fields are prefixed with a dollar sign $. Symbolic fields do not have the $ prefix. The value to populate the symbolic field must be enclosed in "double quotes". Start your rules’ file like this: ############### start of example ipfw rules script ############# # ipfw -q -f flush # Delete all rules # Set defaults oif="tun0" # out interface odns="192.0.2.11" # ISP's DNS server IP address cmd="ipfw -q add " # build rule prefix ks="keep-state" # just too lazy to key this each time $cmd 00500 check-state $cmd 00502 deny all from any to any frag $cmd 00501 deny tcp from any to any established $cmd 00600 allow tcp from any to any 80 out via $oif setup $ks $cmd 00610 allow tcp from any to $odns 53 out via $oif setup $ks $cmd 00611 allow udp from any to $odns 53 out via $oif $ks ################### End of example ipfw rules script ############ The rules are not important in this example; how the symbolic substitution field is populated and used is. If the above example is in the /etc/ipfw.rules file, you can reload these rules by typing: # sh /etc/ipfw.rules The /etc/ipfw.rules file can be located and named according to your preference. This can also be accomplished by running the following commands: # ipfw -q -f flush # ipfw -q add check-state # ipfw -q add deny all from any to any frag # ipfw -q add deny tcp from any to any established # ipfw -q add allow tcp from any to any 80 out via tun0 setup keep-state # ipfw -q add allow tcp from any to 192.0.2.11 53 out via tun0 setup keep-state # ipfw -q add 00611 allow udp from any to 192.0.2.11 53 out via tun0 keep-state

Stateful Ruleset The following non-NATed rule set is an example of how to code a very secure 'inclusive' type of firewall. An inclusive firewall only allows those services to pass through that match the rules, and blocks all other by default. All firewalls have a minimum of two interfaces, which have to have rules to allow the firewall to function.

Linux Servers Configuraton

78

All UNIX® flavored operating systems, FreeBSD included, are designed to use the interface lo0 and the IP address 127.0.0.1 for internal communication within an operating system. The firewall rules must contain rules to allow the free movement of these special, internally-used packets. The interface which faces the public Internet is the one which you code your rules to authorize and control access out to the public Internet and access requests arriving from the public Internet. This can be your ppp tun0 interface, or your NIC that is connected to your DSL or cable modem. In cases where one or more than one NIC is connected to a private LAN behind the firewall, the interfaces must have rules coded to allow the free movement of packets originating from those LAN interfaces. The rules should first be organized into three major sections: all the free interfaces; the public interface outbound, and the public interface inbound. The order of the rules in each of the public interface sections should be in order of the mostused rules being placed before less often-used rules, with the last rule in the section being a block log all packets on that interface and direction. The ‘Outbound’ section in the following rule set only contains 'allow' rules, which contain selection values that uniquely identify the service that is authorized for public Internet access. All the rules have proto, port, in/out, via and keep state option coded. The 'proto tcp' rules have the 'setup' option included to identify the start session request as the trigger packet to be posted to the keep state stateful table. The ‘Inbound’ section contains all the blocking of unwelcome packets for two different reasons. Firstly, the packets being blocked may be part of an otherwise valid packet, which may be allowed in by later authorized service rules. Secondly, this rule explicitly blocks selected packets that one receives on an infrequent basis, and does not want to see in the log. This keeps them from being caught by the last rule in the section, which blocks and logs all packets which have fallen through the rules. This last rule creates the legal evidence needed to prosecute the people who are attacking your system. No response is returned for any unwelcome material; their packets just get dropped and vanish. This way, the attacker has no knowledge of whether his or her packets have reached your system. The less the attackers can learn about your system, the more secure it is. When you log packets with port numbers you do not recognize, look the numbers up in /etc/services/ or go to http://www.securitystats.com/tools/portsearch.php and look up a port number to find what its purpose is. Visit http://www.simovits.com/trojans/trojans.html for port numbers used by Trojans. 3.4.1. A Sample Inclusive Rule set The following non-NATed rule set is a completely inclusive type rule set. Comment out any pass rules for services you do not want. If you see any unwelcome messages in your log, add a deny rule in the inbound section. Change the 'dc0' interface name in every rule to the interface name of the NIC that connects your system to the public Internet. For user ppp it would be 'tun0'. Observe a pattern in the usage of these rules: • All statements that are a request to start a session to the public Internet use ‘keepstate’. • All the authorized services that originate from the public Internet have the ‘limit’ option to stop flooding. • All rules use ‘in’ or ‘out’ to clarify direction. • All rules use the ‘via’ interface name to specify the interface the packet is travelling over. The following rules go into /etc/ipfw.rules. ################ Start of IPFW rules file ###############################

Open Source Software Training Toolkit

79

# Flush out the list before we begin. ipfw -q -f flush # Set rules command prefix cmd="ipfw -q add" pif="dc0" # public interface name of NIC # facing the public Internet ################################################################# # No restrictions on Inside LAN Interface for private network # Not needed unless you have LAN. # Change xl0 to your LAN NIC interface name ################################################################# #$cmd 00005 allow all from any to any via xl0 ################################################################# # No restrictions on Loopback Interface ################################################################# $cmd 00010 allow all from any to any via lo0 ################################################################# # Allow the packet through if it has previous been added to the # the "dynamic" rules table by a allow keep-state statement. ################################################################# $cmd 00015 check-state ################################################################# # Interface facing Public Internet (Outbound Section) # Interrogate session start requests originating from behind the # firewall on the private network or from this gateway server # destine for the public Internet. ################################################################# # Allow out access to my ISP's Domain name server. # x.x.x.x must be the IP address of your ISP.s DNS # Dup these lines if your ISP has more than one DNS server # Get the IP addresses from /etc/resolv.conf file $cmd 00110 allow tcp from any to x.x.x.x 53 out via $pif setup keep-state $cmd 00111 allow udp from any to x.x.x.x 53 out via $pif keep-state # Allow out access to my ISP's DHCP server for cable/DSL configurations. # This rule is not needed for .user ppp. connection to the public Internet. # so you can delete this whole group. # Use the following rule and check log for IP address. # Then put IP address in commented out rule & delete first rule $cmd 00120 allow log udp from any to any 67 out via $pif keep-state #$cmd 00120 allow udp from any to x.x.x.x 67 out via $pif keep-state # Allow out non-secure standard www function $cmd 00200 allow tcp from any to any 80 out via $pif setup keep-state # Allow out secure www function https over TLS SSL $cmd 00220 allow tcp from any to any 443 out via $pif setup keep-state # Allow out send & get email function $cmd 00230 allow tcp from any to any 25 out via $pif setup keep-state $cmd 00231 allow tcp from any to any 110 out via $pif setup keep-state # Allow out FBSD (make install & CVSUP) functions # Basically give user root "GOD" privileges. $cmd 00240 allow tcp from me to any out via $pif setup keep-state uid root

Linux Servers Configuraton

80

# Allow out ping $cmd 00250 allow icmp from any to any out via $pif keep-state # Allow out Time $cmd 00260 allow tcp from any to any 37 out via $pif setup keep-state # Allow out nntp news (i.e. news groups) $cmd 00270 allow tcp from any to any 119 out via $pif setup keep-state # Allow out secure FTP, Telnet, and SCP # This function is using SSH (secure shell) $cmd 00280 allow tcp from any to any 22 out via $pif setup keep-state # Allow out whois $cmd 00290 allow tcp from any to any 43 out via $pif setup keep-state # deny and log everything else that.s trying to get out. # This rule enforces the block all by default logic. $cmd 00299 deny log all from any to any out via $pif ################################################################# # Interface facing Public Internet (Inbound Section) # Interrogate packets originating from the public Internet # destine for this gateway server or the private network. ################################################################# # Deny all inbound traffic from non-routable reserved address spaces $cmd 00300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP $cmd 00301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP $cmd 00302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP $cmd 00303 deny all from 127.0.0.0/8 to any in via $pif #loopback $cmd 00304 deny all from 0.0.0.0/8 to any in via $pif #loopback $cmd 00305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config $cmd 00306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs $cmd 00307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster interconnect $cmd 00308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast # Deny public pings $cmd 00310 deny icmp from any to any in via $pif # Deny ident $cmd 00315 deny tcp from any to any 113 in via $pif # Deny all Netbios service. 137=name, 138=datagram, 139=session # Netbios is MS/Windows sharing services. # Block MS/Windows hosts2 name server requests 81 $cmd 00320 deny tcp from any to any 137 in via $pif $cmd 00321 deny tcp from any to any 138 in via $pif $cmd 00322 deny tcp from any to any 139 in via $pif $cmd 00323 deny tcp from any to any 81 in via $pif # Deny any late arriving packets $cmd 00330 deny all from any to any frag in via $pif # Deny ACK packets that did not match the dynamic rule table $cmd 00332 deny tcp from any to any established in via $pif # Allow traffic in from ISP's DHCP server. This rule must contain # the IP address of your ISP.s DHCP server as it.s the only # authorized source to send this packet type.

Open Source Software Training Toolkit

81

# Only necessary for cable or DSL configurations. # This rule is not needed for .user ppp. type connection to # the public Internet. This is the same IP address you captured # and used in the outbound section. #$cmd 00360 allow udp from any to x.x.x.x 67 in via $pif keep-state # Allow in standard www function because I have apache server $cmd 00400 allow tcp from any to me 80 in via $pif setup limit src-addr 2 # Allow in secure FTP, Telnet, and SCP from public Internet $cmd 00410 allow tcp from any to me 22 in via $pif setup limit src-addr 2 # Allow in non-secure Telnet session from public Internet # labeled non-secure because ID & PW are passed over public # Internet as clear text. # Delete this sample group if you do not have telnet server enabled. $cmd 00420 allow tcp from any to me 23 in via $pif setup limit src-addr 2 # Reject & Log all incoming connections from the outside $cmd 00499 deny log all from any to any in via $pif # Everything else is denied by default # deny and log all packets that fell through to see what they are $cmd 00999 deny log all from any to any ################ End of IPFW rules file ###############################

3.4.2. A Sample NAT and Stateful Rule set Some additional configuration statements need to be enabled in order to activate IPFW’s NAT function. The kernel source needs the 'option divert' statement to be added to the other IPFIREWALL statements, and compiled into a custom kernel. In addition to the normal IPFW options in /etc/rc.conf, the following are required: natd_enable="YES" natd_interface="rl0" natd_flags="-dynamic -m" # Enable NATD function # interface name of public Internet NIC # -m = preserve port numbers if possible

Utilizing stateful rules with the ‘divert natd’ rule (Network Address Translation) greatly complicates the rule set coding logic. The positioning of the ‘check-state’ and 'divert natd' rules in the rule set becomes very critical. This is no longer a simple fall-through logic flow. A new action type is used, called 'skipto'. To use the skipto command, it is mandatory that you number each rule so that you know exactly where the skipto rule number is you are really jumping to. The following is an uncommented example of one coding method, selected here to explain the sequence of the packet flow through the rule sets. The processing flow starts with the first rule from the top of the rule file, and its progress, one rule at a time, deeper into the file, until the end is reached, or the packet being tested to the selection criteria matches it, and the packet is released out of the firewall. It is important to take notice of the location of rule numbers 100, 101, 450, 500, and 510. These rules control the translation of the outbound and inbound packets, so their entries in the keep-state dynamic table always register the private LAN IP address. Allow and deny rules specify the direction in which the packet is going (outbound or inbound) and the interface. All the start outbound session requests skip to rule 500 for the network address translation. Suppose a LAN user uses his or her web browser to get a web page. Web pages communicate over port 80. The packet enters the firewall. It does not match rule 100 because it is headed out, not in. It passes rule 101 because this is the first packet, so it has not been

Linux Servers Configuraton

82

posted to the keep-state dynamic table yet. The packet finally comes to rule 125 and matches. It is outbound through the NIC facing the public Internet. The packet still retains its source IP address as a private LAN IP address. Upon matching with this rule, two actions take place. The keep-state option posts this rule into the keep-state dynamic rules table, and the specified action is executed. The action is part of the information posted to the dynamic table. In this case it is "skipto rule 500". Rule 500 NATs the packet IP address, and out it goes. This is very important. This packet makes its way to the destination and returns and enters the top of the rule set. This time it matches rule 100, and has its destination IP address mapped back to its corresponding LAN IP address. It is then processed by the check-state rule, found in the table as an existing session conversation, and released to the LAN. It goes to the LAN PC that sent it, and a new packet is sent, requesting another segment of the data from the remote server. This time it gets checked by the check-state rule, its outbound entry is found, and the associated action, 'skipto 500', is executed. The packet jumps to rule 500, gets NATed and is released on its way out. On the inbound side, everything coming in that is part of an existing session conversation is being automatically handled by the ‘check-state’ rule and the properly placed ‘divert natd’ rules. All you have to address is deny all the bad packets and only allow in the authorized services. Let us say there is an Apache server running on the firewall box, and you want people on the public Internet to be able to access the local website. The new inbound start request packet matches rule 100, and its IP address is mapped to the LAN IP for the firewall box. The packet is then matched against the unwelcome elements you want to check for, and finally matches against rule 425. Upon matching, two things happen. The packet rule is posted to the keep-state dynamic table, but this time, any new session request originating from that source IP address is limited to two. This defends against Denial of Service (DoS) attacks running on the specified port number. The action is allowed, and the packet is released to the LAN. On returning, the check-state rule recognizes the packet as belonging to an existing session conversation, sends it to rule 500 for NATing, and it is released to an outbound interface. Example Ruleset #1: #!/bin/sh cmd="ipfw -q add" skip="skipto 500" pif=rl0 ks="keep-state" good_tcpo="22,25,37,43,53,80,443,110,119" ipfw -q -f flush $cmd 002 allow all from any to any via xl0 # exclude LAN traffic $cmd 003 allow all from any to any via lo0 # exclude loopback traffic $cmd 100 divert natd ip from any to any in via $pif $cmd 101 check-state # Authorized outbound packets $cmd 120 $skip udp from any to xx.168.240.2 53 out via $pif $ks $cmd 121 $skip udp from any to xx.168.240.5 53 out via $pif $ks $cmd 125 $skip tcp from any to any $good_tcpo out via $pif setup $ks $cmd 130 $skip icmp from any to any out via $pif $ks $cmd 135 $skip udp from any to any 123 out via $pif $ks # Deny all inbound traffic from non-routable reserved address spaces $cmd 300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP $cmd 301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP $cmd 302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP $cmd 303 deny all from 127.0.0.0/8 to any in via $pif #loopback $cmd 304 deny all from 0.0.0.0/8 to any in via $pif #loopback $cmd 305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config

Open Source Software Training Toolkit

83

$cmd 306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs $cmd 307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster $cmd 308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast # Authorized inbound packets $cmd 400 allow udp from xx.70.207.54 to any 68 in $ks $cmd 420 allow tcp from any to me 80 in via $pif setup limit src-addr 1 $cmd 450 deny log ip from any to any # This is skipto location for outbound stateful rules $cmd 500 divert natd ip from any to any out via $pif $cmd 510 allow ip from any to any ######################## end of rules ################## The following is pretty much the same as above, but uses a self-documenting coding style full of description comments to help an inexperienced IPFW rule writer better understand what the rules are doing. Example Ruleset #2: #!/bin/sh ################ Start of IPFW rules file ############################### # Flush out the list before we begin. ipfw -q -f flush # Set rules command prefix cmd="ipfw -q add" skip="skipto 800" pif="rl0" # public interface name of NIC # facing the public Internet ################################################################# # No restrictions on Inside LAN Interface for private network # Change xl0 to your LAN NIC interface name ################################################################# $cmd 005 allow all from any to any via xl0 ################################################################# # No restrictions on Loopback Interface ################################################################# $cmd 010 allow all from any to any via lo0 ################################################################# # check if packet is inbound and nat address if it is ################################################################# $cmd 014 divert natd ip from any to any in via $pif ################################################################# # Allow the packet through if it has previous been added to the # the "dynamic" rules table by a allow keep-state statement. ################################################################# $cmd 015 check-state ################################################################# # Interface facing Public Internet (Outbound Section) # Interrogate session start requests originating from behind the # firewall on the private network or from this gateway server # destine for the public Internet.

Linux Servers Configuraton

84

################################################################# # Allow out access to my ISP's Domain name server. # x.x.x.x must be the IP address of your ISP's DNS # Dup these lines if your ISP has more than one DNS server # Get the IP addresses from /etc/resolv.conf file $cmd 020 $skip tcp from any to x.x.x.x 53 out via $pif setup keep-state # Allow out access to my ISP's DHCP server for cable/DSL configurations. $cmd 030 $skip udp from any to x.x.x.x 67 out via $pif keep-state # Allow out non-secure standard www function $cmd 040 $skip tcp from any to any 80 out via $pif setup keep-state # Allow out secure www function https over TLS SSL $cmd 050 $skip tcp from any to any 443 out via $pif setup keep-state # Allow out send & get email function $cmd 060 $skip tcp from any to any 25 out via $pif setup keep-state $cmd 061 $skip tcp from any to any 110 out via $pif setup keep-state # Allow out FreeBSD (make install & CVSUP) functions # Basically give user root "GOD" privileges. $cmd 070 $skip tcp from me to any out via $pif setup keep-state uid root # Allow out ping $cmd 080 $skip icmp from any to any out via $pif keep-state # Allow out Time $cmd 090 $skip tcp from any to any 37 out via $pif setup keep-state # Allow out nntp news (i.e. news groups) $cmd 100 $skip tcp from any to any 119 out via $pif setup keep-state # Allow out secure FTP, Telnet, and SCP # This function is using SSH (secure shell) $cmd 110 $skip tcp from any to any 22 out via $pif setup keep-state # Allow out whois $cmd 120 $skip tcp from any to any 43 out via $pif setup keep-state # Allow ntp time server $cmd 130 $skip udp from any to any 123 out via $pif keep-state ################################################################# # Interface facing Public Internet (Inbound Section) # Interrogate packets originating from the public Internet # destine for this gateway server or the private network. ################################################################# # Deny all inbound traffic from non-routable reserved address spaces $cmd 300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP $cmd 301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP $cmd 302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP $cmd 303 deny all from 127.0.0.0/8 to any in via $pif #loopback $cmd 304 deny all from 0.0.0.0/8 to any in via $pif #loopback $cmd 305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config $cmd 306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs $cmd 307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster $cmd 308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast

Open Source Software Training Toolkit

85

# Deny ident $cmd 315 deny tcp from any to any 113 in via $pif # Deny all Netbios service. 137=name, 138=datagram, 139=session # Netbios is MS/Windows sharing services. # Block MS/Windows hosts2 name server requests 81 $cmd 320 deny tcp from any to any 137 in via $pif $cmd 321 deny tcp from any to any 138 in via $pif $cmd 322 deny tcp from any to any 139 in via $pif $cmd 323 deny tcp from any to any 81 in via $pif # Deny any late arriving packets $cmd 330 deny all from any to any frag in via $pif # Deny ACK packets that did not match the dynamic rule table $cmd 332 deny tcp from any to any established in via $pif # Allow traffic in from ISP's DHCP server. This rule must contain # the IP address of your ISP's DHCP server as it's the only # authorized source to send this packet type. # Only necessary for cable or DSL configurations. # This rule is not needed for 'user ppp' type connection to # the public Internet. This is the same IP address you captured # and used in the outbound section. $cmd 360 allow udp from x.x.x.x to any 68 in via $pif keep-state # Allow in standard www function because I have Apache server $cmd 370 allow tcp from any to me 80 in via $pif setup limit src-addr 2 # Allow in secure FTP, Telnet, and SCP from public Internet $cmd 380 allow tcp from any to me 22 in via $pif setup limit src-addr 2 # Allow in non-secure Telnet session from public Internet # labeled non-secure because ID & PW are passed over public # Internet as clear text. # Delete this sample group if you do not have telnet server enabled. $cmd 390 allow tcp from any to me 23 in via $pif setup limit src-addr 2 # Reject & Log all unauthorized incoming connections from the public Internet $cmd 400 deny log all from any to any in via $pif # Reject & Log all unauthorized out going connections to the public Internet $cmd 450 deny log all from any to any out via $pif # This is skipto location for outbound stateful rules $cmd 800 divert natd ip from any to any out via $pif $cmd 801 allow ip from any to any # Everything else is denied by default # deny and log all packets that fell through to see what they are $cmd 999 deny log all from any to any ################ End of IPFW rules file ###############################

Linux Servers Configuraton

86

Asterisk
(VoIP)

Open Source Software Training Toolkit

87

1. Overview
Telephone communication has not changed radically since the telephone was invented in the late 1800s. New technologies like digital circuits, DTMF (or, "touch tone"), and caller ID have improved on this invention, of course, but its basic functionality still remains the same. Over the years, service providers made a number of innovative changes in order to improve the kinds and types of services offered to subscribers, including toll-free numbers, call-return, and call-forwarding, etc. By and large, users did not know how these services worked, but they did know two things: the same old telephone is used, and the service provider charges for every incremental service addition introduced. In the 1990s, a number of individuals in research environments, both in educational and in corporate institutions, began to take a serious interest in carrying voice and video over IP networks, especially over corporate Intranets and the Internet. This technology is commonly referred to today as Voice over Internet Phone (VoIP). It is the process of breaking up audio or video into small chunks, transmitting those chunks over an IP network, and reassembling those chunks at the far end so that two people can communicate using both audio and video. The idea of VoIP is certainly not new, as there are research papers and patents dating back several decades; and demonstrations of the concept have been given at various times over the years. VoIP took center stage with the "information super highway" (or, the Internet) concept that was popularized by former US Vice President Al Gore in the 1990s. It was envisioned that the Internet would make it possible to interconnect every home and every business with a packet-switched data network. Before Al Gore's effort to grow the Internet, the Internet was generally limited to use in academic environments only, but the possibility of mass deployment of the Internet sparked renewed interest in VoIP.

2. Introduction
Asterisk© is a Linux-based IPBX application developed by Mark Spencer of Digium™, the company behind Asterisk. Asterisk@Home© evolved from the core of Asterisk. It is made up of several major components. These were developed under the GNU General Public License (GPL), supported relatively by the users themselves. It consists of applications, a provisioning system, an installer, and an operating system that, together, constitute a complete package ready-for-use as an out-of-the-box PBX. For the purposes of this tutorial, the major components of Asterisk@Home© include: 1. 2. 3. 4. 5. Asterisk, the core PBX Flash Operator Panel, a screen-based operator’s console Asterisk Management Portal (AMP), a web-based provisioning tool for Asterisk A report system - that part of the AMP which provides CDR reporting tools A maintenance system, also a part of the AMP, which provides low-level interfaces to some components, and real-time system information 6. CentOS, a version of Linux related to Enterprise Linux (but without the branding and the support)

2.1. The Components
Two main components need to be set up: • • • An Asterisk-powered IP PBX The phones (or softphones) Network

2.1.1. The IP PBX A dedicated PC is needed in order to run an IP PBX. The PC described below is sufficient enough to power an IPBX in a small office environment: • • 600 Mhz Pentium III PC or better 256 MB RAM – minimum

Linux Servers Configuraton

88

• • • •

10 GB hard disk space - minimum 10/100 NIC CD-ROM Drive 10/100 4 or 8 ports Ethernet switch

2.1.2. Phones You can use soft phones as well as hard phones from Planet, and Cisco, etc. To get started, it is easiest to get a softphone, and run it on another computer. For details, see the section on how to install a softphone. 2.1.3. Network A static IP address is needed to run Asterisk on a network (e.g. 192.168.0.12).

3. Installation and Configurations
Download the ISO from http://sourceforge.net/projects/asteriskathome/ • Burn the downloaded ISO image onto a blank CD. Ensure that your PC will boot from the CD. If necessary, change the BIOS settings to reflect this. Warning: This will erase all the data on the hard drives of the PC. If you have two drives, both may be erased as well - beware. Boot your Asterisk PC with the CD in the CD drive, and press the “Enter” key.


• •

Press the “Enter” key to start the installation. It will take approximately 30 minutes for the installation to be complete ready for the configuration stage. During this stage, you will see screens similar to the following. Linux and the required files are being installed. Wait for the process to end.

Open Source Software Training Toolkit

89

After Linux is loaded, the CD will eject. Take the CD out, and wait for the system to reboot. You will then be presented with lines and lines of code. This process will take a while because it is building Asterisk.

Change Default Settings Once Asterisk@Home has been installed, some default system changes need to be made to Asterisk. Log in to your new Asterisk@Home box (user: root, password: password)

To get help, At the command-line, type: help-aah A help list will be displayed:

Linux Servers Configuraton

90

Change the Linux Password Note: Change your root password immediately by typing: passwd

Change some of the other default passwords as well; set your date, and the IP address of your box to a static address. Change the IP Address Change the Asterisk IP address from DHCP to static. At the command prompt, type: netconfig

Select [Yes] to set up networking, and hit the “Enter” key.

Open Source Software Training Toolkit

91

Use the “Tab” key to switch between various fields. Enter the IP address that is to be allocated to the Asterisk box, the Netmask (sub-net mask), Default Gateway and Primary nameserver, as per the example given above. Select “OK”, and reboot the system. Set Time Zone Set the correct time zone. The following examples depend on whether you are setting up AAH 1.x or AAH 2.x. For AAH 1.x type the following at the command-line: redhat-config-date You will get the screen on the left; choose an appropriate time zone. Check the system clock. Use UTC if you want to. Choose “OK” to complete the process.

Linux Servers Configuraton

92

For AAH 1.5 and 2.x, type the following at the command-line: config You will get the prompt as per the screen on the right. Press D. You will then be presented with the time zone screen. Choose your time zone to complete the process.

Log off Linux and reboot. Asterisk will now start with the new IP address.

4. Connect to AMP from a Web Browser
Connect to http://ipaddress/ (e.g. http:192.168.1.7) to configure Asterisk@Home. You will be presented with an Asterisk Management Portal (AMP) as illustrated below:

4.1 Logging into an Asterisk Management Portal (AMP)
To log in to an Asterisk Management Portal (AMP) use the user: maint, and the password: password, unless you have changed the password during the initial set up. Once you have logged into an AMP, you will be presented with the following screen:

Open Source Software Training Toolkit

93

Select the Setup tab and you will be presented with the following screen. This is where you start configuring Asterisk@Home. Notice the selection options on the left hand side. Selecting each option will display a configuration screen for that particular function e.g. creating new extensions, creating new trunks, etc.

4.2. General Settings
Select General Settings, and set them up as illustrated below:

Linux Servers Configuraton

94

Hover your mouse over the corresponding field description. An amber underline will display the purpose of the fields.

In the Asterisk Dial command option, customize your preferences regarding Asterisk’s “behavior”, e.g. if you want the caller to hear music instead of the standard ringing sound, replace the “r” with an “m”. For further options, hover your mouse over the label, and you will be informed about other options. After setting up the General Settings, click on the “Submit Changes” button, and the red bar on the top of the screen for the changes to take place.

4.3. Extensions
The number of extensions to be set up depends upon you. You can have soft phones installed in four or five computers, or have a mixture of ATAs and SIP SoftPhones. The following extension numbers should be avoided: 200 300-399 70-79 80-89 800-899 8000-8999 Park notify Reserved for speed-dial Reserved for call-on-hold Reserved for meet-me and conference Reserved for meet-me and conference Reserved for meet-me and conference

Open Source Software Training Toolkit

95

80000-89999 -

Reserved for meet-me and conference

Select the type of trunk e.g. SIP, IAX2, ZAP or Custom, from the Create Extension main menu illustrated below:

The AAH v2.x’s screen, where you actually create an extension, is given below:

Click on the “Add Extension” button to add more extensions, e.g. 201, 202, 2000 and 2001. Allocate the password in the numeric form. If you enabled Voicemail, allocate the same password as well. You may also nominate an e-mail address for Voicemail e-mail notification.

5. Setting the soft phone
Now that Asterisk is up, you need to setup up a soft phone. The following soft phones can be used with Asterisk:

1. Adore Softphone (SIP softphone) 2. DIAX softphone 3. eStara softphone 4. Express Talk (SIP softphone) 5. FireFly softphone 6. Iaxcomm softphone 7. IaxTeleFon softphone 8. Idefisk Manual (IAX2 softphone) 9. KIAX softphone 10. MediaX IAX2 softphone 11. Microsoft Windows Messenger 5.1 12. SIPPS softphone

Linux Servers Configuraton

96

13. SJphone softphone 14. SNOM360 softphone 15. X-Lite softphone 16. XtremePhone (ePhone)
We will use the BOL SIPPhone. It is extremely simple to set up for use with Asterisk, and it also features a call-forwarding facility. Obtain a copy of the BOL 2000 SIPPhone from http://www.bol2000.com/download/sipphone/ After downloading and set up, the following screen will be displayed when it runs:

5.1. Profile Tab
This is the only screen that is required to be filled in. Account: <enter the extension number e.g. 201> Password: <enter the password e.g. 201>

Domain/Realm: <leave it blank> Proxy: Your Asterisk network address e.g. 192.168.1.7 Port: 5060

Open Source Software Training Toolkit

97

Check the Auto Login and Keep Password. Click OK.

5.2. Audio and Video Tab
Click on the “Audio & Video” tab to ensure that the audio properties set is consistent with the audio card installed in your PC/Notebook.

• • •

Click on the Tuning Wizard to tune your audio input and output. Check Auto Send Video, if you are using video. Check it anyway. Check Auto Receive Video, if you are using video. Check it anyway.

Click OK.

5.3. Network Tab
Ensure that your Internet Connection Type is set to LAN.

Ignore the “Information of Network” field. Click OK.

5.4. Call-forwarding
To forward an unanswered call to an extension, click on the “Call Forward” tab, and enter the telephone number you want to forward your incoming calls to. You have three options of callforwarding – Always On, Busy, or No Answer. This facility is only available, however, if your PC is on, and the softphone is active. Click OK.

Linux Servers Configuraton

98

You might want to set-up a couple of PCs with the softphone, after which you can start testing your new phone system by dialing each extension in turn. If you use one of the softphones and dial 7777, Asterisk will simulate an incoming call. Once done, test your softphone connection to Asterisk. To check if Asterisk is running Click on the “System Status” tab. You will be presented with the following screen:

5.5. Flash Operator Panel (FOP)
The Flash Operator Panel is a switchboard-type application for the Asterisk PBX. It runs on a web browser with the Flash plug-in. It is able to display information about your PBX activity in real-time. The layout is configurable (button sizes and colors, icons, etc). You can have more than 100 buttons active per screen. It also supports contexts: you can have one server running, and many different client displays (for hosted PBX, different departments, etc). It can integrate with CRM software, by popping up a web page (and passing the CLID) when a specified button is ringing.

The following information is displayed on the FOP: • • • • Which extensions are busy, ringing, or available Who is talking and to whom (CLID, context, priority) SIP and IAX registration, and reach status Queue status (the number of waiting users)

Open Source Software Training Toolkit

99

• • •

Message Waiting Indicator and count Parked channels Logged-in agents

Functions you can perform on FOP: • • • • • • • Hang-up a channel Using drag-and-drop to transfer a call Initiate calls by drag-and-drop Barge in on a call using drag-and-drop Set the caller ID when transferring or originating a call Automatically pop-up a web page with customer details Click-to-dial from a web page

Linux Servers Configuraton

100