Setting Linux Server Bagian I
Setting Linux Server Bagian I
Sistem operasi linux memang keren kalo dimanfaatkan untuk kepentingan jaringan dan security.
Pada artikel ini saya akan membocorkan sedikit. dan mungkin artikel ini sudah basi di internet
tapi gk ada salahnya saya ikut-ikutan basi. gk apa-apa basi kalo bisa bermanfaat bagi mereka
yang masih newbie dalam menggunakan linux sebagai server. Pada bahasan kali ini, saya akan
menjelaskan tentang bagai mana mengeset linux server sebagai router ‘asal bisa konek’ dulu.
masalah setting server yang lain dan masalah security akan saya bahas pada artikel berikutnya.
Ok. skenarionya begini…. perusahaan saya ato warnet saya berlangganan kepada ISP dan sang
ISP memberikan data seperti di bawah ini :
IP addresss : 202.169.234.159 / 24
IP gateway ISP : 202.169.234.1
IP DNS 1 : 202.169.224.3
IP DNS 2 : 202.169.224.4
IP DNS 3 : 202.169.224.11
data - data di atas tadi saya dapatkan dari ISP tempat perusahaan saya berlangganan.
kemudian saya menginstall sebuah komputer dengan Sistem Operasi Linux Redhat9 dengan
memasangkan 2 buah Ethernet Card. sebut saja linux memberikan nama Ethernet Card tersebut
dengan nama eth0 untuk Ethernet ke 0 dan eth1 untuk ethernet yang ke 1.
kemudian di kantor saya ada komputer lain yang terhubung jaringan komputer juga dengan
mengunakan IP lokal. kira - kira datanya seperti ini
nah.. saya ingin supaya semua komputer yang ada di kantor saya ato warnet saya bisa menikmati
koneksi internet. nah.. itulah yang akan saya bahas sekarang
Linux server akan mempunyai dua buah IP address. IP address pubic yang dari ISP, yang akan
dipasangkan pada eth1 dan IP address Lokal yang sama net IDnya sama dengan komputer lain di
kantor saya yang akan dipasangkan pada eth0
Setting IP
setting di atas untuk memberikan ip 192.168.0.1 eth0. langkah selanjutnya adalah memberikan
eth1 dengan ip public yang didapatkan dari ISP
Setting ip untuk setiap ethernet, disimpan pada masing - masing file yang terpisah. ini pada
sistem operasi linux redhat 9. dan berbeda dengan distro yang lain. seperti slackware, hanya satu
file saja. karena dari awal saya membahas redhat9, mari kita lanjutkan kembali dengan RedHat9.
setting IP untuk eth0 disimpan di file
/etc/sysconfig/network-scripts/ifcfg-eth0
silahkan edit file tadi dengan editor kesayangan anda :
DEVICE=eth0
BOOTPROTO=static
IPADDR=192.168.0.1
NETMASK=255.255.255.0
ONBOOT=yes
NETWORK=192.168.0.0
parameter yang perlu diperhatikan adalah DEVICE yang diisikan sesuai dengan nama device.
yaitu eth0. dan IP address. dan jangan lupa ONBOOT=yes juga penting supaya konfigurasi ini
direload ketika komputer restart
DEVICE=eth1
BOOTPROTO=static
ONBOOT=yes
IPADDR=202.169.234.159
NETMASK=255.255.255.0
USERCTL=no
PEERDNS=no
GATEWAY=202.169.234.1
TYPE=Ethernet
NETWORK=202.169.234.0
BROADCAST=202.169.234.255
hmm….. ya..kira - kira dari settingan tadi, bisalah dimengerti maksudnya apa. loh…. koq yang
eth1 lebih banyak sih ? lah gak apa apa kan ?. yang eth0 tidak saya copy kan semua. hanya yang
penting2 saja. tapi di eth1, ada satu lagi yang penting yaitu GATEWAY=202.169.234.1 artinya,
di eth1, saya mendefinisikan IP gateway ke alamat gateway ISP.
wah wah wah .. apa itu.. biasa aja lagi… perhatikan saja. ada beberapa blok yaitu eth0, eth1 dah
lo. eth0 itu itu untuk konfigurasi eth0, eth1 untuk eth1 dan lo adalah untuk loopback. loopback
pasti akan ada. jadi gk usah di pusingkan… yang penting pada masing2 blok(eth0 dan
eth1),perhatikan pada bagian inet addr . pastikan isinya sesuai dengan konfigurasi yang kita
maksudkan.
nameserver 202.169.224.3
nameserver 202.169.224.4
nameserver 202.169.224.11
ROUTING
routing ? apaan tuh… gampangnya gini aja deh… ceritanya komputer linux yang sedang saya
Konfigurasi ini akan jadi gerbang buat komputer lain yang di kantor saya untuk bisa koneksi ke
internet. kenapa demikian ? ya karena kantor saya menyewa cuman 1 IP public. sedangkan ada
banyak komputer. jadi IP public yang cuman 1 ini dimanfaatkan ato dibagi-bagiakan ke
komputer yang lain di kantor saya. nah.. begitu ceritanya. sekarang pertanyaannya adalah apakah
komputer linux yang sekarang lagi saya konfigurasi ini sudah menjalankan tugasnya untuk
routing atau belum ? ato istilah kerennya ip forwarding dah aktif ato blum?. kita bisa check
dengan melihat isi file /proc/sys/net/ipv4/ip_forward . lengkaplnya begini perintahnya
#cat /proc/sys/net/ipv4/ip_forward
Jika hasilnya adalah 0, maka fungsi ip forwarding belum dijalankan. Ini adalah default dari
Linux Redhat. kemudian kita harus menulikan angka 1 ke dalam file tadi. Caranya seperti ini :
TAPI…. lagi - lagi ini bersifat temporer/ sementara. Karena file terserbut akan diset kembali ke 0
ketika komputer restart ato network direstart. Trus ? ya.. supaya terus bernilai 1, bisa dengan
menambahkan script yang tadi (mengeset atau menulis angka 1) di startup script ato dengan cara
mengedit file : /etc/sysctl.conf
net.ipv4.ip_forward = 1
Untuk melihat routing table yang sudah ada, bisa dilakukan dengan perintah seperti ini :
# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
202.169.234.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
0.0.0.0 202.169.234.1 0.0.0.0 UG 0 0 0 eth1
jika hasilnya sudah serperti di atas, maka gk perlu menambahkan lagi. berarti sudah beres. Jika
bermaksud menambahkan lagi ato belum ada, bisa dilakukan dengan perintah sebagai berikut :
IP public adalah IP yang digunakan di internet. Gak boleh sembarangan menggunakan IP ini
karena sudah ada penjatahan dari badan khusus. misalnya di wilayah Asia ada namanya IDNIC
yang mengatur pembagian IP.
IP Private adalah IP yang digunakan di dalam area lokal saja. dan IP ini sudah disepakati tidak
akan digunakan di Internet. Dengan konsekweksi, gk bisa langsung koneksi ke internet secara
langsung dengan IP ini. harus ‘bersembunyi’ di belakang IP Public. COntoh IP Private
Kantor saya cukup memiliki 1 IP Public saja. nah. .. tugas linux server yang kita konfigurasi ini,
mengganti IP komputer kantor yang menggunakan IP lokal menjadi IP Public ketika mau
mengakses sistus di internet. mekanisme ini disebut dengan
mentranslate/menerjemahkan/mengganti IP ato istilah kerennya adalah NETWORK ADDRESS
TRANSLATION (NAT). Untuk melakukan NAT, kita membutuhkan sebuah program tambahan
yang sudah ada di linux redhat. namanya IPTABLES
jadi ceritanya begini. dengan menggunakan IPTABLES, kita mengganti ip apa saja yang dari
jaringan lokal, yang keluar melewati interface eth1 ato dalam baris perintah di atas
disimbolkan dengan -o eth1 menerapkan sebuah policy atau disimbolkan dengan -j dengan
kebijakan SNAT (SOURCE NAT). diganti menjadi IP public 202.169.234.159. dan jangan lupa
disimpan dengan perintah :
#iptables-save
Untuk sementara ini, bisa dikatakan server sudah beres. sudah bisa digunakan oleh komputer lain
untuk koneksi ke internet. Tapi ini belum selesai. karena masih ada yang belum. yang InsyaAllah
akan saya lanjutkan pada artikel berikutnya
KONFIGURASI KLIENT
untuk konfiguras klient, cukup sedernaha sekali, tinggal buka properti network card, kemudian
set ip address yang satu net ID dengan ip server linux. dan gateaway ke ip address server linux:
berikut adalah data- data lengkapnya :
IP Address : 192.168.1.2
Gateway : 192.168.1.1
DNS : 202.169.234.3
DNS : 202.169.234.4
Untuk sementara DNS masih harus ke DNS public. sebenarnya linux server bisa diinstallkan
DNS server tetapi hanya sebagai Chace DNS. Untuk sementara ini dulu ya ? saya akan lanjutkan
dengan bahasan selanjutnya yang lebih menarik tentunya.
Setting Up a Server
So it will be assumed that the idea is to host websites that use certain technologies such as a scripting
language and a database (for dynamic sites), and also to act as a mailing tool, for sending and receiving
email.
Consider that this article only shows some of the basic features for configuring these services,
each program has much more in depth options. Entire books have been written just about Apache
or MySQL. So, don't just stay with what you learn here, play around, read, learn; system
administration is all about security and performance, so there's a lot more to discover.
I have also decided to show some optimization (tuning) techniques for a better performance. We
will use only free/open source software in this article, thus,it is not necessary to buy commercial
licenses. The software we will use is Debian GNU/Linux, Apache, MySQL, PHP and Postfix.
The first three are what is called LAMP, where the P can stand for various server side scripting
languages such as PHP, Perl and Python. In general, it represents the open source web platform
(both for developing and using it). I have been using LAMP and Postfix for years and must say
that, after trying lots of other programs of the same sort, it is the wisest choice if you want a
powerful, easy to use/configure/maintain and secure server environment.
Why use Debian? I have always liked this distribution because it's easy to manage packages
(programs) and system services. It is also very secure and stable, making it perfect for servers
and any system that must run 24/7. It's huge package repository (over 15490) is more than
enough to get the best use out of any computer system.
Why use Apache? Simple - it's currently the best, most secure and most used HTTP server. It
also supports a huge amount of modules and extensions. Here are some specific benefits of
Apache: support, efficiency, portability and customizability.
Why use MySQL? It's logo says it all: The world's most popular open source database. This
DBMS is reliable, powerful and easy to manage and use. Also, we will use it with Postfix for
better integration and performance.
Why use Postfix? If you ask any systems administrator why he/she uses Postfix as a Mail
Transport Agent (MTA) the answer will be it's easy and fast. Another great feature is it's security
and the wide amount of operating systems it can run on (BSD, Linux, AIX, Solaris, OSX, etc.)
/etc/init.d/apache2 start|stop|restart|reload|force-reload
apacheclt start|stop|restart|...
apache2.conf is where the main configuration is, it used to be httpd.conf, so don't be fooled.
mods-available/ is the directory with all the modules that are available. The .load contain the
Apache directives that are needed to load the modules. And the .conf are the configuration
directives for each module.
mods-enabled/ is the directory that contains the symbolic links to the modules that we want to
enable from mod-available/. At least the .load file must be there, so we will have:
/etc/apache2/mod-enabled/modulex.load -> /etc/apache2/mod-available/modulex.load
Next, we create the symbolic links for this module and restart the server:
cd /etc/apache2
ln -s mods-available/userdir.* /etc/apache2/mods-enabled/
/etc/init.d/apache restart
This works for all the modules you want to load. Now let's try some optimization methods.
Apache uses a great deal of resources, specially RAM, because it accumulates whatever is
necessary to accommodate what it's serving and this process never decreases until it is complete.
This takes up as much RAM as the largest dynamic script.
To help reduce this problem, edit apache2.conf and enable KeepAlive (increases time) and set a
low value for KeepAliveTimout (this will reduce the time the process waits without doing
anything). Also, set the value for MaxRequestsPerChild around 20, depending on the amount of
dynamic sites the server is hosting. The idea behind this is that when the process ends, it makes it
start over again, but with lower RAM usage. However, by doing this, you might have to increase
MaxClients around 50%.
/etc/init.d/mysql start|stop|restart|reload|force-reload|status
To first start working with this database, the root password must be set. The word root does not
apply to the system's root, but to the database administrator, however, it can be the same person.
So let's set it and log in:
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
mysql>
If you don't like using the command line system (lazy sysadmins), there a couple graphical user
interfaces for MySQL, such as MySQLCC (QT), gMySQLCC (GTK+), etc. Since everything is
running fine (or should be) it's time to optimize. MySQL uses algorithms that let you run it with
little memory, but you can give it options to increase the memory usage if you have more, and
therefore increase performance. To lower the amount of time MySQL sits waiting, edit the
configuration file: /etc/mysql/my.cnf and add/change the following (values may vary depending
on your specific needs):
wait_timeout=60
connect_timeout=10
interactive_timeout=100
join_buffer_size=1M
query_cache_size=128M
query_cache_limit=2M
max_allowed_packet=16M
table_cache=1024
Just like for Apache and MySQL, extra packages will have to be install as well: apache2-mpm-
prefork, libapache2-mod-php5 and php5-common.
I also like to add some more packages for PHP, such as CLI, Pear, LDAP, IMAP, GD, mhash,
ODBC and PostScript:
The configuration file for PHP is located in /etc/php5/apache2/php.ini, every time you modify it,
Apache must be restarted. So let's see if everything is working. First let's create a simple script,
called information.php, in Apache's DocumentRoot, that is /var/www/information.php and inside
it should go:
Now, fireup a browser and open www.mycompany.com/information.php. You should see a page
with information about the PHP version that is installed. Also it provides some details about
Apache, and all the PHP modules. Last, but not least, let's make sure MySQL and PHP are
working well together. First, log in to MySQL and create a new database:
mysql> exit
Bye
'
Create a new file, db.php, in the same directory and write:
<?
if(mysql_connect("localhost", "root", "rootpassword"))
echo("connection success");
?>
Check your browser and you should see: connection success. Now for a little optimization.
Usually compiling PHP scripts on the fly uses a lot of memory, so if your hosting several big
web sites and have lots of users visiting, you might want to do something about this resource
abuse. The solution is to use a program that keeps the scripts precompiled. The most popular
include Zend Accelerator, Turck MMCache and PHP Accelerator. Performance can increase up
to 200%.
Finally LAMP is up, running and optimized. You can also provide further services, such as more
databases (PosgreSQL, Oracle, Informix, etc) and more server side languages (Perl, JSP, Python,
etc).
Leave the values dpkg suggests when configuring. The default configuration files are in
/etc/postfix, we will only use main.cf. Once done, we create the postfix user for MySQL and the
database for the emails:
mysql -A -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 4 to server version: 5.0.20a-Debian_2-log
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 3 to server version: 5.0.20a-Debian_2-log
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
The next step is configuring Postfix to support MySQL, so edit the configuration file and add:
transport_maps=mysql:/etc/postfix/transport.cf
virtual_mailbox_base=/home/postfix
virtual_uid_maps=mysql:/etc/postfix/ids.cf
virtual_gid_maps=mysql:/etc/postfix/ids.cf
virtual_mailbox_maps=mysql:/etc/postfix/aliases.cf
virtual_maps=mysql:/etc/postfix/remote_aliases.cf
Since we are specifying files that don't exist, we must create them. In transport.cf write:
user=postfix
password=thepostfixpass # the password used in MySQL
dbname=mail
table=transport
select_field=transport
where_field=domain
hosts=localhost
user=postfix
password=thepostfixpass # the password used in MySQL
dbname=mail
table=aliases
select_field=maildir
where_field=alias
hosts=localhost
In ids.cf:
user=postfix
password=thepostfixpass # the password used in MySQL
dbname=mail
table=aliases
select_field=id
where_field=alias
hosts=localhost
user=postfix
password=thepostfixpass # the password used in MySQL
dbname=mail
table=remote_aliases
select_field=rcpt
where_field=alias
hosts=localhost
Lets now create the information for the domain1 example in MySQL:
mysql -A -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 8 to server version: 5.0.20a-Debian_2-log
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
To add users to that domain, simply insert into the aliases table the data (you can get postfix's
userid from /etc/passwd, for example:
This tutorial assumes that a computer has Linux installed and running. See RedHat Installation
for the basics. A connection to the internet is also assumed. A connection of 128 Mbits/sec or
greater will yield the best results. ISDN, DSL, cable modem or better are all suitable. A 56k
modem will work but the results will be mediocre at best. The tasks must also be performed with
the root user login and password.
No single distribution seems to have an advantage. A Ubuntu, SuSe, Fedora, Red Hat or CentOS
distribution will include all of the software you will need to configure a web server. If using Red
Hat Enterprise Linux, both the Workstation or the Server edition will support your needs except
that the Workstation edition will not include the vsFTP package. It will have to be compiled
from source or use sftp.
Software Prerequisites: The Apache web server (httpd), FTP (requires xinetd or inetd) and
Bind (named) software packages with their dependencies are all required. One can use the rpm
command to verify installation:
A Red Hat 8.0 wu-ftpd RPM may be installed (Newer version 2.6.2 or later with security fix wu-
ftpd-2.6.2-11+) or install from source.
Note: The apache2-MPM is a generic term for Apache installation options for "Multi-Processing
Modules (MPM)s "prefork" or "worker". If you try and only install apache2 you will get the
following error:
One should also have a working knowledge of the Linux init process so that these services are
initiated upon system boot. See the YoLinux init process tutorial for more info.
This tutorial is for the Apache HTTP web server (Version 1.3 and 2.0). See the YoLinux list of
Linux HTTP servers for a list of other web servers for the Hyper Text Transport Protocol.
Web pages are served from the directory as configured by the DocumentRoot directive. The
default directory location is:
Red Hat 7.x-9, Fedora Core, Red Hat Enterprise 4/5, CentOS 4/5 /var/www/html/
Apache may be configured to run as a host for one web site in this fashion or it may be
configured to serve for multiple domains. Serving for multiple domains may be achieved in two
ways:
Virtual hosts: One IP address but multiple domains - "Name based" virtual hosting.
Multiple IP based virtual hosts: One IP address for each domain - "IP based" virtual hosting.
The default configuration will allow one to have multiple user accounts under one domain by using a
reference to the user account: http://www.domain.com/~user1/. If no domain is registered or
configured, the IP address may also be used: http://XXX.XXX.XXX.XXX/~user1/.
[Potential Pitfall] The default umask for directory creation is correct by default but if not use:
chmod 755 /home/user1/public_html
[Potential Pitfall] When creating new "Directory" configuration directives, I found that placing
them by the existing "Directory" directives to be a bad idea. It would not use the .htaccess
file. This was because the statement defining the use of the .htaccess file was after the
"Directory" statement. Previously in RH 6.x the files were separated and the order was defined
a little different. I now place new "Directory" statements near the end of the file just before the
"VirtualHost" statements.
For users of Red Hat 7.1, the GUI configuration tool apacheconf was introduced for the crowd
who like to use pretty point and click tools.
Start/stop/restart script:
o Red Hat/Fedora/CentOS: /etc/rc.d/init.d/httpd
o SuSE: /etc/apache2/httpd.conf
(Need to add directive: ServerName host-name)
o Ubuntu (dapper 6.06/hardy 8.04) / Debian: /etc/apache2/apache2.conf
o SuSE: /etc/apache2/conf.d/component.conf
Start/Stop/Restart scripts: The script is to be run with the qualifiers start, stop, restart or
status.
i.e. /etc/rc.d/init.d/httpd restart. A restart allows the web server to start again and read
the configuration files to pick up any changes. To have this script invoked upon system boot
issue the command chkconfig --add httpd. See Linux Init Process Tutorial for a more
complete discussion.
Directive Description
start Start the Apache httpd daemon. Gives an error if it is already running.
graceful Gracefully restarts the Apache httpd daemon. If the daemon is not running, it is
started. This differs from a normal restart in that currently open connections are not
aborted.
restart Restarts the Apache httpd daemon. If the daemon is not running, it is started. This
command automatically checks the configuration files as in configtest before initiating
the restart to make sure the daemon doesn't die.
fullstatus Displays a full status report from mod_status. Requires mod_status enabled on your
server and a text-based browser such as lynx available on your system. The URL used
to access the status report can be set by editing the STATUSURL variable in the script.
Giving Apache access to the file system: It is prudent to limit Apache's view of the file system
to only those directories necessary. This is done with the directory statement. Start by denying
access to everything, then grant access to the necessary directories.
<Directory />
Options None
AllowOverride None
</Directory>
Set default location of system web pages and allow access: (Red Hat/Fedora/CentOS)
DocumentRoot "/var/www/html"
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
Enabling Red Hat / Fedora Linux, Apache public_html user directory access:
This will allow users to serve content from their home directories under the subdirectory
"/home/userid/public_html/" by accessing the URL http://hostname/~userid/
File: /etc/httpd/conf/httpd.conf
...
...
<IfModule mod_userdir.c>
#UserDir disable - Add comment to this line
#
# To enable requests to /~user/ to serve the user's public_html
# directory, remove the "UserDir disable" line above, and uncomment
# the following line instead:
UserDir public_html # Uncomment this line
</IfModule>
...
...
<Directory /home/*/public_html>
AllowOverride FileInfo AuthConfig Limit
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
<Limit GET POST OPTIONS>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>
Change to a comment (add "#" at beginning of line) from Fedora Core default UserDir
disable and assign the directory public_html as a web server accessible directory.
OR
Assign a single user the specific ability to share their directory:
<Directory /home/user1/public_html>
AllowOverride None
order allow,deny
allow from all
Options Indexes Includes FollowSymLinks
</Directory>
Allows the specific user, "user1" only, the ability to serve the directory
/home/user1/public_html/
Also use SELinux command to set the security context: setsebool httpd_enable_homedirs
true
Directory permissions: The Apache web server daemon must be able to read your web
pages in order to feed their contents to the network. Use an appropriate umask and file
protection. Allow access to web directory: chmod ugo+rx -R public_html.
Note that the user's directory also has to have the appropriate permissions as it is the
parent of public_html.
Default permissions on user directory: ls -l /home
drwx------ 20 user1 user1 4096 Mar 5 12:16 user1
Allow the web server access to operate the parent directory: chmod ugo+x /home/user1
d-wx--x--x 20 user1 user1 4096 Mar 5 12:16 user1
One may also use groups to control permisions. See the YoLinux tutorial on managing
groups.
Ubuntu has broken out the Apache loadable module directives into the directory
/etc/apache2/mods-available/. To enable an Apache module, generate soft links to
the directory /etc/apache2/sites-enabled/ by using the commands
a2enmod/a2dismod to enable/disable Apache modules.
Example:
o [root@node2]# a2enmod
A list of available modules is displayed. Enter "userdir" as the module to enable.
o Restart Apache with the following command: /etc/init.d/apache2 force-
reload
Note: This is the same as manually generating the following two soft links:
o ln -s /etc/apache2/mods-available/userdir.conf /etc/apache2/mods-
enabled/userdir.conf
o ln -s /etc/apache2/mods-available/userdir.load /etc/apache2/mods-
enabled/userdir.load
You must allow the web server running as user "apache" to access the directory if it is to display
pages held there.
Fix with command: chmod ugo+rx /home/userx
Fedora Core 3 and Red Hat Enterprise Linux 4 introduced SELinux (Security Enhanced Linux)
security policies and context labels.
To view the security context labels applied to your web page files use the command: ls -Z
SELINUX=disabled
or using the command setenforce 0 to temporarily disable SELinux until the next reboot.
When using SELinux security features, the security context labels must be added so that
Apache can read your files. The default security context label used is inherited from the
directory for newly created files. Thus a copy (cp) must be used and not a move (mv)
when placing files in the content directory. Move does not create a new file and thus the
file does not recieve the directory security context label. The context labels used for the
default Apache directories can be viewed with the command: ls -Z /var/www
The web directories of users (i.e. public_html) should be set with the appropriate
context label (httpd_sys_content_t).
-R: Recursive. Files and directories in current directory and all subdirectories.
-h: Affect symbolic links.
httpd_sys_content_t Used for static web content. i.e. HTML web pages.
Policy Description
Red Hat/Fedora/Suse and all System V init script based Linux systems:
/etc/init.d/httpd restart
Red Hat/Fedora: service httpd restart
Virtual Hosts:
The Apache web server allows one to configure a single computer to represent multiple websites as if
they were on separate hosts. There are two methods available and we describe the configuration of
each. Choose one method for your domain:
Name based virtual host: (most common) A single computer with a single IP adress supporting
multiple web domains. The web browser using the http protocol, identifies the domain being
addressed.
IP based virtual host: The virtual hosts can be configured as a single multi-homed computer with
multiple IP addresses on a single network card, with each IP address representing a different
web domain. This has the appearance of a web domain supported by a dedicated computer
because it has a dedicated IP address.
A virtual host configuration allows one to host multiple web site domains on one server. (This is
not required for a dedicated linux server which hosts a single web site.)
NameVirtualHost XXX.XXX.XXX.XXX
<VirtualHost XXX.XXX.XXX.XXX>
ServerName www.your-domain.com - CNAME (bind DNS alias www)
specified in Bind configuration file (/var/named/...)
ServerAlias your-domain.com - Allows requests by domain name
without the "www" prefix.
ServerAdmin [email protected]
DocumentRoot /home/user1/public_html
ErrorLog logs/your-domain.com-error_log
TransferLog logs/your-domain.com-access_log
</VirtualHost>
Notes:
You can specify more than one IP address. i.e. if web server is also being used as a
firewall/gateway and you have an external internet IP address as well as a local network
IP address.
NameVirtualHost XXX.XXX.XXX.XXX
NameVirtualHost 192.168.XXX.XXX
See the YoLinux Tutorial on configuring a network gateway/firewall using iptables and
NAT.
Use your IP address for XXX.XXX.XXX.XXX, actual domain name and e-mail address.
One can use DNS views to provide different local network DNS results.
Note that I configure Apache for both requests http://www.domain-name.com and
http://domain-name.com.
Once virtual hosts are configured, your default system domain ( /var/www/html) will
stop working. Your default domain now must be configured as a virtual domain.
<Directory "/var/www/html">
</Directory>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot /var/www/html
ErrorLog logs/error_log
TransferLog logs/access_log
</VirtualHost>
# Add a VirtualHost definition for your domain which was once the system
default.
<VirtualHost XXX.XXX.XXX.XXX>
ServerName www.your-domain.com
ServerAlias your-domain.com
ServerAdmin [email protected]
DocumentRoot /var/www/html
ErrorLog logs/error_log
TransferLog logs/access_log
</VirtualHost>
...
..
<VirtualHost XXX.XXX.XXX.XXX>
ServerName www.your-domain.com - Note that no aliases are listed
...
...
</VirtualHost>
<VirtualHost XXX.XXX.XXX.XXX>
ServerName your-domain.com
ServerAlias other-domain.com
ServerAlias www.other-domain.com
Redirect permanent / http://www.your-domain.com.com/
</VirtualHost>
...
..
Note:
o See the YoLinux.com Apache "Redirect" Tutorial
When specifying more domains, they may all use the same IP address or some/all may use their
own unique IP address. Specify a "NameVirtualHost" for each IP address.
After the Apache configuration files have been edited, restart the httpd daemon:
/etc/rc.d/init.d/httpd restart (Red Hat) or /etc/init.d/apache2 restart (Ubuntu /
Debian)
Example: /etc/apache2/sites-available/supercorp
<VirtualHost XXX.XXX.XXX.XXX>
ServerName supercorp.com
ServerAlias www.supercorp.com
ServerAdmin webmaster@localhost
DocumentRoot /home/supercorp/public_html/home
<Directory "/">
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/supercorp/public_html/home>
Options Indexes FollowSymLinks MultiViews
IndexOptions SuppressLastModified SuppressDescription
AllowOverride All
Order allow,deny
allow from all
</Directory>
ErrorLog /var/log/apache2/supercorp.com-error.log
Restart Apache:
o apache2ctl graceful
or
o /etc/init.d/apache2 restart
or
o /etc/init.d/apache2 reload
Also note that Apache modules can also be enabled/disabled with scripts a2enmod/a2dismod.
Man pages:
One may assign multiple IP addresse to a single network interface. See the YoLinux networking
tutorial: Network Aliasing. Each IP address may then be it's own virtual server and individual
domain. The downside of the "IP based" virtual host method is that you have to possess
multiple/extra IP addresses. This usually costs more. The standard name based virtual hosting
method above is more popular for this reason.
<VirtualHost *>
ServerAdmin [email protected]
DocumentRoot /home/user0/public_html
</VirtualHost>
<VirtualHost XXX.XXX.XXX.101>
ServerAdmin [email protected]
DocumentRoot /home/user1/public_html
</VirtualHost>
<VirtualHost XXX.XXX.XXX.102>
ServerAdmin [email protected]
DocumentRoot /home/user2/public_html
</VirtualHost>
The default <VirtualHost *> block will be used as the default for all IP addresses not
specified explicitly. This default IP (*) may not work for https URL's.
CGI is a program executable which dynamically generates a web page by writing to stdout. CGI is
permitted by either of two configuration file directives:
ScriptAlias:
o Red Hat 7.x-9, Fedora core: ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
or
Options +ExecCGI:
<Directory /var/www/cgi-bin>
Options +ExecCGI
</Directory>
The executable program files must have execute privileges, executable by the process owner (Red Hat
7+/Fedora Core: apache. Older use nobody) under which the httpd daemon is being run.
The suEXEC feature provides Apache users the ability to run CGI and SSI programs under user IDs
different from the user ID of the calling web-server. Normally, when a CGI or SSI program executes, it
runs as the same user who is running the web server.
NameVirtualHost XXX.XXX.XXX.XXX
<VirtualHost XXX.XXX.XXX.XXX>
ServerName node1.your-domain.com - Allows requests
by domain name without the "www" prefix.
ServerAlias your-domain.com www.your-domain.com - CNAME (alias
www) specified in Bind configuration file (/var/named/...)
ServerAdmin [email protected]
DocumentRoot /home/user1/public_html/your-domain.com
ErrorLog logs/your-domain.com-error_log
TransferLog logs/your-domain.com-access_log
ERROR Pages:
You can specify your own web pages instead of the default Apache error pages:
PHP:
If the appropriate php, perl and httpd RPM's are installed, the default Red Hat Apache
configuration and modules will support PHP content. RPM Packages (RHEL4):
Apache configuration:
...
PHP Configuration File:
[PHP]
engine = On
...
...
display_errors = Off
include_path = ".:/php/includes"
...
...
memory_limit = 32M ; Default is typically 8MB which is too low.
...
...
[MySQL]
...
...
mysql.default_host = superserver ; Hostname of the computer
mysql.default_user = dbuser
...
Small portion of file shown.
Note that changes will not take effect until the apache web server daemon is restarted.
<?php
phpinfo();
?>
OR (older format)
<?
phpinfo();
?>
Test: http://localhost/~user1/test.php
For more info see YoLinux list of PHP information web sites.
Scanning the Apache web log files will not provide meaningfull statistics unless they are graphed
or presented in an easy to read fashion. The following packages to a good job of presenting site
statistics.
eXTReMe Tracking
CgiWrap - setuid wrapper that allows users to install and execute their own cgi scripts that get
executed as their own userid
Thumbprint - CGI for viewing a directory of images as thumbnails
o https configuration
Installation:
....
...
..
#!/bin/sh
cp /opt/etc/analog-domain1.com.cfg /etc/analog.cfg
/usr/bin/analog
cp /opt/etc/analog-domain2.com.cfg /etc/analog.cfg
/usr/bin/analog
...
Links:
Many FTP programs exist. This example covers the popular vsftpd (Red Hat default 9.0, Fedora
Core, Suse) and wu-ftpd (Washington University) program which comes standard with RedHat
(last shipped with RedHat 8.0 but can be installed on any Linux system). (RPM: wu-ftpd) There
are other FTP programs including proFtpd (supports LDAP authentication, Apache like
directives, full featured ftp server software), bftpd, pure-ftpd (free BSD and optional on Suse),
etc ...
For hostile environments set up a chrooted environment for an sftp encrypted connection and
the rssh restricted shell for OpenSSH. See the YoLinux.com internet security tutorial for Linux
sftp and rssh configuration
FTPd and SELinux: To allow FTPd daemon access and FTP access to users home directories:
setsebool -P allow_ftpd_full_access=1
Other wise you will get an error in /var/log/messages:
SELinux is preventing the ftp daemon from writing files outside the home
directory (./public_html).
setsebool -P ftp_home_dir 1
# vsFTPd: Configuration
# WU-FTPd: Configuration
The vsFTPd ftp server was first made available in Red Hat 9.0. It has been adopted by Suse and
OpenBSD as well. This is currently the recomended FTP daemon for use on FTP servers.
Enable vsftpd:
Red Hat/Fedora Core/CentOS: VsFTPd is a stand alone service and by the default Fedora Core
installation, not controlled by xinetd as is the wu-ftpd default installation.
Thus start service: service vsftpd start (or: /etc/init.d/vsftpd start)
Configure vsftpd to start upon system boot: chkconfig --add vsftpd
SuSE: By default, the vsftpd is an xinetd controlled service. To enable FTP server services edit the
file /etc/xinetd.d/vsftpd and change:
disable = yes
to:
disable = no
Restart the xinetd daemon: /etc/init.d/xinetd restart
Note: vsftpd can also be run as a stand-alone service to achieve a faster response time.
For more on starting/stopping/configuring Linux services, see the YoLinux tutorial on the Linux
init process and service activation.
Configuration files:
vsFTPd configuration file:
o Fedora Core / Red Hat: /etc/vsftpd/vsftpd.conf
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it, may
confuse older FTP clients.
#async_abor_enable=YES
pam_service_name=vsftpd
Restart the FTP service if the config file is changed: service vsftpd restart (or:
/etc/init.d/vsftpd restart)
[Potential Pitfall]: vsftp does NOT support comments on the same line as a directive. i.e.:
directive=XXX # comment
o Ubuntu: /etc/vsftpd/vsftpd.chroot_list
(Requires: chroot_list_enable=YES)
user1
user2
...
user-n
o Ubuntu: /etc/vsftpd.user_list
root
bin
daemon
adm
lp
sync
shutdown
halt
...
If userlist_enable=NO, then specify valid users.
#%PAM-1.0
auth required pam_listfile.so item=user sense=deny
file=/etc/vsftpd.ftpusers onerr=succeed
auth required pam_stack.so service=system-auth
auth required pam_shells.so
account required pam_stack.so service=system-auth
session required pam_stack.so service=system-auth
This causes PAM to check /etc/vsftpd.ftpusers for users who are denied. This duplicates
/etc/vsftpd.user_list. Speciy user in both files as PAM is independent of vsftpd
configuration.
PAM authentication configuration file: ftpusers
o Red Hat: /etc/vsftpd/ftpusers
o Ubuntu: /etc/vsftpd.ftpusers
root
bin
daemon
adm
lp
sync
shutdown
halt
...
...
...
user6 - Users to deny
user8
...
...
/var/log/xferlog {
# ftpd doesn't handle SIGHUP properly
nocompress
missingok
}
# Access rights
anonymous_enable=YES - Turn on anonymous FTP
chown_uploads=YES - Uploaded files owned by an assigned user
chown_username=ftp - Uploaded files owned by this assigned user
local_enable=NO
write_enable=NO - No upload of files system changes allowed
anon_upload_enable=NO
anon_mkdir_write_enable=NO
anon_other_write_enable=NO
# Security
anon_world_readable_only=YES
connect_from_port_20=YES
force_dot_files=NO
guest_enable=NO
hide_ids=YES
pasv_min_port=50000
pasv_max_port=60000
# Features
xferlog_enable=YES
ls_recurse_enable=NO
ascii_download_enable=NO
async_abor_enable=YES
# Performance
one_process_model=NO
idle_session_timeout=120
data_connection_timeout=300
accept_timeout=60
connect_timeout=60
max_per_ip=4
anon_max_rate=50000
pam_service_name=vsftpd
userlist_enable=YES
#enable for standalone mode
listen=YES
tcp_wrappers=YES
Anonymous logins use the login name "anonymous" and then the user supplies their email
address as a password. Any password will be accepted. Used to allow the public to download
files from an ftp server. Generally, no upload is permitted.
Web hosting configuration: /etc/vsftpd/vsftpd.conf
# Access rights
anonymous_enable=NO
local_enable=YES - Allow users to ftp to their
home directories
write_enable=YES - Allow users to STOR, DELE,
RNFR, RNTO, MKD, RMD, APPE and SITE
local_umask=022
# Security
connect_from_port_20=YES
force_dot_files=NO
guest_enable=NO - Don't remap user name
ftpd_banner=Welcome to Super Duper Hosting - Customize the login banner
string.
chroot_local_user=YES - Limit user to browse their
own directory only
chroot_list_enable=YES - Enable list of system / power
users
chroot_list_file=/etc/vsftpd.chroot_list - Actual list of system / power
users
hide_ids=YES
pasv_min_port=50000
pasv_max_port=60000
# Features
xferlog_enable=YES
ls_recurse_enable=NO
ascii_download_enable=NO
async_abor_enable=YES
dirmessage_enable=YES - Message greeting held in file
.message or specify with message_file=...
# Performance
one_process_model=NO
idle_session_timeout=120
data_connection_timeout=300
accept_timeout=60
connect_timeout=60
max_per_ip=4
#
pam_service_name=vsftpd
userlist_enable=YES
#enable for standalone mode
listen=YES
tcp_wrappers=YES
user1
user2
...
user-n
If userlist_enable=NO, then specify users not to be chroot'd..
[Potential Pitfall]: Mispelling a directive will cause vsftpd to fail with little warning.
File: .message
Links:
The wu-ftpd FTP server can be downloaded (binary or source) from it's home page at http://wu-
ftpd.org.
guest FTP - one logs in with a real user name and password, but the user is chroot'ed to his
home directory and cannot escape from it. They are constrained to their home directory which
also means that they don't have access to /bin/ls and other commands on the server. Thus a
local minimalist environment must be set up.
Note:
user1, user2 and user3 refer to login accounts. Use the appropriate login name.
The above configuration disables anonymous FTP which allows anyone to perform an FTP login
with the id anonymous and an email address as a password. To enable anonymous FTP, change
the class directive to:
o /sbin/linuxconf
(Note: Linuxconf is no longer included with Red Hat 7.3 and later)
Red Hat Linux assigns users a user id and group id which is the same. This means that it does not
matter if you use a realuser or realgroup directive as they will act the same.
Red Hat Linux 7.1 and later uses the xinet daemon to manage ftp connections. Thus xinetd must
be running and configured to support ftp. The configuration file is /etc/xinetd.d/wu-ftpd.
The command chkconfig wu-ftpd on will make the ftp server available. See xinet
configuration for more info.
Optional configuration:
o Create a group ftpchroot
[Potential Pitfall]: Flakey ftp behavior, timeouts, etc?? FTP works best with name resolution of
the computer it is communicating with. This requires proper /etc/resolve.conf and name
server (bind) configuration, /etc/hosts or NIS/NFS configuration.
File /home/user1/public_html/etc/pathmsg:
The whole point of the chroot directory is to make the user's home directory appear to be the root
of the filesystem (/) so one could not wander around the filesystem. Configuration of
/etc/ftpaccess will limit the user to their respective directories while still offering access to
/bin/ls and other system commands used in FTP operation.
As root:
cd /home/user1
mkdir public_html
chown $1.$1 public_html
touch .rhosts - Security protection
chmod ugo-xrw .rhosts
Man Pages:
Server:
File Formats:
/etc/ftpaccess - Configuration file for ftpd
/etc/ftpservers - ftpd virtual hosting configuration file. (optional)
/etc/ftphosts - allow or deny access to certain accounts from various hosts. (optional)
#%PAM-1.0
auth required pam_listfile.so item=user sense=deny
file=/etc/ftpusers onerr=succeed
auth required pam_stack.so service=system-auth
auth required pam_shells.so
account required pam_stack.so service=system-auth
session required pam_stack.so service=system-auth
Xinetd configuration file: /etc/xinetd.d/wu-ftpd
service ftp
{
disable = no
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.ftpd
server_args = -l -a
log_on_success += DURATION USERID
log_on_failure += USERID
nice = 10
}
Note: wu-FTPd is controlled by xinetd and not a stand alone service like vsFTPd.
Logrotate configuration file: /etc/logrotate.d/ftpd
/var/log/xferlog {
nocompress
}
More information:
WU-FTPD Development Group Home Page
More resources
Academ Consulting
FTP and text file type conversions: End Of Line Characters - by Peter Benjamin
WS_FTP
FTP Pitfalls:
ftp> ls
227 Entering Passive Mode (208,188,34,109,208,89)
ftp: connect: No route to host
This means you have firewall issues most probably on the FTP server itself. Start by removing the
firewall "iptables" rules: iptables -F Add rules until you discover what is causing the problem.
Passive mode:
Passive mode can also help one past the rules:
ftp> passive
Passive mode on.
This toggles passive mode on and off. When on, FTP will be limited to ports specified in the
vsftpd configuration file: vsftpd.conf with the parameters pasv_min_port and
pasv_max_port
Firewall connection tracking module:
# cat /etc/sysconfig/iptables-config | grep ip_nat_ftp
IPTABLES_MODULES="ip_conntrack_ftp"
FTP will change ports during use. The ip_conntrack_ftp module will consider each
connection "RELATED". If iptables allows RELATED and ESTABLISHED connections then
FTP will work. i.e. rule: /etc/sysconfig/iptables
FTP fails because it can not change to the users home directory:
Error:
This is often a result of SELinux preventing the vsftpd process from accesing the user's
home directory. As root, grant access with the following command:
setsebool -P ftp_home_dir 1
Followed by: service vsftpd restart
ftp: (/usr/kerberos/bin/ftp) kerberos enabled console ftp client. (RPM package FC3: krb5-
workstation)
When hosting web sites, there is no need to grant a shell account which only allows the server to
have more potential security holes. Current systems can specify the user to have only FTP access
with no shell by granting them the "shell" /sbin/nologin provided with the system or the
"ftponly" shell described below. The shell can be specified in the file /etc/passwd of when
creting a user with the command adduser -s /sbin/nologin user-id
[Potential Pitfall]: Red Hat 7.3 server with wu-ftp server 2.6.2-5 does not support this
configuration to prevent shell access. It requires users to have a real user shell. i.e. /bin/bash It
works great in older and current Red Hat versions. If it works for you, use it, as it is more secure
to deny the user shell access. You can always deny telnet access. You should NOT be using this
problem ridden version of ftpd. Use the latest wu-ftpd-2.6.2-11 which supports users with shell
/opt/bin/ftponly
[Potential Pitfall]: Ubuntu Dapper/Hardy - Setting the shell to the preconfigured shell
/bin/false will NOT allow vsftp access. One must create the shell "ftponly" as defined below
to allow vsftp access with no shell.
Change the shell for the user in /etc/passwd from /bin/bash to be /opt/bin/ftponly.
...
user1:x:502:503::/home/user1:/opt/bin/ftponly
...
#!/bin/sh
#
# ftponly shell
#
trap "/bin/echo Sorry; exit 0" 1 2 3 4 5 6 7 10 15
#
[email protected]
#System=`/bin/hostname`@`/bin/domainname`
#
/bin/echo
/bin/echo
"********************************************************************"
/bin/echo " You are NOT allowed interactive access."
/bin/echo
/bin/echo " User accounts are restricted to ftp and web access."
/bin/echo
/bin/echo " Direct questions concerning this policy to $Admin."
/bin/echo
"********************************************************************"
/bin/echo
#
# C'ya
#
exit 0
The last step is to add this to the list of valid shells on the system.
Add the line /opt/bin/ftponly to /etc/shells.
/bin/bash
/bin/bash1
/bin/tcsh
/bin/csh
/opt/bin/ftponly
For more on Linux security see the: YoLinux.com Internet web site Linux server security
tutorial
Two of the most popular ways to configure the program Bind (Berkeley Internet Domain
software) to perform DNS services is in the role of (1) ISP or (2) Web Host.
1. In an ISP configuration for clients (web surfers) conected to the internet, the DNS server must
resolve IP addresses for any URL the user wishes to visit. (See DNS caching server)
2. In a purely web hosting configuration, Bind will only resolve for the IP addresses of the domains
which are being hosted. This is the configuration which will be discussed and is often called an
"Authoritative-only Nameserver".
When resolving IP addresses for a domain, Internic is expecting a "Primary" and a "Secondary"
DNS name server. (Sometimes called Master and Slave) Each DNS name server requires the
file /etc/named.conf and the files it points to. This is typically two separate computer systems
hosted on two different IP addresses. It is not necesary that the Linux servers be dedicated to
DNS as they may run a web server, mail server, etc.
Note on Bind versions: Red Hat versions 6.x used Bind version 8. Release 7.1 of Red Hat began
using Bind version 9 and the GUI configuration tool bindconf was introduced for those of you
that like a pretty point and click interface for configuration.
Installation Packages:
o caching-nameserver: We will not be covering this as it is not required for web hosting.
This is used by internet providers so their clients can cache the DNS entries of the sites
they are visiting.
Ubuntu (dapper/hardy) / Debian: bind9
Configuration files:
Debian / Ubuntu:
File: named.conf
zone "localhost" {
type master;
file "/etc/bind/db.local";
};
zone "0.0.127.in-addr.arpa" {
type master;
file "/etc/bind/db.127";
};
BIND Views: The BIND naming service can support "views" which allow various sub-networks
(i.e. private internal or public external networks) to have a different domain name resolution
result.
If even one view is specified, then ALL zones MUST be associated with a "view".
Bind 9 allows for views which allow different zones to be served to different types of
clients, localhost, private networks and public networks. This maps to the three view
names "localhost_resolver", "internal" and "external":
o internal: User specified Local Area Network (LAN). If not used to support a local
private LAN, remove (or comment out) this view.
If you are only setting up a caching name server, then only specify the view
"localhost_resolver" (delete all other views).
In order to support a DNS for internet domains using views, one will have to configure
an "external" view
Typical Red Hat Enterprise 5 example: (Bind 9.3.4 with three "views")
options
{
directory "/var/named"; // the default
dump-file "data/cache_dump.db";
statistics-file "data/named_stats.txt";
memstatistics-file "data/named_mem_stats.txt";
};
logging
{
// By default, SELinux policy does not allow named to modify the
/var/named
// directory, so put the default debug log file in data/ :
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
view "localhost_resolver"
{
// This view sets up named to be a localhost resolver ( caching only
nameserver ).
// If all you want is a caching-only nameserver, then you need only
define this view:
match-clients { localhost; };
...
};
view "internal"
{
// This view will contain zones you want to serve only to "internal"
clients
// that connect via your directly attached LAN interfaces - "localnets" .
// For local private LAN. Not covered in this tutorial.
// Delete this view if web hosting with no local LAN.
match-clients { localnets; };
...
};
key ddns_key
{
algorithm hmac-md5;
secret "use /usr/sbin/dns-keygen to generate TSIG keys";
};
view "external"
{
// This view will contain zones you want to serve only to "external"
// public internet clients. This is covered below.
match-clients { any; };
...
..
};
Default configuration files: Red Hat may supply the default configuration in:
/usr/share/doc/bind-9.X.X/sample/etc/named.conf
cp /usr/share/doc/bind-9.X.X/sample/etc/named.conf
/var/named/chroot/etc
cp /usr/share/doc/bind-9.X.X/sample/etc/named.root.hints
/var/named/chroot/etc
cp /usr/share/doc/bind-9.X.X/sample/etc/named.rfc1912.zones
/var/named/chroot/etc
cp /usr/share/doc/bind-9.X.X/sample/var/named/localdomain.zones
/var/named/chroot/var/named
also from /usr/share/doc/bind-9.X.X/sample/var/named/:
localhost.zones, named.local, named.zero, named.broadcast,
named.ip6.local, named.root
view "external"
{
/* This view will contain zones you want to serve only to "external" clients
* that have addresses that are not on your directly attached LAN interface
subnets:
*/
match-clients { any; };
match-destinations { any; };
allow-transfer { XXX.XXX.XXX.XXX; }; - IP address of secondary DNS
recursion no;
// you'd probably want to deny recursion to external clients, so you
don't
// end up providing free DNS service to all takers
zone "your-domain.com" {
type master;
file "/var/named/data/external/named.your-domain.com";
notify yes;
allow-update { none; };
};
// You can also add the zones as a separate file like they do in
Ubuntu by adding the following statement
include "/etc/named.conf.local";
};
DNS key:
Use the following command /usr/sbin/dns-keygen to create a key. Add this key to the
"secret" statement as follows:
key ddns_key
{
algorithm hmac-md5;
secret
"XlYKYLF5Y7YOYFFFY6YiYYXyFFFFBYYYYFfYYYJiYFYFYYLVrnrWrrrqrrrq";
};
Man Pages:
named.conf
your-domain.com. IN MX 10 mail1.offsitemail.com.
your-domain.com. IN MX 20 mail2.offsitemail.com.
Initial configuration: Note that Red Hat may supply the default zone configuration in:
/usr/share/doc/bind-9.X.X/sample/var/named/
cp /usr/share/doc/bind-9.X.X/sample/var/named/localhost.zone
/var/named/chroot/var/named/data/
cp /usr/share/doc/bind-9.X.X/sample/var/named/localdomain.zone
/var/named/chroot/var/named/data/
cp /usr/share/doc/bind-9.X.X/sample/var/named/named.broadcast
/var/named/chroot/var/named/data/
cp /usr/share/doc/bind-9.X.X/sample/var/named/named.ip6.local
/var/named/chroot/var/named/data/
cp /usr/share/doc/bind-9.X.X/sample/var/named/named.zero
/var/named/chroot/var/named/data/
cp /usr/share/doc/bind-9.X.X/sample/var/named/named.local
/var/named/chroot/var/named/data/
cp /usr/share/doc/bind-9.X.X/sample/var/named/named.root
/var/named/chroot/var/named/data/
cd /var/named/chroot/var/named/data/
File: named.conf
zone "your-domain.com"{
type slave;
file "named.your-domain.com"; - Specify slaves/named.your-
domain.com for RHEL4/5 chrooted bind
masters { XXX.XXX.XXX.XXX; }; - IP address of primary DNS
};
zone "your-domain-2.com"{
type slave;
file "named.your-domain-2.com";
masters { XXX.XXX.XXX.XXX; };
};
view "external"
{
match-clients { any; };
match-destinations { any; };
allow-transfer { none; }; - Slave does not transfer to anyone,
slave receives
recursion no;
include "/etc/named.root.hints";
zone "your-domain.com" {
type slave;
file "/var/named/slaves/external/named.your-domain.com";
notify no; - Slave does not notify, slave
is notified by master
masters { XXX.XXX.XXX.XXX; }; - State IP of master server
};
};
Note: RHEL4/5, CentOS 4/5, Fedora 3+ use chrooted directory structure permissions which
require the use of the slaves subdirectory /var/named/slaves
Slave Zone Files: These are transfered from master to slave and chached by slave. There is no need to
generate a zone file on the slave.
Additional Information:
[Potential Pitfall]: Ubuntu dapper/hardy - Path names used can not violate Apparmor security
rules as defined in /etc/apparmor.d/usr.sbin.named. Note that the slave files are typically
named "/var/lib/bind/named.your-domain.com" as permitted by the security configuration.
[Potential Pitfall]: Ubuntu dapper/hardy - Create log file and set ownership and permission for
file not created by installation:
touch /var/log/bindlog
chown root.bind /var/log/bindlog
Named needs write permission on the directory containing the file. This condition often occurs
for a new "slave" or "secondary" name server where the zone files do not yet exist.
The default (RHEL4/5, CentOS 4/5, Fedora Core 3+, ...):
Bind Defaults:
Logging is to /var/log/messages
After the configuration files have been edited, restart the name daemon.
/etc/init.d/named restart
Bind zone transfers work best if the clocks of the two systems are synchronised. See the
YoLinux SysAdmin Tutorial: Time and ntpd
Test the name server with the host command in interactive mode:
host node.domain-to-test.com your-nameserver-to-test.domain.com
or
Test the name server with the nslookup command in interactive mode:
nslookup
> server your-nameserver-to-test.domain.com
> node.domain-to-test.com
> exit
OR
host -t mx domain-to-test.com
OR
Test your DNS with the following DNS diagnostics web site: DnsStuff.com
Note: Most modern Linux distributions default to a "chrooted" installation. This technique runs
the Bind name service with a view of the filesystem which changes the definition of the root
directory "/" to a directory in which Bind will operate. i.e. /var/named/chroot.
The following example uses the Red Hat RPM bind-8.2.3-0.6.x.i386.rpm. Applies
to Bind version 9 as well.
The latest RedHat bind updates run the named as user "named" to avoid a lot of earlier
hacker exploits. To chroot the process is to create an even more secure environment by
limiting the view of the system that the process can access. The process is limited to the
chrooted directory assigned.
The chroot of the named process to a directory under a given user will prevent the
possibility of an exploit which at one time would result in root access. The original
default RedHat configuration (6.2) ran the named process as root, thus if an exploit was
found, the named process will allow the hacker to use the privileges of the root user. (no
longer true)
Example:
When chrooted, the process does not have access to system libraries thus a local lib
directory is required with the appropriate library files - theoretically. This does not seem
to be the case here and as noted above in chrooted FTP. It's a mystery to me but it
works???? Another method to handle libraries is to re-compile the named binary with
everything statically linked. Add -static to the compile options. The chrooted process
should also require a local /etc/named.conf etc... but doesn't seem to???
#!/bin/sh
cd /opt
mkdir named
cd named
mkdir etc
mkdir bin
mkdir var
cd var
mkdir named
mkdir run
cd ..
chown -R named.named bin etc var
You can probably stop here. If your system acts like a chrooted system should, then continue
with the following:
cp -p /etc/named.conf etc
cp -p /etc/localtime etc
cp -p /bin/false bin
echo "named:x:25:25:Named:/var/named:/bin/false" > etc/passwd
echo "named:x:25:" > etc/group
touch var/run/named.pid
if [ -f /etc/namedb ]
then
cp -p /etc/namedb etc/namedb
fi
mkdir dev
cd dev
cd ..
chown -R named.named bin etc var
#!/bin/bash
#
# named This shell script takes care of starting and stopping
# named (BIND DNS server).
#
# chkconfig: - 55 45
# description: named (BIND) is a Domain Name Server (DNS) \
# that is used to resolve host names to IP addresses.
# probe: true
[ -f /usr/sbin/named ] || exit 0
[ -f /etc/named.conf ] || exit 0
RETVAL=0
start() {
# Start daemons.
echo -n "Starting named: "
daemon named -u named -g named -t /opt/named - Change made here
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/named
echo
return $RETVAL
}
stop() {
# Stop daemons.
echo -n "Shutting down named: "
killproc named
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/named
echo
return $RETVAL
}
rhstatus() {
/usr/sbin/ndc status
return $?
}
restart() {
stop
start
}
reload() {
/usr/sbin/ndc reload
return $?
}
probe() {
# named knows how to reload intelligently; we don't want linuxconf
# to offer to restart every time
/usr/sbin/ndc reload >/dev/null 2>&1 || echo start
return $?
}
exit $?
Note: The current version of bind from the RedHat errata updates and security fixes
(http://www.redhat.com/support/errata/) runs the named process as user "named" in the
home (not chrooted) directory /var/named with no shell available. (named -u named)
This should be secure enough. Proceed with a chrooted installation if your are paranoid.
See:
Modern releases of Linux (i.e. Fedore Core 3, Red Hat Enterprise Linux 4) come preconfigured
to use "chrooted" bind. This security feature forces even an exploited version of bind to only
operate within the "chrooted" jail /var/named/chroot which contains the familiar directories:
o /dev/null
o /dev/random
o /dev/zero
These directories are generated and configured by the Red Hat/Fedora RPM package "bind-chroot".
If building from source you will have to generate this configuration manually:
mkdir -p /var/named/chroot
mkdir /var/named/chroot/dev
mknod /var/named/chroot/dev/null c 1 3
mknod /var/named/chroot/dev/zero c 1 5
mknod /var/named/chroot/dev/random c 1 8
mkdir -p /var/named/chroot/etc
ln -s /var/named/chroot/etc/named.conf /etc/named.conf
mkdir -p /var/named/chroot/var/named
ln -s /var/named/chroot/var/named/named.XXXX /var/named/named.XXXX
ln -s /var/named/chroot/var/named/named.YYYY /var/named/named.YYYY
...
mkdir -p /var/named/chroot/var/named/slaves
mkdir -p /var/named/chroot/var/named/data
mkdir -p /var/named/chroot/var/run
mkdir -p /var/named/chroot/var/tmp
This will populate name servers around the world with different IP addresses for your web server
www.your-domain.com
www0 IN A XXX.XXX.XXX.1
www1 IN A XXX.XXX.XXX.2
www2 IN A XXX.XXX.XXX.3
www3 IN A XXX.XXX.XXX.4
www4 IN A XXX.XXX.XXX.5
www5 IN A XXX.XXX.XXX.6
Bind/DNS Links:
LDP DNS-HOWTO
GraniteCanyon.com: Free DNS hosting - If you don't want to set it up, have someone do it for
you.
DynDNS.org
Command: ipcheck.py -i eth0 DynDNS-user-id password node.dnsalias.net
Then add script update.dyndns.ip to directory /etc/cron.daily/ to update IP.
This host must also be allowed access through any firewall rules.
DynDNS/TODD - Dynamic DNS for those with dynamic IP addresses. (i.e. dial-up game servers
etc.)
o Register.com
o DomainsNext.com - $11.95/year
o EasyDNS.com - $25.00/year
o Gandi.net - European
Note that the Name registrations policies for the registrars are stated at ICANN.org.
You must renew with the same registrar within five days BEFORE the expiration date. There is no
rule for afterwards.
Most free a domain name 30 days after it expires.
Run a reverse proxy. See nginx ("engine X"). From a single external internet network connection,
route http, smtp, imap or pop3 traffic to various servers on an internal network. Results are
pushed back to the nginx proxy for routing to the internet (no caching).
Run the Apache httpd web server module "mod_proxy" to offload processing of dynamic
content to another web server. This acts as a reverse proxy, routing external traffic to various
servers on an internal network.
You can use a single Linux server to forward requests to a cluster of servers using iptables for IP
masquerading and IPVsadm to scale your load. The load balancing server receiving and routing
the requests is called the "Linux Virtual Server" (LVS). The LVS receives the requests which are
passed to the real servers which process and reply to the request. This reply is forwarded to the
client by the LVS.
This feature is available with the Linux 2.4/2.6 kernel. (If compiling kernel: Networking Options
+ IP: Virtual Server Configuration)
Configuration: This example will load balance http traffic to three web servers and ftp traffic to a
fourth server.
Enable IP Masquerading:
For more on IP Masquerading, iptables and subnet addresses, see the YoLinux network gateway
tutorial.
Command directives:
-s: scheduler:
rr: Robin Robin: distributes jobs equally amongst the avail- able real
servers.
lc: Least-Connection: assigns more jobs to real servers with fewer active
jobs.
Command directives:
-w: Weight is an integer specifying the capacity of a server rela- tive to the
others in the pool. The valid values of weight are 0 through to 65535. The default is 1.
Links:
LinuxVirtualServer.org
iptables - Administration tool for IPv4 packet filtering and NAT
To view if these services are running, type ps -aux and look for the httpd, inetd and named
services (daemons). These are background processes necessary to perform the server tasks.
#!/bin/sh
# Author Greg Ippolito
# Requires: /opt/etc/AccountDefaults/pathmsg favicon.ico mwh-mini_tr.gif
etc.
# /opt/bin/ftponly
# You must be root to run this script.
#
if [ $# -eq 0 ]
then
echo "Enter user id as a command argument"
else if [ -r /home/$1 ]
then
echo "User's home directory already exists"
else
echo "1) Create user."
adduser -m $1
echo "3) Add read access to user directory so apache can read it."
cd /home
chmod ugo+rx $1
cd $1
Use Linux ipchains / iptables and IP forwarding to configure Linux as a firewall and
router. This is the method covered in this tutorial.
The Linux router project has produced a specialized version of Linux just to run
ipchains / iptables and IP masquerading.
See LinuxRouter.org.
Use SOCKS gateway proxy software running on Linux.
For more information see the SOCKS5/e-Border home page.
Use a CISCO router - Configuration tutorial. (Note: PIX series are preferred for firewall
use.)
This tutorial will cover using a linux computer as a gateway between a private network and the
internet. Any internet connection whether it be a dial-up PPP, DSL, cable modem or a T1 line
can be used. In the case of most dial-up PPP connections and cable modem connections, only a
single IP address is issued allowing only one computer to connect to the internet at a time. Using
Linux and iptables / ipchains one can configure a gateway which will allow all computers on a private
network to connect to the internet via the gateway and one external IP address, using a technology
called "Network Address Translation" (NAT) or masquerading and private subnets. Iptables/ipchains can
also be configured so that the Linux computer acts as a firewall, providing protection to the internal
network.
Note: Red Hat 7.1-9.0 and the default Linux 2.4 kernel may use ipchains or iptables but not both.
Iptables is the preferred firewall as it supports "state" and can recognize if a network connection
has already been "ESTABLISHED" or if the connection is related to the previous connection
(required for ftp which makes multiple connections on different ports). Ipchains can not. Ipchain
rules take precedence over iptables rules. During system boot, the kernel attempts to activate
ipchains, then attempts to activate iptables. If ipchain rules have been activated, the kernel will
not start iptables.
Red Hat 7.1 will not support ipchains unless that option is configured (during install or later). If
during install you select "Disable Firewall - no protection" then ipchains will not be available
and you must rely upon iptables for a manual firewall configuration. (iptables only. ipchains will
be unavailable)
GUI configuration:
iptables: The GUI configuration tool /usr/bin/redhat-config-securitylevel can
be used to choose a preconfigured firewall (High, Medium or no firewall) or it can be
used to manually configure rules based on the network services your server will offer.
The init script /etc/rc.d/init.d/iptables will use rules stored in
/etc/sysconfig/iptables.
ipchains: The tool that does this is lokkit (or /usr/bin/gnome-lokkit), which uses
ipchains to configure firewall options for High and Low security options. To support
ipchains after install, run /usr/bin/gnome-lokkit and configure a firewall. It will
configure ipchains to activate the firewall. Lokkit will generate the file
/etc/sysconfig/ipchains. (Used by init script /etc/rc.d/init.d/ipchains which
calls /sbin/ipchains-restore)
To see if ipchains and the Lokkit configuration is invoked during system boot, use the
command:
The default Red Hat 7.1+ Linux 2.4 kernel is compiled to support both iptables and ipchains.
Kernel support for ipchains is available during a kernel configuration and compilation. During
make xconfig or make menuconfig turn on the feature: "IP: Netfilter Configuration" +
"ipchains (2.2-style) support".
[Potential Pitfall]: When performing an upgrade instead of a new install, the upgrade software
will not install iptables as did not exist on the system previously. It will perform an upgrade to a
newer version of ipchains. If you wish to use iptables, you must manually install the iptables
RPM.
i.e.: rpm -ivh iptables-XXX.i386.rpm
[Potential Pitfall]: The Linux operating system kernel may load or not load what you had
expected. Use the command lsmod to see if ip_tables or ip_chains were loaded.
Switching a running system from ipchains to iptables: (Red Hat 7.1-9.0 - Linux kernel 2.4
specific)
An individual on a computer on the private network may point their web browser to a site on the
internet. This request is recognized to be beyond the local network so it is routed to the Linux
gateway using the private network address. The request for the web page is sent to the web site
using the external internet IP address of the gateway. The request is returned to the gateway
which then translates the IP address to computer on the private network which made the request.
This is often called IP masquerading. The software interface which enables one to configure the
kernel for masquerading is iptables (Linux kernel 2.4) or ipchains (Linux kernel 2.2)
The gateway computer will need two IP addresses and network connections, one to the private
internal network and another to the external public internet.
A note on private network IP addresses: A set of IP addresses has been reserved by IANA for private
networks. They range from 192.168.0.1 to 192.168.254.254 for a typical small business or home
network and are often referred to as CIDR private network addresses. Most private networks conform to
this scheme.
20 bit block in
172.16.0.0 172.31.255.255 172.16.0.0/12 255.240.0.0 1,048,576
class B
16 bit block in
192.168.0.0 192.168.255.255 192.168.0.0/16 255.255.0.0 65,536
class C
The actual number of hosts will be fewer that listed because addresses on each subnet will be
reserved as a broadcast address, etc.
This is detailed in RFC 1918 - Address Allocation for Private Internets. For a description of class
A, B, and C networks see the YoLinux Networking Tutorial class description.
The private networks may be subdivided into various subnets as desired. Examples:
This example uses a Linux computer connected to the internet using a dial-up line and modem
(PPP). The Linux gateway is connected to the internal network using an ethernet card. The
internal network consists of Windows PC's.
The Linux box must be configured for the private internal network and PPP for the dial-up
connection. See the PPP tutorial to configure the dial-up connection. Use the ifconfig command
to configure the private network. i.e. (as root)
This is often configured during install or can be configured using the Gnome tool neat (or the
admin tool Linuxconf or netcfg for older Red Hat systems). System changes made with the
ifconfig or route commands are NOT permanent and are lost upon system reboot. Permanent
settings are held in configuration scripts executed during system boot. (i.e.
/etc/sysconfig/...) See the YoLinux Networking tutorial for more information on assigning
network addresses.
iptables:
ipchains:
#!/bin/sh
ipchains -F forward - Flush all previous
rules and settings
ipchains -P forward DENY - Default set to deny
packet forwarding
ipchains -A forward -s 192.168.10.0/24 -j MASQ - Use IP address of
gateway for private network
ipchains -A forward -i ppp0 -j MASQ - Sets up external
internet connection
echo 1 > /proc/sys/net/ipv4/ip_forward - Enables packet
forwarding by kernel
A PPP connection as described by the YoLinux PPP tutorial will create the PPP network
connection as the default route.
High speed connections to the internet result in an ethernet connection to the gateway. Thus the
gateway is required to possess two ethernet Network Interface Cards (NICs), one for the
connection to the private internal network and another to the public internet. The ethernet cards
are named eth and are numbered uniquely from 0 upward.
This is often configured during install or can be configured using the Gnome tool neat (or the
admin tool Linuxconf or netcfg for older Red Hat systems). System changes made with the
ifconfig or route commands are NOT permanent and are lost upon system reboot. Permanent
settings are held in configuration scripts executed during system boot. (i.e.
/etc/sysconfig/...) See the YoLinux Networking tutorial for more information on assigning
network addresses.
Run the appropriate script on the linux computer where eth0 is connected to the internet and eth1
is connected to a private LAN:
iptables:
# Delete and flush. Default table is "filter". Others like "nat" must be
explicitly stated.
iptables --flush - Flush all the rules in filter and nat
tables
iptables --table nat --flush
iptables --delete-chain - Delete all chains that are not in default
filter and nat table
iptables --table nat --delete-chain
ipchains:
#!/bin/sh
ipchains -F forward - Flush rules
ipchains -P forward DENY - Default set to deny
packet forwarding
ipchains -A forward -s 192.168.10.0/24 -j MASQ - Use IP address of
gateway for private network
ipchains -A forward -i eth1 -j MASQ - Sets up external
internet connection
echo 1 > /proc/sys/net/ipv4/ip_forward
Note: While this configuration requires that the Linux gateway computer have two network
cards, if you only have one PCI slot available you may use a card such as the Intel Pro 100 or Pro
1000 Dual Port which has two ethernet connections which reside on a single card. (This is what I
use) Yolinux Hardware tutorial: More on Network interface cards
Intel PCI Dual Pro 100 or Pro 1000 NIC card supports two
physical ethernet connections (eth0, eth1) on one card.
Compliant Standards: IEEE 802.3-LAN, IEEE 802.3U-LAN ,
Plug and Play
Connectivity Technology: Cable - 10Base-T, 100Base-TX
Data Link Protocol: Ethernet, Fast Ethernet
Processor: 82550 - Intel