Ubuntu 22.04 에서 NSD 4.8.0 설치하기

리눅스/DNS|2023. 12. 19. 14:40
반응형

NLnet Labs 에서 제작한 NSD (Name Server Daemon) 은 BSD 라이센스를 가지고 있는 오픈소스 DNS 로써 속도, 신뢰성, 안정성 및 높은 보안성이 특징입니다. NSD 는 타 DNS 에 비해 월등히 빠른 속도를 보입니다. 몇 십만개 또는 몇 백만개의 쿼리를 요청하는 경우에도 쉽게 처리가 가능한 성능을 발휘하기 때문에 최상위 루트 네임서버중 몇 대는 NSD 로 사용되고 있다고 알려져 있습니다.

여기에서는 간단히 NSD 를 소스로 설치하고 sysdocu.kr 도메인을 등록해 질의 테스트하는 부분까지 안내합니다.

 

* 참고 : 패키지 설치 방법

# apt -y update

# apt -y install nsd

 

 

1. 설치

 

NSD 소스 파일을 다운로드 합니다.

공식 홈페이지에서는 현재 4.8.0 버전을 배포하고 있습니다.

- 공식 홈페이지 : https://nlnetlabs.nl/projects/nsd/about/
# wget https://nlnetlabs.nl/downloads/nsd/nsd-4.8.0.tar.gz

 

압축을 해제하고 설치 디렉토리로 이동합니다.

# tar xvzf nsd-4.8.0.tar.gz

# cd nsd-4.8.0


NSD 설치에 필요한 패키지를 사전 설치합니다.
# apt -y update
# apt -y install build-essential libssl-dev libevent-dev bison flex

 

NSD 설치를 계속 진행합니다.
# ./configure
# make
# make install

 

설치가 완료되었으면 명령어를 통해 설치 버전을 확인합니다.

# nsd -v
NSD version 4.8.0
Written by NLnet Labs.

Configure line:
Event loop: libevent 2.1.12-stable (uses epoll)
Linked with OpenSSL 3.0.2 15 Mar 2022

Copyright (C) 2001-2020 NLnet Labs.  This is free software.
There is NO warranty; not even for MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.

 

 

2. 설정

 

기본 설정 파일을 생성합니다.

# cp -arp /etc/nsd/nsd.conf.sample /etc/nsd/nsd.conf

 

기본 파일에 옵션이 많이 있는것을 확인할 수 있습니다.

하지만 모든 옵션에 대한 설명을 다루지 않을 예정이므로 아래와 같이 몇가지 옵션만으로 구성해 보겠습니다.

아래 내용에 없는 옵션을 사용하고자 할 경우 공식 Ducoment 를 참고하시기 바랍니다.

https://nsd.docs.nlnetlabs.nl/en/latest/manpages/nsd.conf.html

설정파일에 사용할 key 파일과 pem 파일은 생성 명령이 준비되어 있으므로, 우선 테스트를 위해 아래 도메인 부분만 보유한 도메인으로 변경하고, 나머지는 같은 내용으로 작성합니다.

# vi /etc/nsd/nsd.conf

server:
        server-count: 1
        ip-address: 0.0.0.0
        do-ip4: yes
        port: 53
        username: nsd
        zonesdir: "/etc/nsd"
        zonelistfile: "/var/db/nsd/zone.list"
        logfile: "/var/log/nsd.log"
        pidfile: "/var/run/nsd.pid"
        xfrdfile: ""
        tcp-count: 1000
        tcp-query-count: 0
        tcp-timeout: 120

remote-control:
        control-enable: yes
        control-interface: 127.0.0.1
        control-port: 8952
        server-key-file: /etc/nsd/nsd_server.key
        server-cert-file: /etc/nsd/nsd_server.pem
        control-key-file: "/etc/nsd/nsd_control.key"
        control-cert-file: "/etc/nsd/nsd_control.pem"

zone:
        name: "sysdocu.kr"
        zonefile: "sysdocu.kr.zone"

 

도메인을 여러개 등록하려는 경우 nsd.conf 파일 하단 3줄 (zone 부분) 을 복사하여 아래로 붙여넣고 도메인과 zone 파일명을 적절히 수정하면 됩니다.

설정이 제대로 되었는지 명령을 통해 확인합니다.

출력되는 내용은 고쳐야 하는 내용이며, 아무런 결과가 나오지 않으면 정상입니다.

# nsd-checkconf /etc/nsd/nsd.conf

 

설정파일에 사용했던 key 파일과 pem 파일을 생성합니다.

# nsd-control-setup
setup in directory /etc/nsd
Certificate request self-signature ok
subject=CN = nsd-control
removing artifacts
Setup success. Certificates created. Enable in nsd.conf file to use

 

생성된 key 파일과 pem 파일을 확인합니다.

# ll /etc/nsd
total 52
drwxr-xr-x   2 root root  4096 12월 21 10:56 ./
drwxr-xr-x 108 root root  4096 12월 20 22:38 ../
-rw-r--r--   1 root root   666 12월 21 10:56 nsd.conf
-rw-r--r--   1 root root 16685 12월 20 21:50 nsd.conf.sample
-rw-------   1 root root  2484 12월 21 10:56 nsd_control.key
-rw-r-----   1 root root  1484 12월 21 10:56 nsd_control.pem
-rw-------   1 root root  2484 12월 21 10:56 nsd_server.key
-rw-r-----   1 root root  1529 12월 21 10:56 nsd_server.pem

 

zone 파일을 생성합니다.

# vi /etc/nsd/sysdocu.kr.zone

$ORIGIN sysdocu.kr.
$TTL 86400

@       IN        SOA        ns1.sysdocu.kr. admin.sysdocu.kr. (
        2023121901  ;Serial
        7200        ;Refresh
        3600        ;Retry
        1209600     ;Expire
        3600        ;Negative response caching TTL
)

@               NS      ns1.sysdocu.kr.
@               NS      ns2.sysdocu.kr.
@               MX      10 mail.sysdocu.kr.
@               A       115.68.249.232
ns1             A       115.68.249.232
ns2             A       115.68.249.232
www             A       115.68.249.232
mail            A       115.68.249.232
*               A       115.68.249.232

 

마찬가지로 zone 파일의 설정이 제대로 되었는지 체크해봅니다.

형식) nsd-checkzone {zone이름} {zone파일}

# nsd-checkzone sysdocu.kr /etc/nsd/sysdocu.kr.zone
zone sysdocu.kr is ok

 

NSD 사용자를 생성합니다.

# useradd -r nsd

 

* 참고

이제 데몬을 구동해야 하는데, 이전에 53번 포트를 systemd-resolved  데몬이 사용하고 있을 경우 nsd 가 시작되지 않으므로 해당 데몬을 중지하고, 서버에서 외부 DNS 를 사용하기 위해서 /etc/resolv.conf 파일 최상단에 nameserver 8.8.8.8 를 추가해 줍니다.

방법은 netstat -nltp 로 확인이 가능합니다.

예) systemctl stop systemd-resolved

 

nsd 데몬을 구동하고 상태를 확인합니다.

# nsd-control start

# nsd-control status

version: 4.8.0
verbosity: 0

 

 

3. 테스트

 

외부에서 도메인 질의를 합니다.

 

# nslookup sysdocu.kr 115.68.249.135
Server: 115.68.249.135
Address: 115.68.249.135#53

Name: sysdocu.kr
Address: 115.68.249.232

 

# nslookup -type=mx sysdocu.kr 115.68.249.135
Server: 115.68.249.135
Address: 115.68.249.135#53

sysdocu.kr mail exchanger = 10 mail.sysdocu.kr.

 

반응형

댓글()

Ubuntu 22.04 에서 MaraDNS 3.5.0036 설치하기

리눅스/DNS|2023. 12. 17. 18:05
반응형

Ubuntu 22.04 에서 MaraDNS 설치하는 방법입니다.

apt 와 같은 패키지 관리 툴로 손쉽게 설치가 가능한 부분이 있지만,

# apt -y update

# apt -y install maradns

 

여기에서는 소스로 설치하고 관리하는 방법을 알려드립니다.

우선 MaraDNS 의 특징은 용량이 작고, 가볍고 (메모리 점유율이 낮음), 빠른 (Performance) 장점이 있습니다.

PowerDNS 는 DB 와 연동을하여 레코드로 zone 파일 내용을 관리하지만, MaraDNS 는 Bind 와 같이 파일로 레코드를 관리합니다.

 

 

1. 설치

 

소스를 설치하기 위해 gcc 컴파일러를 우선 설치 합니다.

# apt -y install gcc

 

그리고 현재 기준 MaraDNS 3.5.0036 버전을 다운로드하고 압축을 풀어 설치합니다.

- Download : https://maradns.samiam.org/download.html

# wget https://maradns.samiam.org/download/3.5/3.5.0036/maradns-3.5.0036.tar.xz

# tar xvf maradns-3.5.0036.tar.xz

# cd maradns-3.5.0036

# CC=cc

# export CC

# make

# make install

 

설치가 모두 마무리되면 출력된 내용과 같이 데몬을 실행해줍니다.

# systemctl start maradns
# systemctl start deadwood    // 필수 구동은 아니므로, 아래 설명 확인 후 구동 여부를 선택해주세요.

 

netstat 명령으로 포트가 확인되면 좋은데, MaraDNS 는 UDP 통신을 하므로, netstat 명령으로 포트가 확인되지 않아 프로세스 상태로 체크해봐야 합니다.

# systemctl status maradns

 

 

2. 설정

 

MaraDNS 는 역할에 따라 설정 파일이 두개로 나뉩니다.

 

1) /etc/mararc (관련 데몬 : maradns)

이 파일은 DNS 서버를 실행하는 데 사용되며, DNS 질의 및 응답 동작을 제어하는 다양한 설정을 포함합니다. 주요한 설정 사항은 zone 파일의 경로, Listen 주소, 캐싱 및 안전성 관련 설정 등이 있습니다.

 

2) /etc/dwood3rc (관련 데몬 : deadwood)

이 파일은 특정 환경에서의 DNS 서버 동작을 제어하는데 사용됩니다. DNS 캐시 설정, 불필요한 DNS 쿼리에 대한 차단, 차단된 도메인 목록 관리 등과 같은 설정을 포함할 수 있습니다. DNS 의 보안과 효율성을 향상시키는데 사용됩니다.

 

여기에서는 기본 설정만 다루겠습니다.

# vi /etc/mararc

csv2 = {}
csv2["sysdocu.kr."] = "db.sysdocu.kr"           # 등록할 도메인과 zone 파일 이름
ipv4_bind_addresses = "115.68.249.135"    # Binding 할 IP 주소 (ifconfig 로 확인되는 IP)
chroot_dir = "/etc/maradns"

 

* 외부 질의를 허용하려면 Binding 주소를 공인 IP 로 변경해야 합니다.

  VM 의 경우 ifconfig 명령으로 공인 IP 가 보이지 않는 경우에는 (공인과 연결된) 사설 IP 로 입력해 보시기 바랍니다.

 

도메인 zone 파일을 생성합니다.

# vi /etc/maradns/db.sysdocu.kr

sysdocu.kr.      +86400    soa    ns1.sysdocu.kr. dns@sysdocu.kr. 2023121701 86400 3600 604800 10800 ~
sysdocu.kr.      +86400    ns     ns1.sysdocu.kr. ~
sysdocu.kr.      +86400    ns     ns2.sysdocu.kr. ~
sysdocu.kr.      +86400    mx     10 mail.sysdocu.kr. ~
mail.sysdocu.kr. +86400    a      115.68.249.232 ~
ns1.sysdocu.kr.  +86400    a      115.68.249.232 ~
ns2.sysdocu.kr.  +86400    a      115.68.249.232 ~
sysdocu.kr.      +86400    a      115.68.249.232 ~
www.sysdocu.kr. +86400    a      115.68.249.232 ~

 

적용을 위해 데몬을 재시작 합니다.

# systemctl restart maradns

 

 

3. 테스트

 

로컬 또는 외부에서 질의 테스트를 해봅니다.

# nslookup sysdocu.kr 115.68.249.135
Server: 115.68.249.135
Address: 115.68.249.135#53

Name: sysdocu.kr
Address: 115.68.249.232

 

반응형

댓글()

PDNS (PowerDNS) 4.2 시스템 로그 및 쿼리 로그 설정

리눅스/DNS|2023. 3. 30. 07:52
반응형

PDNS 로그를 수집하고자 할때 아래와 같이 설정하면 됩니다.

아래는 PDNS 4.2 에서 테스트 하였습니다.

 

1. 설정

데몬 구동 파일을 백업하고 수정합니다.

# cp -arp /usr/lib/systemd/system/pdns.service /usr/lib/systemd/system/pdns.service.bak

# vi /usr/lib/systemd/system/pdns.service

...
[Service]
Type=notify
# rsyslog 사용하도록 아래 --disable-syslog 옵션 삭제
ExecStart=/usr/sbin/pdns_server --guardian=no --daemon=no --disable-syslog --log-timestamp=no --write-pid=no
# rsyslog 설정으로 넘겨주도록 아래 설정 추가
SyslogFacility=local0
SyslogLevel=debug
...

 

PDNS 설정을 추가합니다.

# vi /etc/pdns/pdns.conf

...
logging-facility=0
log-dns-details=yes  # DNS 설정 상 잘못된 세부 정보 로깅
log-dns-queries=yes # 유입되는 모든 질의 로깅
loglevel=5

...

 

rsyslog 설정을 추가합니다.

서비스 데몬 설정 상 debug level 로 해놓아서 아래 로깅 설정이 중요합니다.

vi /etc/rsyslog.conf

...
local0.=info                                    /var/log/pdns/pdns.info
local0.=warn                                  /var/log/pdns/pdns.warn
local0.=err                                     /var/log/pdns/pdns.err
local0.=debug                                /var/log/pdns/pdns.debug
...

 

로그 디렉토리를 생성합니다.

# mkdir /var/log/pdns

2. 적용

# systemctl daemon-reload
# systemctl restart pdns
# systemctl restart rsyslog

 

3. 확인

# cd /var/log/pdns
# ll
합계 145288
drwxr-xr-x  2 root root      4096  3월 29 09:41 .
drwxr-xr-x. 9 root root      4096  3월 29 16:37 ..
-rw-------  1 root root 147126477  3월 30 07:46 pdns.debug
-rw-------  1 root root       998  3월 29 09:30 pdns.err
-rw-------  1 root root      1331  3월 29 09:27 pdns.info
-rw-------  1 root root   1619633  3월 29 09:39 pdns.warn

 

pdns.debug 파일에 도메인 질의했던 Remote IP 와 Record Type, Domain name 등 정보가 간략히 출력되는데

참고로 packetcache 값은 아래 의미를 가지고 있습니다.

- HIT : 이전에 처리된 DNS 쿼리 결과가 캐시에 저장되어 있고, 현재 처리중인 쿼리와 동일한 결과를 반환할 수 있습니다.

           이 경우, pdns 서버는 저장된 정보를 즉시 반환하므로, 쿼리 처리 시간이 매우 빠릅니다.
- MISS : 이전에 처리된 DNS 쿼리 결과가 캐시에 없으며, 실제 DNS 서버에서 새로운 쿼리를 처리해야 합니다.

              이 경우, pdns 서버는 실제 DNS 서버로부터 결과를 가져와서 반환해야 하므로, 쿼리 처리 시간이 증가할 수 있습니다.

 

* 참고

도메인 질의가 많은 서버의 경우 로그 파일 사이즈도 방대하게 늘어나기 때문에

아래 URL 참고하여 logrotate 로 로그 파일을 관리 하면 됩니다.

(내용중 PDNS 설정 부분 참조)

https://sysdocu.tistory.com/63

반응형

댓글()

네임서버 DNS 퍼포먼스 테스트 (dnsperf)

리눅스/DNS|2023. 3. 28. 16:14
반응형

네임서버 성능을 확인하기 위해 다량의 도메인 질의를 해 볼 수 있습니다.

아래 설치 및 사용 방법을 확인해 주세요.

CentOS 7 기준으로 작성되었습니다.

 

1. 설치

# cd /usr/local/src

# wget https://www.dns-oarc.net/files/dnsperf/dnsperf-2.3.2.tar.gz
# tar xfvz dnsperf-2.3.2.tar.gz
# cd dnsperf-2.3.2/
# ./configure
# make
# make install

 

2. 사용

도메인을 질의하기 위해 테스트 또는 유명 도메인과 A 레코드를 질의하기 위해 A 값을 파일로 만듭니다.

# echo "sysdocu.kr A" > list.txt

 

아래와 같은 형식으로 테스트가 가능합니다.

# dnsperf -s 8.8.8.8 -d list.txt -T 2 -Q 1000 -l 1

* 옵션 설명

- s : 네임서버 IP 또는 도메인 (생략시 127.0.0.1)

- d : 도메인 또는 도메인이 들어있는 파일명

- T : 사용할 스레드 수

- Q : 쿼리량

- l : 질의 지속 시간 (초)

 

1초에 1000개 쿼리 수행 결과는 아래와 같이 나옵니다.

DNS Performance Testing Tool
Version 2.3.2

[Status] Command line: dnsperf -s 8.8.8.8 -d list.txt -T 2 -Q 1000 -l 1
[Status] Sending queries (to 8.8.8.8)
[Status] Started at: Tue Mar 28 16:16:00 2023
[Status] Stopping after 1.000000 seconds
[Status] Testing complete (time limit)

Statistics:

  Queries sent:         1000
  Queries completed:    1000 (100.00%)
  Queries lost:         0 (0.00%)

  Response codes:       NOERROR 1000 (100.00%)
  Average packet size:  request 28, response 112
  Run time (s):         1.000256
  Queries per second:   999.744066

  Average Latency (s):  0.000880 (min 0.000374, max 0.019629)
  Latency StdDev (s):   0.001580

반응형

댓글()

[TIP] Docker 룰이 포함된 iptables 룰 저장 및 복구

리눅스/DNS|2022. 12. 22. 16:53
반응형

[TIP] Docker 룰이 포함된 iptables 룰 저장 및 복구

 

iptables 기본 룰에서 docker 컨테이너등을 실행하면 컨테이너가 사용하는 포트의 연결을 위해

자동으로 iptables 룰이 추가됩니다.

하지만 iptables 룰을 잘못 수정하였다가 컨테이너 서비스가 먹통 되는 일이 생기는데 이를 방지하기 위해

iptables 룰을 주기적으로 저장해 두어야 합니다.

 

-----------------------------------

# iptables -nL
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy DROP)
target     prot opt source               destination         
DOCKER-USER  all  --  0.0.0.0/0            0.0.0.0/0           
DOCKER-ISOLATION-STAGE-1  all  --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain DOCKER (2 references)
target     prot opt source               destination         
ACCEPT     tcp  --  0.0.0.0/0            192.168.96.2         tcp dpt:3306
ACCEPT     tcp  --  0.0.0.0/0            192.168.96.3         tcp dpt:443
ACCEPT     tcp  --  0.0.0.0/0            192.168.96.4         tcp dpt:9000
ACCEPT     tcp  --  0.0.0.0/0            192.168.96.3         tcp dpt:80

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
target     prot opt source               destination         
DOCKER-ISOLATION-STAGE-2  all  --  0.0.0.0/0            0.0.0.0/0           
RETURN     all  --  0.0.0.0/0            0.0.0.0/0           

Chain DOCKER-ISOLATION-STAGE-2 (2 references)
target     prot opt source               destination         
DROP       all  --  0.0.0.0/0            0.0.0.0/0           
RETURN     all  --  0.0.0.0/0            0.0.0.0/0           

Chain DOCKER-USER (1 references)
target     prot opt source               destination         
RETURN     all  --  0.0.0.0/0            0.0.0.0/0           

-----------------------------------

 

현재 iptables 룰 저장

# iptables-save > iptables_20221222.rules

 

백업한 iptables 룰 복원

# iptables-restore < iptables_20221222.rules

 

혹시 백업해둔 룰이 없을땐 서비스 중지를 감수하고 docker 를 재시작 하면 컨테이너가 구동되면서 iptables 룰이 재구성 됩니다.

# systemctl restart docker

 

반응형

댓글()

bind 9 설치 (Ubuntu 19.04)

리눅스/DNS|2019. 10. 29. 10:31
반응형

우분투 19.04 버전에서 네임서버를 운영하기 위한 절차 입니다.

아래 절차만 순차적으로 따라하셔도 구축이 되며,

사용하고 계신 A, MX, CNAME 레코드 등에 대해서는 알맞게 레코드를 추가하여 설정하시면 됩니다.



1. 설치


root@sysdocu:~# apt -y install bind9



2. 도메인 설정


파일을 열어 아래 내용을 추가 합니다.


root@sysdocu:~# vi /etc/bind/named.conf.local


zone "sysdocu.com" IN {

  type master;

  file "sysdocu.com.zone";

};



새로운 zone 파일을 생성하여 내용을 입력합니다.


root@sysdocu:~# vi /var/cache/bind/sysdocu.com.zone


$TTL 600

@       IN      SOA     ns1.sysdocu.com. root (

                                        2019102901  ; serial

                                        1D        ; refresh

                                        1H        ; retry

                                        1W        ; expire

                                        3H )      ; minimum

@       IN      NS      ns1.sysdocu.com.

@       IN      NS      ns2.sysdocu.com.

@       IN      MX      10 mail.sysdocu.com.

@       IN      TXT     "v=spf1 ip4:192.168.10.2 ~all"

ns1     IN      A       192.168.10.2

ns2     IN      A       192.168.10.2

@       IN      A       192.168.10.2

www     IN      A       192.168.10.2

mail    IN      A       192.168.10.2

*       IN      A       192.168.10.2



설정한 내용을 적용합니다.


root@sysdocu:~# systemctl enable bind9

root@sysdocu:~# systemctl restart bind9



3. 질의 테스트


1) 로컬에서 질의 확인


root@sysdocu:~# nslookup sysdocu.com localhost

Server: localhost

Address: ::1#53


Name: sysdocu.com

Address: 192.168.10.2



2) 외부에서 질의 확인


[root@localhost ~]# nslookup sysdocu.com 192.168.10.2

Server: 192.168.10.2

Address: 192.168.10.2#53


Name: sysdocu.com

Address: 192.168.10.2



4. 참고

- 네임서버로 사용하기 위해 방화벽에서 UDP 53 번 포트 허용하는 것은 필수 입니다.

- 도메인 구입처에서 호스트 및 네임서버를 변경하면 시간이 한참 지나 적용이 될 수 있으므로

  이점 참고하여 운영하시기 바랍니다.


반응형

댓글()

DDNS 구축하기 (PDNS 사용자)

리눅스/DNS|2015. 1. 26. 17:36
반응형

PDNS 에 DDNS 기능이 있는것 같은데, 아직 개발 단계에 있다는 말도 있고..

SSH 키를 이용해 인증하는것 같아 제 나름의 방법대로 구축 방법을 기술하였습니다.



1. Client 설정


Client 서버에서 네임서버로 IP 정보를 전송해야 하므로, Client 서버에 아래와 같은 명령을 이용하여 주기적으로 IP를 체크업데이트 할 수 있도록 해야합니다.

아래 인증 방법 두 가지 중 하나를 이용하면 됩니다.



인증 방법1

# lynx -source -auth=아이디:패스워드 'http://ns1.sysdocu.com/update.php?도메인'


인증 방법2

# wget -O - --http-user=아이디 --http-passwd=패스워드 'http://ns1.sysdocu.com/update.php?도메인'



위 스크립트가 5분마다 자동 실행될 수 있도록 자동 스케쥴러에 등록해 놓습니다.

아래 예에서는 아이디 및 패스워드갱신할 도메인 sysdocu.com 을 실제로 입력하였습니다.


# crontab -e


*/5 * * * * wget -O - --http-user=sysdocu --http-passwd=PassW0rD 'http://ns1.sysdocu.com/update.php?sysdocu.com'



2. Server 설정


네임서버에서는 Client 서버의 IP 정보를 수시로(1분 마다체크 하고 있다가 변경되어질 때업데이트 합니다.


그래서 Client 서버에서 보내오는 신호를 체크하고 DB에 저장된 IP값과 비교, IP 값이 다를 경우 업데이트 하는 스크립트를 만들어야 합니다.


우선 pdns DB에 users 테이블을 추가합니다. 아이디로 검색해 본인이 사용하는 도메인이 맞는지 확인하기 위해 사용됩니다.


# vi users.sql


CREATE TABLE users (

no INT PRIMARY KEY AUTO_INCREMENT,

id varchar(255),

domain varchar(255)

) Engine=InnoDB;


# mysql -p pdns < users.sql

Enter password:  (패스워드 입력)


추후에 사용할때는 users 테이블에 실제 사용하는 아이디랑 도메인이 들어가 있어야 작동을 합니다.

예) user1    sysdocu.com

      user1    www.sysdocu.com

      user2    system.sysdocu.com


# touch /usr/local/apache/htdocs/update.php    // ns1.sysdocu.com 의 기본 디렉토리 안에 빈페이지를 생성합니다.


# vi /root/ipcheck.sh


#!/bin/bash


cat /usr/local/apache/logs/ns1.sysdocu.com-access_log |grep 'update.php' |grep '200 -' |awk {'print $1" "$3" "$7'} |sed -e 's/\/update.php?//' > temp.txt

cat /dev/null > /usr/local/apache/logs/ns1.sysdocu.com-access_log


while read newIP USER Host trash

do


접속계정과 호스트를 이용해 DB의 저장값을 불러옵니다.

authuser=`mysql -updns -p12345678 pdns -e "SELECT COUNT(*) FROM users WHERE id='$USER' AND domain='$Host'" |tail -n 1`


저장값이 있으면 아이피값이 같은지 비교다를경우 업데이트합니다.

if [ "$authuser" = "1" ]; then

oldIP=`mysql -updns -p12345678 pdns -e "select content from records where name='$Host' and type='A'" |tail -n 1`


if [ "$oldIP" != "$newIP" ]; then

mysql -mysql -updns -p12345678 pdns -e "UPDATE records SET content='$newIP' where name='$Host' and type='A'"

fi


else

echo ""

fi


done < temp.txt


rm -f temp.txt



이제 위 스크립트가 1분마다 자동으로 실행될 수 있도록 자동 스케쥴러에 등록해 놓습니다.


# crontab -e


* * * * * sh /root/ipcheck.sh



또한 인증 받은 사람만(아이디패스워드로 확인업데이트가 가능하도록 아파치 웹인증 암호를 걸어 놓습니다.


# cd /usr/local/apache/htdocs    // ns1.sysdocu.com 의 기본 디렉토리


# vi .htaccess


AuthName "User Authorization"

AuthType Basic

AuthUserFile /usr/local/apache/htdocs/.htpasswd

AuthGroupFile /dev/null

<Limit GET>

require valid-user

</Limit>



# /usr/local/apache/bin/htpasswd -c .htpasswd sysdocu

New password : ********

Re-type new password : ********


위와 같이 아이디 sysdocu 와 그에 해당하는 패스워드를 설정했습니다이제 생성한 아이디패스워드 사용자만 update.php 파일에 접근이 가능합니다.


여기에 아이디패스워드를 추가 할때는 -c 옵션을 빼고 동일하게 명령을 수행하면 됩니다.

그리고 .htpasswd 파일의 위치를 잘 입력해주어야 합니다현재 디렉토리에서는 파일명만 적되다른 디렉토리에 위치한 상태에서 명령을 내릴 때는 절대경로또는 상대경로를 이용하여 위치를 정확히 입력합니다.


# /usr/local/apache/bin/htpasswd .htpasswd UserID


-c 옵션은 초기 사용자를 생성 할때만 사용됩니다여러개의 아이디를 만든 후 -c 옵션을 잘못 주었다면 기존의 아이디가 모두 사라져버리므로 주의를 해야 합니다. (주기적으로 인증 파일 백업 권장)


참고 이용자 삭제

# /usr/local/apache/bin/htpasswd -D .htpassd UserID


반응형

댓글()

wireshark 로 DNS 쿼리 모니터링 하기

리눅스/DNS|2015. 1. 26. 17:36
반응형
1. 설치
# yum -i install wireshark


2. 사용
# tshark -nni eth0 -f 'udp port 53' -t a -w result.txt

-f 'udp port 53'    // UDP PORT 53번에 대해서만 캡쳐
-t a                // 시간 출력 (절대값)
-w result.txt       // 출력 내용 저장 (result.txt 라는 이름의 바이너리 파일 생성)

아래는 결과 인데, 쿼리 하나에 라인이 두 개 출력됩니다.
윗줄은 요청, 아랫줄은 응답(response)입니다.

0.000000 192.168.10.100 -> 192.168.10.2 DNS Standard query A ns1.sysdocu.com
0.000365 192.168.10.2 -> 192.168.10.100 DNS Standard query response A 192.168.10.2

위 예제처럼 result.txt 로 저장한 데이타는 바이너리로 저장되기 때문에 vi 에디터로 열면 글자가 깨져서 보입니다.
출력 내용을 보려면 -r 옵션을 이용하면 됩니다.

# tshark -r result.txt


반응형

댓글()

dnstop 설치 (DNS 쿼리량 순서로 모니터링)

리눅스/DNS|2015. 1. 26. 17:35
반응형
1. 환경 구성
사전 설치 패키지 (필수 요소 : libpcap, libpcap-devel)
# yum -y install libpcap*


2. 설치
이제 dnstop 을 설치해봅니다.

# cd /usr/local/src
# tar xvzf dnstop-20121017.tar.gz
# cd dnstop-20121017
# ./configure
# make
# make install

다른 버전이 있나 살펴볼 때에는 위 URL에서 파일명만 빼고 접속을 해보면 됩니다.


3. 사용 방법

쿼리 요청 Source IP 순서대로 출력합니다.
# dnstop


요청 도메인이 많은 순서로 출력합니다.
- 이때 옵션이 사용되는데, 도메인의 점(.)을 기준으로 몇개의 자리까지 출력할것인지 정합니다. 
  (아래 -l9 와 같이 옵션을 사용할 경우에는 9.8.7.6.5.4.3.sysdocu.com 까지 출력)

# dnstop eth0 -l9

실행 후 9 를 눌러야 원하는 결과를 얻을 수 있습니다. (또는 shift + 9)

* 옵션값을 -l2 로 했을경우 질의를 www.sysdocu.com 으로 하면, sysdocu.com 만 출력 됩니다.
  그러므로 잘못 표기되는 도메인이 없도록 최대값 -l9 를 쓰도록 합니다.
* shift + 9 를 누르게 되면 질의 요청한 Client IP 도 리스트에 같이 출력됩니다.


반응형

댓글()

PDNS의 다양한 에러 로그 및 해결책

리눅스/DNS|2015. 1. 26. 17:35
반응형
제가 운영하며 겪었던 오류 메세지 및 해결책입니다.
국내 문서는 거의 희박하여 해결하는데 고생했습니다...
같은 오류가 출력되는 분을 위해 기록해둡니다.


[에러]
Jan 20 10:23:10 ns1 pdns[18253]: AXFR of domain 'sysdocu.com' failed: not authoritative

[해결]
pdns.conf 파일에 disable-axfr=no 설정

--------------------------

[에러]
Jan 20 10:56:32 ns1 pdns[12973]: Received a malformed qdomain from 27.102.207.197, 'http://sysdocu.com': sending servfail

[해결]
설정상의 특별한 문제가 있는것이 아니므로 무시해도 됩니다.
쿼리를 도메인으로 하지 않고 잘못된 쿼리를 요청해서 응답할 수 없다고 나타나는 메세지 입니다.

예)
nslookup http://sysdocu.com ns1.sysdocu.com    // 잘못된 쿼리
nslookup sysdocu.com ns1.sysdocu.com          : // 정상 쿼리

--------------------------

[에러]
Jan 20 10:27:23 ns1 pdns[3077]: Recursive query for remote 176.31.191.182:25345 with internal id 65 was not answered by backend within timeout, reusing id

[해결]
recursor=168.126.63.1 이와 같이 ISP 업체 네임서버를 사용하더라도 정보를 받아오는데 시간이 걸리기 때문에 발생한 문제입니다.
이를 해결하려면 자체 네임서버(pdns 구동 서버)의 pdns-recursion 설정을 통해 해결하면 됩니다.

# vi /etc/pdns-reursor/recursor.conf
setuid=pdns-recursor
setgid=pdns-recursor
config-dir=/etc/pdns-recursor/
daemon=yes
local-port=54
socket-dir=/var/run/

version-string=ns1.sysdocu.com 


pdns-recursor 를 54번 포트로 구동합니다.
# /etc/init.d/pdns-recursor start

그리고 pdns.conf 파일 옵션중 recursor 만 아래 내용으로 수정합니다.
recursor=127.0.0.1:54

끝으로 pdns 를 재시작 해줍니다.
# /etc/init.d/pdns restart

--------------------------

[에러]
Jan 20 13:57:52 ns9 pdns[18384]: Discarding packet from recursor backend with id 18397, qname or qtype mismatch

[해결]
질의 응답은 정상적이나 messages 로그에 대량의 로그가 쌓입니다.
이는 /etc/resolv.conf 의 네임서버와 pdns.conf 의 recursor 설정 IP가 맞지 않아서 발생하는 문제이므로
recursor 에 설정한 IP를 /etc/resolv.conf 에 설정한 IP와 동일하게 맞추어 주면 됩니다.


반응형

댓글()

BIND9를 위한 로그 설정

리눅스/DNS|2015. 1. 26. 17:35
반응형

BIND는 오픈 소스의 성격에 맞게 다양한 로그와 디버거 정보를 제공하고 있습니다.

특히 로그는 성격에 맞게 Category로 나누어져 있으며, Category별로 다양하게 저장이 가능합니다.

 

시스템의 부하와 디스크의 공간이 있다면 로그를 많이 남겨두는 것이 장애시 분석을 가능하게 하는 방법입니다. 가급적이면 로그를 많이 남겨두는 것이 좋습니다.

 

로그는 named.conf에 적용을 하면 되며, 카테고리별 설명은 아래와 같습니다.

 

default

The default category defines the logging options for those categories where no specific configuration has been defined.

general

The catch-all. Many things still aren't classified into categories, and they all end up here.

database

Messages relating to the databases used internally by the name server to store zone and cache data.

security

Approval and denial of requests.

config

Configuration file parsing and processing.

resolver

DNS resolution, such as the recursive lookups performed on behalf of clients by a caching name server.

xfer-in

Zone transfers the server is receiving.

xfer-out

Zone transfers the server is sending.

notify

The NOTIFY protocol.

client

Processing of client requests.

unmatched

Messages that named was unable to determine the class of or for which there was no matching view. A one line summary is also logged to the clientcategory. This category is best sent to a file or stderr, by default it is sent to thenull channel.

network

Network operations.

update

Dynamic updates.

update-security

Approval and denial of update requests.

queries

Specify where queries should be logged to.

At startup, specifying the category queries will also enable query logging unlessquerylog option has been specified.

The query log entry reports the client's IP address and port number, and the query name, class and type. It also reports whether the Recursion Desired flag was set (+ if set, - if not set), EDNS was in use (E) or if the query was signed (S).

client 127.0.0.1#62536: query: www.example.com IN AAAA +SE

client ::1#62537: query: www.example.net IN AAAA -SE

dispatch

Dispatching of incoming packets to the server modules where they are to be processed.

dnssec

DNSSEC and TSIG protocol processing.

lame-servers

Lame servers. These are misconfigurations in remote servers, discovered by BIND 9 when trying to query those servers during resolution.

delegation-only

Delegation only. Logs queries that have have been forced to NXDOMAIN as the result of a delegation-only zone or a delegation-only in a hint or stub zone declaration.

 

아래는 BIND9에서 제공하는 모든 Category를 적용한 샘플입니다. 

logging {
	channel "default_syslog" {
		// Send most of the named messages to syslog.
		syslog local2;
		severity debug;
	};
	channel "default_syslog" {
		file "log/default.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "general_syslog" {
		file "log/general.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "database_syslog" {
		file "log/database.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "security_syslog" {
		file "log/security.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "config_syslog" {
		file "log/config.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "resolver_syslog" {
		file "log/resolver.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "xfer-in_syslog" {
		file "log/xfer-in.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "xfer-out_syslog" {
		file "log/xfer-out.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "notify_syslog" {
		file "log/notify.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "client_syslog" {
		file "log/client.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "unmatched_syslog" {
		file "log/unmatched.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "network_syslog" {
		file "log/network.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "update_syslog" {
		file "log/update.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "update_security_syslog" {
		file "log/update_security.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "queries_syslog" {
		file "log/queries.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "dispatch_syslog" {
		file "log/dispatch.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "dnssec_syslog" {
		file "log/dnssec.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "lame-servers_syslog" {
		file "log/lame-servers.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};
	channel "delegation-only_syslog" {
		file "log/delegation-only.log" versions 3 size 20m;
		severity debug;
		print-category yes;
		print-severity yes;
		print-time yes;
	};

	category default { default_syslog; };
	category general { default_syslog; };
	category database { database_syslog; };
	category security { security_syslog; };
	category config { config_syslog; };
	category resolver { resolver_syslog; };
	category xfer-in { xfer-in_syslog; };
	category xfer-out { xfer-out_syslog; };
	category notify { notify_syslog; };
	category client { client_syslog; };
	category unmatched { unmatched_syslog; };
	category network { network_syslog; };
	category update { update_syslog; };
	category update-security { update_security_syslog; };
	category queries { queries_syslog; };
	category dispatch { dispatch_syslog; };
	category dnssec { dnssec_syslog; };
	category lame-servers { lame-servers_syslog; };
	category delegation-only { delegation-only_syslog; };	
};

[출처] BIND9를 위한 로그 설정|작성자 네임서버

네임서버 이야기 | 네임서버 (http://blog.naver.com/netpiadns/50021687725)


[출처] 네임서버 이야기 | 네임서버 (http://blog.naver.com/netpiadns/50021687725)



반응형

댓글()