Используем OpenDNS+DynDNS+pdnsd(или Bind) для защиты и ускорения на dynamic IP

Всем привет.
Нам потребуется:
1)Модем с поддержкой DynDNS(опционально)
2)UNIX система (опционально)
3)Прямые руки

Приступим:
1)Идём на DynDNS.com
Регистрируем там домен, в моём случае myhost.ath.cx
Затем переходим в модем, роутер, прогу и делаем синхронизацию с аккаунтом
2)Идём на OpenDNS.com
Проходим регистрацию
Настраиваем:
Во вкладке Networks ставим имя сети, задаём свой IP

Во вкладке Settings => Content Filtering => Choose your filtering level => Custom Выбираем необходимые фильтры контента.
3)Идём на dnsomatic.com
Аккаунт должен быть создан при регистрации на OpenDNS
Переходим на вкладку Your Services
Затем добавляем Service:DynDNS
User ID:Ваше имя на DynDNS
Password:Ваш пароль
Host/Identifier:Ваш хост, в моё случае myhost.ath.cx
Жмём Update Account Info
Затем добавляем Add a service:OpenDNS
Имя сети: имя указанное при вводе IP на OpenDNS
Жмём Update Account Info
4) Вписываем DNS OpenDNS в свой модем, соединение, и т.д
208.67.222.222
208.67.220.220


В принципе всё. Но мы идём дальше:

Поставим кэширующий DNS
Все действия описаны для Gentoo(Linux)
Для начала разберёмся с pdnsd
Я предпочёл его, за перманентный кэш.
1)Ставим pdnsd
В моём случае emerge pdnsd
Исходники доступны здесь
Переходим в /etc/pdnsd/
cd /etc/pdnsd/
Затем cp pdnsd.conf.sample pdnsd.conf
Правим:
У меня в конечном варианте выглядит так
// Sample pdnsd configuration file. Must be customized to obtain a working pdnsd setup!
// Read the pdnsd.conf(5) manpage for an explanation of the options.
// Add or remove '#' in front of options you want to disable or enable, respectively.
// Remove '/*' and '*/' to enable complete sections.

global {
perm_cache=4096;
cache_dir="/var/cache/pdnsd";
# pid_file = /var/run/pdnsd.pid;
run_as="pdnsd";
server_ip = 192.168.1.5; # Use eth0 here if you want to allow other
# machines on your network to query pdnsd.
status_ctl = on;
# paranoid=on; # This option reduces the chance of cache poisoning
# but may make pdnsd less efficient, unfortunately.
query_method=udp_tcp;
min_ttl=15m; # Retain cached entries at least 15 minutes.
max_ttl=1w; # One week.
timeout=10; # Global timeout option (10 seconds).
}

# The following section is most appropriate if you have a fixed connection to
# the Internet and an ISP which provides good DNS servers.
/*
server {
label= "myisp";
ip = 195.54.2.1; # Put your ISP's DNS-server address(es) here.
# proxy_only=on; # Do not query any name servers beside your ISP's.
# This may be necessary if you are behind some
# kind of firewall and cannot receive replies
# from outside name servers.
timeout=4; # Server timeout; this may be much shorter
# that the global timeout option.
uptest=if; # Test if the network interface is active.
interface=eth0; # The name of the interface to check.
interval=10m; # Check every 10 minutes.
purge_cache=off; # Keep stale cache entries in case the ISP's
# DNS servers go offline.
}

*/
/*
# The following section is more appropriate for dial-up connections.
# Read about how to use pdnsd-ctl for dynamic configuration in the documentation.
server {
label= "dialup";
file = "/etc/ppp/resolv.conf"; # Preferably do not use /etc/resolv.conf
proxy_only=on;
timeout=4;
uptest=if;
interface = ppp0;
interval=10; # Check if the interface every 10 seconds.
purge_cache=off;
preset=off;
}
*/

# The servers provided by OpenDNS are fast, but they do not reply with
# NXDOMAIN for non-existant domains, instead they supply you with an
# address of one of their search engines. They also lie about the addresses of
# of the search engines of google, microsoft and yahoo.
# If you do not like this behaviour the "reject" option may be useful.
server {
label = "opendns";
ip = 208.67.222.222, 208.67.220.220;
reject = 208.69.32.0/24, # You may need to add additional address ranges
208.69.34.0/24, # here if the addresses of their search engines
208.67.219.0/24; # change.
reject_policy = fail; # If you do not provide any alternative server
# sections, like the following root-server
# example, "negate" may be more appropriate here.
timeout = 4;
uptest = ping; # Test availability using ICMP echo requests.
ping_timeout = 100; # ping test will time out after 10 seconds.
interval = 15m; # Test every 15 minutes.
preset = off;
}
#Это нужно для того, что бы при отказе соединения или посещении запрещённого ресурса
#у вас выводилось окно OpenDNS, если нижнюю секцию opendns убрать то тогда
#в место окна OpenDNS будет показываться ошибка 404 вашего браузера.
server {
label= "opendns";
ip = 208.67.222.222,208.67.220.220; # Put your ISP's DNS-server address(es) here.
# proxy_only=on; # Do not query any name servers beside your ISP's.
# This may be necessary if you are behind some
# kind of firewall and cannot receive replies
# from outside name servers.
timeout=4; # Server timeout; this may be much shorter
# that the global timeout option.
uptest=if; # Test if the network interface is active.
interface=eth0; # The name of the interface to check.
interval=10m; # Check every 10 minutes.
purge_cache=off; # Keep stale cache entries in case the ISP's
# DNS servers go offline.
}

server {
label= "myisp";
ip = 195.54.2.1; # Put your ISP's DNS-server address(es) here.
# proxy_only=on; # Do not query any name servers beside your ISP's.
# This may be necessary if you are behind some
# kind of firewall and cannot receive replies
# from outside name servers.
timeout=4; # Server timeout; this may be much shorter
# that the global timeout option.
uptest=if; # Test if the network interface is active.
interface=eth0; # The name of the interface to check.
interval=10m; # Check every 10 minutes.
purge_cache=off; # Keep stale cache entries in case the ISP's
# DNS servers go offline.
}

# This section is meant for resolving from root servers.
server {
label = "root-servers";
root_server = on;
randomize_servers = on; # Give every root server an equal chance
# of being queried.
ip = 198.41.0.4
, 192.228.79.201
, 192.33.4.12
, 128.8.10.90
, 192.203.230.10
, 192.5.5.241
, 192.112.36.4
, 128.63.2.53
, 192.36.148.17
, 192.58.128.30
, 193.0.14.129
, 198.32.64.12
, 202.12.27.33
;
timeout = 5;
uptest = query; # Test availability using empty DNS queries.
interval = 30m; # Test every half hour.
ping_timeout = 300; # Test should time out after 30 seconds.
purge_cache = off;
exclude = .localdomain;
policy = included;
preset = off;
}
source {
owner=localhost;
# serve_aliases=on;
file="/etc/hosts";
}

/*
include {file="/etc/pdnsd.include";} # Read additional definitions from /etc/pdnsd.include.
*/

rr {
name=localhost;
reverse=on;
a=127.0.0.1;
owner=localhost;
soa=localhost,root.localhost,42,86400,900,86400,86400;
}

/*
neg {
name=doubleclick.net;
types=domain; # This will also block xxx.doubleclick.net, etc.
}
*/

/*
neg {
name=bad.server.com; # Badly behaved server you don't want to connect to.
types=A,AAAA;
}
*/

Думаю тут всё понятно
По непонятной причине pdnsd у меня так и не заработал, решил скомпилировать сам
cd /tmp
wget http://www.phys.uu.nl/~rombouts/pdnsd/releases/pdnsd-1.2.7-par.tar.gz
tar xvfz pdnsd-1.2.7-par.tar.gz
cd pdnsd-1.2.7
./configure --enable-ipv6 --program-prefix=/usr/local
make
cp /etc/pdnsd/pdnsd/pdnsd.conf /usr/local/etc/
cp -r src /usr/local/pdnsd
cd /usr/local/pdnsd
./pdnsd -d

Запуск в режиме Демона для проверки
Ставим bind-tools для проверки DNS
emerge bind-tools
dig ya.ru

Просмотр вывода, в моём случае
; <<>> DiG 9.4.2-P2 <<>> ya.ru
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 17622
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;ya.ru. IN A

;; ANSWER SECTION:
ya.ru. 6382 IN A 213.180.204.8

;; Query time: 1 msec
;; SERVER: 192.168.1.5#53(192.168.1.5)
;; WHEN: Sat Nov 22 13:22:42 2008
;; MSG SIZE rcvd: 39

Значит работает
Осталось добавить в автозапуск
Исправленный скрипт
#!/sbin/runscript
# Copyright 1999-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /var/cvsroot/gentoo-x86/net-dns/pdnsd/files/pdnsd.rc6,v 1.13 2007/07/13 07:46:00 mrness Exp $

opts="reload"

depend() {
need net
provide dns
}

checkconfig() {
if [ ! -e /usr/local/etc/pdnsd.conf ] ; then
eerror "You need an /usr/local/etc/pdnsd.conf file first."
eerror "There is a sample in /usr/local/etc/pdnsd.conf.sample"
return 1
fi
}

start() {
checkconfig || return 1
ebegin "Starting pdnsd"
start-stop-daemon --start --quiet --exec /usr/local/pdnsd/pdnsd -- -d -p /var/run/pdnsd.pid
eend $?
}

stop() {
ebegin "Stopping pdnsd"
start-stop-daemon --stop --quiet --pidfile /var/run/pdnsd.pid
eend $?
}

Убиваем pdnsd
Добавляем в автозапуск
rc-update add pdnsd default
Запускаем
/etc/init.d/pdnsd start
правим resolv.conf
nano /etc/resolv.conf
В моём случае
# Generated by dhclient for interface eth0
nameserver 192.168.1.5
nameserver 192.168.1.1 # на модеме то-же вписан OpenDNS+DNS провайдера
nameserver 208.67.222.222
nameserver 208.67.220.220

2) Для Bind
ставим его
emerge bind
правим конфиг
В моём случае:
options {
directory "/var/bind";

// uncomment the following lines to turn on DNS forwarding,
// and change the forwarding ip address(es) :
//forward first;
//forwarders {
// 123.123.123.123;
// 123.123.123.123;
//};

listen-on-v6 { none; };
listen-on { 127.0.0.1;192.168.1.5; };

// to allow only specific hosts to use the DNS server:
allow-query {
any;
};
forwarders { 208.67.222.222;208.67.220.220; }; // Здесь IP OpenDNS
// if you have problems and are behind a firewall:
query-source address * port 53;
pid-file "/var/run/named/named.pid";
};

// Briefly, a zone which has been declared delegation-only will be effectively
// limited to containing NS RRs for subdomains, but no actual data beyond its
// own apex (for example, its SOA RR and apex NS RRset). This can be used to
// filter out "wildcard" or "synthesized" data from NAT boxes or from
// authoritative name servers whose undelegated (in-zone) data is of no
// interest.
// See http://www.isc.org/products/BIND/delegation-only.html for more info

//zone "COM" { type delegation-only; };
//zone "NET" { type delegation-only; };

zone "." IN {
type hint;
file "named.ca";
};

zone "localhost" IN {
type master;
file "pri/localhost.zone";
allow-update { none; };
notify no;
};

zone "127.in-addr.arpa" IN {
type master;
file "pri/127.zone";
allow-update { none; };
notify no;
};

Сохраняем.
Запускаем
/etc/init.d/named start
Проверяем
dig ya.ru
Добавляем в атозапуск
rc-update add named default
Правим resolv.conf по образцу выше
nano /etc/resolv.conf

Всё.
UPD
После чтения доков по www.dnsomatic.com выяснилось, что это не совсем то, что нужно.
Это сервис для синхронизации IP между сервисами.
Для UNIX единственное, что предлагается, так это воспользоваться ddclient
Если техника позволяет, можно вписать с свой роутер, модем и т.д сервер updates.dnsomatic.com
Имя пользователя и пароль.
Мы же пойдём более простым путём:
Синхронизироваться будем через скрипт, который добавим в cron на выполнение каждые 10 минут
Для этого понадобится wget или curl
Wget:
wget -O - --no-check-certificate "https://имя_пользователя:пароль@updates.dnsomatic.com/nic/update?wildcard=YESG&mx=YES&backmx=NOCHG"
--14:13:23-- https://имя_пользователя:пароль@updates.dnsomatic.com/nic/update?wildcard=YESG&mx=YES&backmx=NOCHG
=> `-'

Resolving updates.dnsomatic.com... 67.215.64.64
Connecting to updates.dnsomatic.com|67.215.64.64|:443... connected.
WARNING: Certificate verification error for updates.dnsomatic.com: unable to get local issuer certificate
HTTP request sent, awaiting response... 200 OK
Length: 16 [text/html]

100%[============================================================================================================================>] 16 --.--K/s

14:13:24 (144.52 KB/s) - `-' saved [16/16]

Curl:
curl --insecure "https://имя_пользователя:пароль@updates.dnsomatic.com/nic/update?wildcard=YESG&mx=YES&backmx=NOCHG"
blog comments powered by Disqus