티스토리 뷰

How to set up a home DNS server

by Shannon Hughes


Domain Name System

The Domain Name System (DNS) is the crucial glue that keeps computer networks in harmony by converting human-friendly hostnames to the numerical IP addresses computers require to communicate with each other. DNS is one of the largest and most important distributed databases the world depends on by serving billions of DNS requests daily for public IP addresses. Most public DNS servers today are run by larger ISPs and commercial companies but private DNS servers can also be useful for private home networks. This article will explore some advantages of setting up various types of DNS servers in the home network.

Why set up a private DNS server?

This question is valid and the answer may vary depending on your home network environment. Maintaining a host file on each client with IP/hostname mappings in a home network that contains a router and a few machines may be sufficient for most users. If your network contains more than a few machines, then adding a private DNS server may be more attractive and worth the setup effort. Some advantages may include:

  • Maintenance: keeping track of the host file for every client in your network can be tedious. In fact, it may not even be feasible for roaming DHCP laptops or your occasional LAN party guests. Maintaining host information in one central area and allowing DNS to manage host names is more efficient.

  • Cache performance: DNS servers can cache DNS information, allowing your clients to acquire DNS information internally without the need to access public nameservers. This performance improvement can add up for tasks such as web browsing.

  • Prototyping: A private internal DNS server is an excellent first step to eventually setting up a public accessible DNS server to access a web server or other services hosted on your internal network. Learning from mistakes on an internal network can help prevent duplicate errors on a public DNS server that could result in loss of service for external users. Note: Some ISPs require customers to have a static IP or business subscription when hosting services in a home network environment.

  • Cool factor: Ok, I may be stretching it, but the "cool" factor did have some influence when I set up my first home network DNS server. Creating an internal domain that reflects an individual's personality without paying a domain registrar and issuing hostnames to your clients is cool. The cool factor doubles when your customized hostname glows from your friend's laptop screen.

Let's start out simply by setting up a caching-only nameserver to handle client DNS requests. A caching-only nameserver won't allow references to internal clients by hostname, but it does allow clients to take advantage of frequently requested domains that are cached.

Caching nameserver

Fortunately, setting up a caching nameserver is easy using RHEL (Red Hat Enterprise Linux) or Fedora RPMs. The following RPMs need to be installed on the machine acting as the nameserver (use rpm -q to determine if these packages are installed):

  • bind (includes DNS server, named)

  • bind-utils (utilities for querying DNS servers about host information)

  • bind-libs (libraries used by the bind server and utils package)

  • bind-chroot (tree of files which can be used as a chroot jail for bind)

  • caching-nameserver (config files for a simple caching nameserver)

A caching nameserver forwards queries to an upstream nameserver and caches the results. Open the file /var/named/chroot/etc/named.conf and add the following lines to the global options section:

     forwarders { xxx.xxx.xxx.xxx; xxx.xxx.xxx.xxx; }; #IP of upstream ISP nameserver(s)
     forward only; #rely completely on our upstream nameservers

The block above will cause the caching name server to forward DNS requests it can't resolve to your ISP nameserver. Save the named.conf file and then assign 644 permissions:
chmod 644 named.conf
Check the syntax using the named-checkconf utility provided by the bind RPM:
named-checkconf named.conf
Correct any syntax errors (watch those semicolons) named-checkconf reports. Monitoring the /var/log/messages file may also be helpful in debugging any errors.
We now need to set the local resolver to point to itself for DNS resolution. Modify the /etc/resolv.conf file to the following:
nameserver 127.0.0.1
If you are running a DHCP server on your router make sure your /etc/resolv.conf file does not get overwritten whenever your DHCP lease is renewed. To prevent this from happening, modify /etc/sysconfig/network-scripts/ifcfg-eth0 (replace eth0 with your network interface if different) and make sure the following settings are set:

BOOTPROTO=dhcp
PEERDNS=no
TYPE=Ethernet

Go ahead and start the nameserver as root and configure to start in runlevels 2-5:
service named start
chkconfig named on

Testing

The bind-utils RPM contains tools we can use to test our caching nameserver. Test your nameserver using host or dig and querying redhat.com:

dig redhat.com
.
.
;; Query time: 42 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)

From the above dig query you can see it took 42 msec to receive the DNS request. Now test out the caching ability of your nameserver by running dig again on the redhat.com domain:

dig redhat.com
.
.
;; Query time: 1 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)

We dropped from 42 msec to 1 msec after the previous DNS query was cached. Caching is working! Let's now put the cache to work by configuring the clients to use the new caching nameserver.

Client Configuration

For Linux and Windows clients you may have a couple of options for your resolver configuration depending on your network environment:

  1. If you have a router and your client's IP address is assigned via DHCP from the router, then you can use the router to assign the primary nameserver during the DHCP lease requested from the client. Log in to your router and make sure your primary nameserver points to your caching nameserver IP address in the router DHCP settings.

  2. For Linux clients, you can set up the resolver in the same procedure as the nameserver by modifying the /etc/resolv.conf file. For Windows clients you will need to set the nameserver IP address in the Control Panel -> Network Connections -> TCP/IP -> Properties -> Use the DNS Server Address option. NOTE: The Windows DNS server option may vary depending on your version.

Test your new client configuration(s) using dig. You can use the nslookup command for Windows clients. Your DNS requests should have similar response times as we saw earlier when testing the nameserver directly.

NOTE: If you are running a firewall on the nameserver system, make sure clients have access to port 53. An example iptables rule for the 192.168.15.0/24 subnet would be:
iptables -A INPUT -s 192.168.15.0/24 -p udp --dport 53 -j ACCEPT
service iptables save

Summary

Your new caching nameserver offers a performance improvement with a minimal amount of set up effort. Clients can now ask the caching nameserver for DNS information, and it only needs to ask the upstream ISP nameserver for cache misses. In the next issue we will setup a master nameserver that is responsible for the authoritative information for our internal client hostnames. An authoritative nameserver also caches by default but additionally allows managing both static and DHCP clients using personalized hostnames set up in zone files. In the meantime, enjoy your new caching nameserver and be thinking about a creative domain and hostname theme for your future authoritative nameserver.

About the author

Shannon Hughes is a Red Hat Network (RHN) engineer who enjoys using open source software to solve the most demanding software projects. When he is not cranking out code, tweaking servers, or coming up with new RHN projects, you can find him trying to squeeze in yet another plant in the yard/garden with his wife, watching Scooby Doo reruns with his two kids and dog, or incorporating the latest open source projects for his church.

 

 

named.caching-nameserver.conf

//
// named.caching-nameserver.conf
//
// Provided by Red Hat caching-nameserver package to configure the
// ISC BIND named(8) DNS server as a caching only nameserver
// (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//
// DO NOT EDIT THIS FILE - use system-config-bind or an editor
// to create named.conf - edits to this file will be lost on
// caching-nameserver package upgrade.
//
options { 
        // bind ip & port 설정
        listen-on port 53 { 127.0.0.1; };
        listen-on port 53 { 10.20.252.77; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";

        // Those options should be used carefully because they disable port
        // randomization
        // query-source    port 53;
        // query-source-v6 port 53;

        //allow-query     { localhost; };
        allow-query-cache { localhost; };
         // 질의를 받아들일 소스포트를 설정하는 부분
        query-source    port 53;
        query-source-v6 port 53; 
        // 질의를 허용할 대역을 설정

        allow-query     { any; };
        //recursion no;
        recursion yes;

};
logging {
        // 실행 시 참고할 로그파일을 설정
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

//2012.03.28 by rocksea
view localhost_resolver {
        //match-clients            { localhost; };
        //match-destinations { localhost; };
        // localhost_resolver에 대한 허용 클리어인트 설정.
        match-clients      { any; };
        match-destinations { any; };
       // 공개용 네임서버 사용시 yes 상위질의 허용여부를 설정. yes 사용시 보안상 취약점 
       //recursion 질의에 대해 localhost_resolver에서 지정된 대역만 허용하도록 zones 파일 분리
        recursion yes;
        include "/etc/named.rfc1912.zones";
};


 

/etc/named.rfc1912.zones

// named.rfc1912.zones:
//
// Provided by Red Hat caching-nameserver package
//
// ISC BIND named zone configuration for zones recommended by
// RFC 1912 section 4.1 : localhost TLDs and address zones
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//
zone "." IN {
        type hint;
        file "named.ca";
};

zone "localdomain" IN {
        type master;
        file "localdomain.zone";
        allow-update { none; };
};

zone "localhost" IN {
        type master;
        file "localhost.zone";
        allow-update { none; };
};

zone "0.0.127.in-addr.arpa" IN {
        type master;
        file "named.local";
        allow-update { none; };
};

zone "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa" IN {
        type master;
        file "named.ip6.local";
        allow-update { none; };
};

zone "255.in-addr.arpa" IN {
        type master;
        file "named.broadcast";
        allow-update { none; };
};

zone "0.in-addr.arpa" IN {
        type master;
        file "named.zero";
        allow-update { none; };
};

zone "rocksea.com" {
        type master;
        file "rocksea.com";

rocksea.com

;
; BIND data file for rocksea.com interface
;
$TTL    86400
@        IN      SOA     rocksea.com. ns.rocksea.com. (
                           1002         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
@        IN      NS      rocksea.com.
@        IN      MX      10      ns

@          IN      A      192.168.0.200
www     IN      A      192.168.0.200

 

☞  $TTL  :  Time To Live의 약자로 이곳에 설정한 도메인에 대한 정보를 다른 네임서버에서 읽어간 다음 읽어간 네임 서버측에 얼마동안 보관하고 있을 것인가를 설정하는 항목이다. 설정 값은 ‘초’ 단위로 설정한다. 여기서 보이는 86400의 의미는 86400초, 즉 하루 24시간을 의미한다. 하루 동안 한번만 읽어 가서 자신의 네임 서버 캐시에 저장한 다음 사용하라고 설정하는 것이다. 하루가 지나면 다른 네임 서버들은 자신의 캐시를 지우고 다시 도메인 설정에 대한 정보를 받아가게 된다.

 

존파일(리버스 파일)내의 @의 의미는 ORIGIN을 의미하는 특수문자로 public domain을 의미한다.

 

☞ IN 다음으로 나오는 우측 설정을 사용한다는 의미이다.

 

☞ SOA는 (start of authority)의 약자로써 도메인 네임 서버에 대한 모든 정보를 가지고 있으며 해당 도메인에 대한 네임 서버가 최적의 상태를 유지할 수 있도록 해준다. 여기서 주의할 사항은 도메인 이름을 적은 다음에는 항상 (.) 루트 도메인을 표시하여야 한다는 점이다.

 

 

SOA 레코드 뒤에 괄호로 묵은 부분에는 Serial, Refresh, Retry, Expire, Minimum 5개의 시간 필드가 놓인다. Minmum을 제외한 나머지 필드는 Secoundary를 제어하기 위한 필드이며 ‘초’ 단위가 기본이다.

 

☞ Serial : 마스터 네임 서버의 오류 또는 비정상 작동으로 인하여 마스터 네임 서버에 장애가 발생했을 때 슬레이브 네임 서버의 시리얼 번호를 지정하는 설정이다. 마스터 네임 서버와 슬레이브 네임 서버를 운영 중 일때 마스터 네임 서버의 zone파일의 내용이 변경 되면 반드시 Serial을 증가 시켜줘야 슬레이브 네임 서버가 자신의 현재 Serial을 비교하여 값이 작다면 zone 파일의 정보를 갱신하게 된다. 슬레이브 네임 서버를 사용하지 않는다면 Serial은 의미가 없다.

대부분의 서버에서는 알아보기 쉽게 하기 위해 날짜 기반으로 YYYYMMDD+NN(카운터)형식을 사용한다.

 

☞ Refresh : 슬레이브 네임 서버에서 마스터 네임 서버의 설정사항이 수정되었는지 주기적으로 체크할 시간을 설정한다. 최대 8자이며 단위는 초단위이다. 1H 로 설정을 한다면 1시간 단위로 슬레이브 네임 서버가 마스터 네임 서버의 변경사항을 체크해 간다. 이때 변경사항의 체크는 시리얼번호를 기준으로 체크한다. 만약 시리얼번호가 슬레이브 네임서버의 시리얼번호 보다 크다면 마스터 네임서버의 현재 설정으로 업데이트 받아간다.

 

☞ Retry : 슬레이브 네임서버에서 마스터 네임서버로 접속할 때 접속에 장애가 발생하면 얼마 후에 다시 재 접속을 시도할지를 지정하는 시간 항목이다. Refresh 보다 적어야지만 의미가 있기 때문에 주의를 요한다.

 

☞ Expire : 존파일의 유효기간을 설정한다. 설정된 시간 안에 마스터서버에서 응답을 받지 못했다면 슬레이브 서버는 데이터에 대한 유효성을 더 이상 인정하지 않고 도메인 데이터를 버린다. 일반적으로 슬레이브 서버의 역할이 마스터 서버에 대한 백업용도 이기 때문에 Expire 설정은 여유있게 설정하도록 한다.

 

☞ Minimum : $TTL 값과 같은 의미이다. 다른 네임서버에서 존파일의 데이터를 가지고 갔을 때 그 데이터에 대한 유효기간을 설정한다. TTL값이 명시되지 않은 레코드는 본 값을 기본으로 갖게 된다.

 

레코드의 종류

레코드

설 명

NS

도메인의 네임서버 정보

MX

도메인의 MX(Mail Exchanger) 서버

A

호스트의 IP주소

CNAME

별칭으로 부여된 canonical name

SOA

도메인의 start-of-authority정보

HINFO

호스트의 CPU 정보와 운영체제 정보

MINFO

메일박스와 메일 리스트 정보

PTR

IP주소에 대한 호스트명

TXT

호스트에 대한 텍스트 정보

UNIFO

사용자 정보

ANY

호스트에 관련된 모든 레크드들의 정보

 

 

☞ NS 레코드는 해당 도메인의 네임서버를 지정하는 레코드이다. NS 레코드 다음에 네임서버의 도메인 (.) 루트도메인 을 입력한다.

 

 

☞ MX 레코드는 해당 도메인에 대한 메일서버를 지정하는 레코드 이다. 일반적으로 메일서버를 여러개 사용할 때 MX 레코드 다음에 우선순위 번호를 지정하여 메일을 수신할 수 있다.

 

☞ A 레코드는 해당 도메인의 실제 IP주소를 설정하는 레코드이다.

 

☞ 서브도메인을 설정하려면 가장 앞부분에 서브 도메인명을 입력하고 A레코드로 IP번호를 지정하면 된다.

 

☞ CNAME 레코드는 별칭을 설정하여 사용하는 레코드이다. 아래와 같이 CNAME 레코드를 사용하고 A 레코드로 정의한 도메인을 적어주면 A레코드 의 도메인 IP를 별칭으로 사용함으로써 mail 도메인에 대해서는 www의 IP를 사용하도록 지정하는 방법이다.

 

☞ PTR 레코드는 A레코드와 상반된 개념이다. 즉 A레코드는 도메인에 대하여 IP를 부여 해줬지만 PTR 레코드는 IP주소에 대해 도메인명을 매핑하여 주는 역할을 한다. 보통 reverse zone 파일에서 사용을 한다.

'Developer' 카테고리의 다른 글

redmine  (0) 2012.03.26
Jboss Clustering  (0) 2012.03.19
Apache CGI 연동  (0) 2012.03.19
Apache2.2 + SSL 설치  (0) 2012.03.15
Binary Search ( 이진검색 ) Code  (0) 2012.03.09
댓글