Openbsd настройка dns сервера
Схема сети показана на схеме 1.
Схема 1. Схема сети.
В качестве базовой была выбрана ОС OpenBSD 4.6 (последняя версия на момент написания).
Вот все исходные данные использованные при написании данной статьи.
Благодарности за помощь в написании статьи:
Efim
Часть 1 - Простейший маршрутизатор
        "Когда орёл летит, забывает ли он о том, что его лапы касались земли?
        Когда тигр после прыжка настигает свою жертву, забывает ли он о
        моменте, проведённом в воздухе? Три фунта VAX!"
                UNIX-коаны Мастера Фу.
Если вы еще не читали введение, то настоятельно рекомендуется прочитать его до чтения данного раздела, во избежание недоразумений.
Оформляя каждую функцию в отдельную задачу, рассмотрим их решение.
1. Установка соединения с провайдером
Забегая вперед, опишу преимущества и недостатки, которыми обладает каждый из способов, помимо очевидных. При использовании связки ppp(8) и pppoe(8), имеется возможность гибкого использования LCP (Link Control Protocol). Основным достоинством здесь является получение в момент установления соединения адресов DNS-серверов провайдера и динамическое обновление файла resolv.conf(5). Так же можно отметить наличие встроенного NAT в ppp(8). Но в процессе тестирования обнаружился один существенный недостаток - ppp(8) ни в какую не хочет восстанавливать оборвавшееся соединение. Что касается интерфейса pppoe(4) ядра, то недостаток тут один, но существенный - невозможно запрашивать DNS-сервера провайдера и автоматически обновлять resolv.conf(5).
1.1. Связка ppp(8) и pppoe(8)
Для начала потребуется написать конфигурационный файл /etc/ppp/ppp.conf [2]. Вообще для проверки возможно использовать интерактивный режим, но файл - надежнее.
Листинг 1.1.1. Конфигурационный файл /etc/ppp/ppp.conf
Устанавливаем права доступа (рекомендуется). После этого только владелец ppp.conf (т. е. root) сможет его читать. А, если вы не забыли, там лежит пароль от PPPoE.
Теперь проверяем соединение.
Если соединение работает нормально, можно настроить автоматическое включение при запуске. Для отключения соединения, необходимо послать управляющему демону сигнал HUP.
На этом можно было бы и закончить, но не могу не упомянуть о включении встроенного NAT в ppp(8). Для этого требуется передать всего один ключ "-nat", т.е. файл для автоматического поднятия PPPoE соединения будет выглядеть следующим образом.
Листинг 1.1.4. Автоматическое поднятие интерфейса с поддержкой NAT
1.2. Использование интерфейса pppoe(4)
Теперь рассмотрим другой, не совместимый с предыдущим, вариант установления соединения. Интерфейс pppoe(4) по-умолчанию поддерживается ядром, для его создания используем файл следующего содержания.
Листинг 1.2.1. Создание pppoe(4) интерфейса
Устанавливаем права на созданный конфигурационный файл интерфейса (опять же, рекомендуется, потому что в нем лежат логин и пароль от PPPoE).
И включаем новый интерфейс.
Если вы используете данный тип соединения, то для разрешения имен со шлюза (и только с него) вам потребуется вручную настроить resolv.conf(5). Потребуется указать адрес DNS-сервера, например можно указать сервера провайдера, или локального DNS-сервера.
В листинге 1.2.4 приведен пример настройки resolv.conf(5), где w.x.y.z и a.b.c.d - IP-адреса DNS-серверов провайдера.
Листинг 1.2.4. Пример resolv.conf(5)
Если вы используете (планируете использовать) сервер имен, запущенный на шлюзе (на том же самом узле) и никаких хитрых настроек производить не собираетесь, то файл /etc/resolv.conf можно оставить пустым - по умолчанию, если не указан ни один DNS-сервер, обращение идет к серверу по адресу 127.0.0.1.
2. Включение маршрутизации
Это самый простой этап. Для того, что бы просто включить маршрутизацию IP-пакетов, выполняется следующая команда[1].
Чтобы маршрутизация включалась при запуске системы, правим sysctl.conf - добавляем или раскомментируем строку "net.inet.ip.forwarding=1"[1].
Листинг 2.1. Включение маршрутизации при запуске.
3. Трансляция адресов (NAT) с помощью pf(4)
Если вы выбрали вариант со связкой ppp(8) & pppoe(8) и включили NAT в ppp(8) (см. раздел 1.1.1), то данный раздел можно пропустить или просто ознакомиться для общего развития. Использование pf(4) для трансляции адресов имеет ряд преимуществ и, как минимум, один недостаток. Этот недостаток заключается в увеличении общей сложности, т.е. использовании все больших элементов для достижения цели. Положительный момент тоже один, но за то какой: возможность гармонично использовать всю мощь межсетевого экрана (МСЭ) pf(4). Это и навороченная фильтрация, и т.н. проброс портов, и шейпинг - перечислять можно еще пару абзацев. Таким образом, если нужна только трансляция адресов и выбран вариант с ppp(8), то от использования pf(4) можно отказаться, но если требуются еще какой-то функционал МСЭ, а тем более если используется интерфейс pppoe(4), то pf(4) - это то что вам нужно.
Хороший краткий обзор дан в [5], в этой же статье приведены ссылки на дополнительные материалы для изучения, здесь приведу только простой конфигурационный файл и команды для запуска. Конфигурация pf(4) находится в /etc/pf.conf (pf.conf(5)). Для управления используется утилита pfctl(8).
Листинг 3.1. pf.conf(5) с поддержкой NAT
Данный вариант не лишен многих недостатков, но он работает имеет некоторые настройки безопасности и достаточно краток. Теперь конфигурацию необходимо применить.
После проведения данных манипуляций можно проверить работоспособность конфигурации, запустив ping(8) на одном из узлов внутренней сети до узла из внешней сети. Лучше всего проверить доступность DNS-серверов провайдера, используя в качестве адреса назначения IP-адрес DNS-сервера. Во-первых, проверятся работоспособность маршрутизации, соединения, NAT, а во-вторых, использование IP-адреса снимает необходимость в DNS-сервере для разрешения имен, о чем в следующем разделе. Если тестирование прошло нормально, можно проверить применение настроек при запуске системы.
У вас может быть еще куча разных строк, но наличие этих двух свидетельствует о том, что настройки будут применяться после каждого запуска системы. Если вы не обнаружили этих строк, то необходимо прописать их в /etc/rc.conf.local (перед этим стоит почитать rc.conf(5)).
4. Поддержка DNS
Почему важна корректная настройка DNS-серверов можно посмотреть в [4] и [6], только не пытайтесь сразу применять советы из статьи. Итак, как сказано в [4], в поставку OpenBSD начиная в версии 4.0 уже включен настроенный DNS-сервер, все что требуется - это включить его.
Теперь можно проверить доступность и работоспособность DNS-сервера на одном из узлов внутренней сети, например с помощью nslookup(1). В случае, если все работает корректно, необходимо включить автоматический запуск.
Существует еще один способ настройки службы DNS - на каждом узле во внутренней сети указать адреса DNS-серверов провайдера и не использовать отдельный сервер на шлюзе, но такая настройка таит множество подводных камней, и необходимо точно знать, что вы делаете и зачем.
Самое неожиданное - многие провайдеры практикуют полную блокировку доступа к внешним ресурсам при дебетовой (предоплатной) системе расчётов и исчерпании средств на балансе расчётного счета. А это влечет за собой проблемы с разрешением имен внутренних сервисов, например для того, чтобы пополнить баланс счета с помощью карты оплаты.
5. Настройка узлов внутренней сети
Настройка внутренних узлов достаточна проста и сводится к установке шлюза по умолчанию и адреса DNS-сервера. В качестве этих адресов указывается адрес внутреннего интерфейса шлюза. В моем случае, это 192.168.0.254 (см. Схему 1 во введении). Конкретные действия, которые необходимо предпринять, зависят от операционной системы, установленной на конкретном узле, и их описание выходит за рамки данной статьи.
6. Заключение
Что бы собрать все воедино рассмотрим несколько возможных контрольных сценариев настройки шлюза в зависимости от выбранных технологий. Более подробное описание шагов описано в соответствующем разделе статьи.
6.1. Связка ppp(8) & pppoe(8), встроенный NAT
6.2. Интефейс pppoe(4), pf(4)
6.3. Связка ppp(8) & pppoe(8), pf(4) NAT
7. Список литературы
размещено: 2010-03-01,
последнее обновление: 2011-11-23,
автор: BlackCat
mamutoff, 2010-03-02 в 16:36:43
orig>Для этого требуется предать всего один ключ "-nat"
Наверное все-таки "передать.
BlackCat, 2010-03-02 в 19:01:49
gerk, 2010-03-09 в 14:56:52
BlackCat, 2010-03-09 в 15:16:27
2 grek: этот вопрос в третьей части раскрывается.
XIX, 2011-03-31 в 8:53:28
ваше утверждение не совсем верно:
\"ppp(8) ни в какую не хочет восстанавливать оборвавшееся соединение\"
я тоже так думал, потом почитал про ppp и теперь соединение восстанавливается при разрыве. Крутить надо:
enable lqr echo
set cd 60
set redial x0 x1 (x0,x1 значения параметров сейчас не помню)
Keen, 2011-04-29 в 15:43:32
"6.3. Связака ppp(8) & pppoe(8), pf(4) NAT"
Связака - это выпускник связного училища? =)
BlackCat, 2011-04-29 в 15:55:22
2Keen, он самый: ходит тунели всем в интернеты настраивает, пакеты вручную транслирует - очень полезный человек в штате.
Вот это внимательность - никто не заметил, даже проверяльщик орфограффии. Вечером исправлю.
alex, 2011-10-07 в 17:44:42
2 BlackCat:
Вечером какого дня и какого года=))?
BlackCat, 2011-10-08 в 22:55:29
2 alex: видимо у меня Одесские корни. Если звёзды сойдутся, то этого года.
BlackCat, 2011-11-23 в 23:20:14
Этот информационный блок появился по той простой причине, что многие считают нормальным, брать чужую информацию не уведомляя автора (что не так страшно), и не оставляя линк на оригинал и автора — что более существенно. Я не против распространения информации — только за. Только условие простое — извольте подписывать автора, и оставлять линк на оригинальную страницу в виде прямой, активной, нескриптовой, незакрытой от индексирования, и не запрещенной для следования роботов ссылки.
Если соизволите поставить автора в известность — то вообще почёт вам и уважение.
The network configuration will use a 192.168.1.0/24 subnet for the wired clients and 192.168.2.0/24 for the wireless. Add the following, changing the mode/channel if needed: OpenBSD defaults to allowing only WPA2-CCMP connections in HostAP mode. If support for older (insecure) protocols is needed, they must be explicitly enabled.
The dhcpd(8) daemon should be started at boot time to provide client machines with IP addresses. The following dhcpd.conf(5) example also provides static IP reservations for a laptop and server based on their MAC addresses. Any RFC 1918 address space may be specified here. The domain-name-servers line in this example specifies a local DNS server that will be configured in a later section.
Firewall
OpenBSD's PF firewall is configured via the pf.conf(5) file. It's highly recommended to become familiar with it, and PF in general, before copying this example. A gateway configuration might look like this: The ruleset's various sections will now be explained: The wired and wireless interface names for the LAN are defined with macros, used to make overall maintenance easier. Macros can be referenced throughout the ruleset after being defined. This is a table of non-routable private addresses that will be used later. PF allows certain options to be set at runtime. The block-policy decides whether rejected packets should return a TCP RST or be silently dropped. The loginterface specifies which interface should have packet and byte statistics collection enabled. These statistics can be viewed with the pfctl -si command. In this case, the egress group is being used rather than a specific interface name. By doing so, the interface holding the default route ( em0 ) will be chosen automatically. Finally, skip allows a given interface to be omitted from packet processing. The firewall will ignore traffic on the lo(4) loopback interface. The match rules used here accomplish two things: normalizing incoming packets and performing network address translation, with the egress interface between the LAN and the public internet. For a more detailed explanation of match rules and their different options, refer to the pf.conf(5) manual. The antispoof keyword provides some protection from packets with spoofed source addresses. Incoming packets should be dropped if they appear to be from the list of unroutable addresses defined earlier. Such packets were likely sent due to misconfiguration, or possibly as part of a spoofing attack. Similarly, clients should not attempt to connect to such addresses. The "return" action is specified to prevent annoying timeouts for users. Note that this can cause problems if the router itself is also behind NAT. The firewall will set a "default deny" policy for all traffic, meaning that only incoming and outgoing connections which have been explicitly put in the ruleset will be allowed. Allow outgoing IPv4 traffic from both the gateway itself and the LAN clients. Allow internal LAN traffic. Forward incoming connections (on TCP ports 80 and 443, for a web server) to the machine at 192.168.1.2. This is merely an example of port forwarding.
While a DNS cache is not required for a gateway system, it is a common addition to one. When clients issue a DNS query, they'll first hit the unbound(8) cache. If it doesn't have the answer, it goes out to the upstream resolver. Results are then fed to the client and cached for a period of time, making future lookups of the same address quicker. Something like this should work for most setups: Further configuration options can be found in the unbound.conf(5) manual. Outgoing DNS lookups can also be encrypted with the dnscrypt-proxy package or with unbound's built-in DNS over TLS support.
If the router should also use the caching resolver, its /etc/resolv.conf file should contain
The resolv.conf file specifies how the resolver routines in the C library (which provide access to the Internet Domain Name System) should operate. The resolver configuration file contains information that is read by the resolver routines the first time they are invoked by a process. If the resolv.conf file does not exist, only the local host file /etc/hosts will be consulted, i.e. the Domain Name System will not be used to resolve hosts.
The file is designed to be human readable and contains a list of keywords with values that provide various types of resolver information. A resolv.conf file is not required for some setups, so this file is optional. It can be created manually, and is also created as part of the OpenBSD install process if use of the DHCP protocol is specified for any interface or if any DNS name servers are configured.
nameserver IPv4 address (in dot notation) or IPv6 address (in hex-and-colon notation) of a name server that the resolver should query. Scoped IPv6 address notation is accepted as well (see inet6(4) for details).
Up to ASR_MAXNS (currently 5) name servers may be listed, one per line. If there are multiple servers, the resolver library queries them in the order listed. If no nameserver entries are present, the default is to use the name server on the local machine. (The algorithm used is to try a name server, and if the query times out, try the next, until out of name servers, then repeat trying all name servers until a maximum number of retries are performed.)
If the lookup keyword is not used in the system's resolv.conf file then the assumed order is bind file . Furthermore, if the system's resolv.conf file does not exist, then the only database used is file .
search Search list for hostname lookup. The search list is normally determined from the local domain name; by default, it begins with the local domain name, then successive parent domains that have at least two components in their names. This may be changed by listing the desired domain search path following the search keyword with spaces or tabs separating the names. Most resolver queries will be attempted using each component of the search path in turn until a match is found. Note that this process may be slow and will generate a lot of network traffic if the servers for the listed domains are not local, and that queries will time out if no server is available for one of the domains.
The search list is currently limited to six domains with a total of 1024 characters. Only one search line should appear; if more than one is present, the last one found overwrites any values found in earlier lines.
sortlist Allows addresses returned by gethostbyname(3) to be sorted. A sortlist is specified by IP address netmask pairs. The netmask is optional and defaults to the natural netmask of the net. The IP address and optional network pairs are separated by slashes. Up to 10 pairs may be specified. For example:
family Specify which type of Internet protocol family to prefer, if a host is reachable using different address families. By default IPv4 addresses are queried first, and then IPv6 addresses. The syntax is:
A maximum of two families can be specified, where family can be any of:
If only one family is specified, only that family is tried.
options Allows certain internal resolver variables to be modified. The syntax is:
Where option is one of the following:
debug Print debugging messages, if libc is compiled with DEBUG . By default on OpenBSD this option does nothing. edns0 Attach an OPT pseudo-RR for the EDNS0 extension, as specified in RFC 2671. This informs DNS servers of a client's receive buffer size, allowing them to take advantage of a non-default receive buffer size, and thus send larger replies. DNS query packets with the EDNS0 extension are not compatible with non-EDNS0 DNS servers, so the option must be used only when all the servers listed in nameserver lines are able to handle the extension.
To verify whether a server supports EDNS, query it using the dig(1) query option +edns=0 : the reply indicates compliance (EDNS version 0) and whether a UDP packet larger than 512 bytes can be used. Note that EDNS0 can cause the server to send packets large enough to require fragmentation. Other factors such as packet filters may impede these, particularly if there is a reduced MTU, as is often the case with pppoe(4) or with tunnels.
inet6 On OpenBSD this option does nothing. On some operating systems, this option enables IPv6 support in gethostbyname(3) by setting RES_USE_INET6 in _res.options (see res_init(3)). insecure1 Do not require IP source address on the reply packet to be equal to the server's address. insecure2 Do not check if the query section of the reply packet is equal to that of the query packet. For testing purposes only. ndots : n Sets a threshold for the number of dots which must appear in a name given to res_query(3) before an initial absolute query will be made. The default for n is 1, meaning that if there are any dots in a name, the name will be tried first as an absolute name before any search list elements are appended to it. tcp Forces the use of TCP for queries. Normal behaviour is to query via UDP but fall back to TCP on failure. trust-ad A name server indicating that it performed DNSSEC validation by setting the Authentic Data (AD) flag in the answer can only be trusted if the name server itself is trusted and the network path is trusted. Generally this is not the case and the AD flag is cleared in the answer. The trust-ad option lets the system administrator indicate that the name server and the network path are trusted. This option is automatically enabled if resolv.conf only lists name servers on localhost.
The domain and search keywords are mutually exclusive. If more than one instance of these keywords is present, the last instance will override.
LOCALDOMAIN A space-separated list of search domains, overriding the search keyword of a system's resolv.conf file. RES_OPTIONS A space-separated list of resolver options, overriding the options keyword of a system's resolv.conf file.
Network configuration in OpenBSD is done with text files in /etc . Typically, these settings are initially configured during the installation process.
Identifying and Setting Up Network Interfaces
Interfaces are named by the type of card, not the type of connection. For example, here's a dmesg(8) snippet for an Intel Fast Ethernet network card: This device uses the fxp(4) driver and is assigned the number 0 here.
The ifconfig(8) utility will show what network interfaces have been identified on a system. This sample shows only one physical Ethernet interface: fxp0 . An IP is configured on it, hence the values inet 10.0.0.38 netmask 0xffffff00 broadcast 10.0.0.255 . The UP and RUNNING flags are also set on it.
-
- Encapsulating interface - Loopback interface - Packet Filter logging interface
Checking Stats on NFS
One thing to check to ensure NFS is operating properly is that all the daemons have properly registered with RPC. To do this, use rpcinfo(8). There are a few utilities that allow an administrator to see what is happening with NFS, such as showmount(8) and nfsstat(1).
This is my network.
It is mine
or technically my employer's,
it is my responsibility
and I care for it with all my heart
there are many other networks a lot like mine,
but none are just like it.
I solemnly swear
that I will not mindlessly paste from HOWTOs.
Клятва системного администратора.
(c) Peter N. M. Hansteen[6]
Как уже было сказано в первой части, правильно настроенный DNS поможет избежать многих трудностей. Настройка DNS-сервера named(8) по-умолчанию - работает, но простой кэширующий сервер - это только вершина айсберга. Настройка проведена по мотивам статей [1] и [3], сверяясь с [4].
1. Простая настройка dhcpd(8)
* Данный параметр не является обязательным, но так удобнее.
** О настройке NTP сервера читать часть 4. WinXP так и не удалось заставить использовать эту опцию.
В результате получаем конфигурационный файл следующего содержания.
Листинг 1.1. Конфигурационный файл dhcpd.conf(5)
Запускаем dhcpd(8) на внутреннем интерфейсе и проверяем его работоспособность.
Если все проверки прошли успешно, добавляем автоматический запуск.
Осталось настроить узлы внутри сети на автоматическое получение настроек через DHCP.
2. Более тонкая настройка DNS-сервера
Основные задачи, которые решались при доведении стандартного конфига:
1. использование только IPv4 (отключить IPv6);
2. управление сервером только локально;
3. выполнение запросов только из локальной (внутренней) сети;
4. разрешение всех имен через корневые сервера (рекурсивные запросы);
5. разрешение имен из зоны провайдера через DNS-сервера провайдера;
6. поддержка зоны internal.lan и обратной зоны 0.168.192.in-addr.arpa - локальная сеть.
Некоторые комментарии относительно каждого пункта:
1. IPv6 не используется в моей сети, а лишние сервисы - это дыра в системе безопасности;
2. управлять DNS-сервером буду только со шлюза - еще один элемент безопасности;
3. без комментариев;
4. защита от проблем с сервером провайдера (если его скомпрометируют);
5. сохранение возможности работать с внутренними ресурсами провайдера, если с внешними будут проблемы.
6. поддерживать внутреннюю зону - полезно;
Эти комментарии даны для того, что бы вы могли определить ненужные вам настройки и не использовать их.
Здесь и далее предполагается, что локальный DNS-сервер запущен (см. Часть 1). Пойдем по порядку и выполним первые четыре пункта. В результате получили следующий конфигурационный файл.
Листинг 2.1. Первая версия named.conf(5)
Проверяем правильность конфигурационного файла.
Если синтаксических ошибок не обнаружено, перезагружаем конфигурационный файл и проверяем работоспособность DNS-сервера.
Далее, во исполнении пункта первого, отредактируем rc.conf.local, что бы named(8) запускался с поддержкой только IPv4.
Теперь, вручную, перезапустим named(8) с новыми параметрами.
Теперь настроим разрешение имен сети провайдера, в первую очередь, через DNS-сервера провайдера, для этого добавим дополнительную зону в named.conf(5). Тип зоны установим "forward" и разрешим выполнять рекурсивный запрос, если DNS сервер провайдера упадет.
Листинг 2.6. Разрешение имен через DNS-сервер провайдера
Результирующий конфигурационный файл представлен в листинге 2.7, изменения заключаются только в добавлении новой зоны.
Листинг 2.7. Полный конфигурационный файл named.conf(5) c поддержкой DNS провайдера
Далее проверяем синтаксис и применяем новые настройки (листинг 2.2, листинг 2.3). Теперь самая интересная часть, добавим поддержку DNS для локальной сети. Перед добавлением зон в named.conf(5), напишем сами зоны и сохраним в /var/named/master.
Написание зоны задача непростая, но данный процесс хорошо описан в [5], а подглядывание в [4] сделает задачу элементарной.
Листинг 2.8. Описание зоны "internal.lan"
Листинг 2.9. Описание зоны "0.168.192.in-addr.arpa"
Имена файлов могут быть любыми, они не несут конфигурационной нагрузки. Теперь проверяем правильность конфигурации зон.
В качестве параметров утилите передаются имя зоны и файл с её описанием.
Если проверка прошла успешно, переходим к добавлению зон в named.conf(5). Потребуется добавить две зоны, для которых данный сервер будет мастером. Итоговая конфигурация представлена в листинге 2.11.
Листинг 2.11. Конфигурация с поддержкой внутренних зон (прямой и обратной)
Проверяем синтаксис и применяем новую конфигурацию (листинг 2.2, листинг 2.3). Теперь можно проверить работоспособность данной конфигурации.
Name: gate.internal.lan
Address: 192.168.0.254
254.0.168.192.in-addr.arpa name = gate.internal.lan.
Теперь необходимо проверить работу с одного из узлов локальной сети. После завершения проверок файлы зон можно дополнить описанием новых узлов в сети, по примеру "gate.internal.lan" (одна A запись в прямой зоне и одна PTR запись в обратной зоне).
Для проверки зон, которые поддерживает named(8), подойдет следующая последовательность действий.
3. Динамическое обновление DNS-записей для локальной сети
В начале необходимо поставить DHCP-сервер из коллекции пакетов, т.к. входящий в базовую поставку сервер не поддерживает динамического обновления.
Сервер будет установлен в /usr/local. Теперь необходимо решить вопрос с его автоматическим запуском и при этом избежать конфликта с уже установленным DHCP-сервером. Автор [1] предлагает заменить бинарные файлы старого сервера на новые. Но можно пойти другим путем: дописать команды запуска в rc.local и использовать конфигурационный файл с другим именем, например - dhcpd-isc.conf. Но все по порядку. Начнем с того, что создадим конфигурационный файл для нового сервера. Для этого скопируем старый файл (см. разд. 1.) и после глобальных параметров добавим строку "ddns-update-style none;". В результате должен получиться конфигурационный файл следующего содержания.
Листинг 3.2. Конфигурационный файл для нового DHCP-сервера
Проверим работоспособность сервера, перед этим остановив встроенный.
Листинг 3.4. Код автозапуска нового DHCP-сервера
Данный код позволяет запускать новый сервер не конфликтуя со старым, единственный минус в том, что параметр dhcpd_isc_flags должен быть равен "NO" или должен отсутствовать файл /etc/dhcpd-isc.conf для того, что бы сервер не запустился. Т.е. для прекращения его автоматического запуска придется приложить некоторые усилия (простым удалением строки не обойтись), но новый сервер ставят и прописывают на автозапуск не для того, что бы держать выключенным.
После этого удаляем строку "dhcpd_flags" из rc.conf.local (для избежания конфликтов) и добавляем параметр dhcpd_isc_flags с указанием интерфейса для автоматического запуска.
Единственным способом проверить работоспособность конфигурации - перезагрузить систему. Если все прошло нормально и сервер успешно раздает адреса, то переходим к связыванию DHCP- и DNS-серверов. В начале создадим новый ключ для взаимодействия dhcpd и named.
Создадим новый файл в /var/named/etc, который будет содержать сгенерированный ключ, следующего содержания.
Листинг 3.7. Новый ключ для named(8)
Не забываем о владельце и правах доступа.
Перед разрешением обновления зон необходимо установить корректные права доступа [1,3].
Далее необходимо подключить новый ключ к named.conf(5) и разрешить обновление зон "internal.lan" и "0.168.192.in-addr.arpa".
Листинг 3.10. Измененный named.conf(5)
Проверяем синтаксис и применяем новую конфигурацию.
Теперь скопируем ключ dhcp.key в директорию /etc (не забывая о правах).
В результате получим следующий конфигурационный файл.
Листинг 3.13. Конфигурационный файл DHCP-сервера с поддержкой обновления DNS-записей
Перезапускаем DHCP-сервер и проверяем, обновляются ли данные при выделении адреса узлу.
Внимание: записи для узлов со статически указанным IP-адресом обновляться не будут. Такие записи необходимо вручную внести в файлы зон.
4. Список литературы
размещено: 2010-03-01,
последнее обновление: 2010-10-15,
автор: BlackCat
konstantine, 2010-10-15 в 4:45:02
Зачем это вообще надо .
BlackCat, 2010-10-15 в 8:01:10
В статье это описано, но повторюсь: "сохранение возможности работать с внутренними ресурсами провайдера, если с внешними будут проблемы". Если требуется более подробный ответ - добро пожаловать на форум (ссылка на обсуждение в конце статьи).
Этот информационный блок появился по той простой причине, что многие считают нормальным, брать чужую информацию не уведомляя автора (что не так страшно), и не оставляя линк на оригинал и автора — что более существенно. Я не против распространения информации — только за. Только условие простое — извольте подписывать автора, и оставлять линк на оригинальную страницу в виде прямой, активной, нескриптовой, незакрытой от индексирования, и не запрещенной для следования роботов ссылки.
Если соизволите поставить автора в известность — то вообще почёт вам и уважение.
Configuring a Wireless Adapter
Adapters based on supported chips can be used like any other network interface. To connect an OpenBSD system to an existing wireless network, use the ifconfig(8) utility.
An example of a hostname.if(5) file for a wireless client might be: Or, for multiple access points: Note that inet autoconf should be after the other configuration lines, as the network adapter will not be able to send a DHCP request until it is configured.
Setting Up a Network Bridge
A bridge(4) is a link between two or more separate networks. Unlike a router, packets go through the bridge transparently: the two network segments appear as one to nodes on either side. Bridges will only forward packets that have to pass from one segment to the other and, as a result, an interface in a bridge may or may not have an IP address of its own. If it does, the interface has effectively two modes of operation: one as part of a bridge, the other as a stand-alone NIC. If neither interface has an IP address, the bridge will pass network data, but will not be externally maintainable (which can be a feature).
Activating the Changes
From here, either reboot or run the netstart(8) script: A few warnings may be produced when running this script if the interfaces have already been configured. Use ifconfig(8) to make sure the interfaces were set up correctly.
Even though it's possible to completely reconfigure networking on a running OpenBSD system, a reboot is recommended after any significant changes.
DHCP Client
To use dhcpleased(8), edit the hostname.if(5) file of the network interface. The wireless networking section explains how to set up wireless interfaces. For ethernet interfaces, one line is enough: OpenBSD will gather its IP address, default gateway, and DNS servers from the DHCP server at startup time. Other options can be specified in dhcpleased.conf(5).
To get an IP via DHCP from the command line, run: Replace xl0 with the interface name.
PXE Booting (i386, amd64)
The Preboot Execution Environment (PXE) is a standard method of booting systems using only the network. A client's PXE-capable NIC broadcasts a DHCP request at the start of the boot process and, rather than only receiving basic IP/DNS information, is also given a file to boot from. On OpenBSD, this file is known as pxeboot(8), and is typically served by tftpd(8).
Trunking a Wireless Adapter
Trunks are virtual interfaces consisting of one or more network interfaces. In this section, our example will be a laptop with a wired bge0 interface and a wireless iwn0 interface. We will build a trunk(4) interface using both of them. The wired and wireless interfaces must be connected to the same layer two network.
To do this, we first activate the two physical ports, then assign them to trunk0 . The wireless interface, however, needs a bit more configuration. It will need to attach to our wireless WPA-protected network: Now, our trunk interface is defined like this: The trunk is set up in failover mode, so either interface can be used. If both are available, it will prefer the bge0 port, since that is the first one added to the trunk device.
Wireless Networking
OpenBSD has support for a number of wireless chipsets. Further supported devices can be found in usb(4) and pci(4). The precise extent of their support is described in the driver man pages.
-
- TI ACX100/ACX111 - Atheros 802.11a/b/g - Atheros 802.11/a/g/n devices - Broadcom and Cypress IEEE 802.11a/ac/b/g/n wireless network device - Conexant/Intersil Prism GT Full-MAC 802.11a/b/g and ural(4) - Ralink Technology RT25x0 802.11a/b/g - Realtek 8180 802.11b - Ralink Technology RT2501USB - Prism2/2.5/3
Another option to consider: use a conventional NIC and an external bridging wireless access point for the OpenBSD-based firewall.
Tips on Bridging
- By using the blocknonip option of ifconfig(8) or in hostname.bridge0, non-IP traffic (such as IPX or NETBEUI) can be prevented from slipping around the filters. This may be important in some situations, but be aware that bridges work for all kinds of traffic, not just IP.
- Bridging requires that the NICs be in a promiscuous mode. They listen to all network traffic, not just that directed at the interface. This will put a higher load on the processor and bus than one might expect.
Mounting NFS Filesystems
To mount the /docs filesystem on host 10.0.0.1 to local filesystem /mnt , run: To have that filesystem mounted at boot, append a line to fstab(5) like so: It is important to use 0 0 at the end of this line so that the computer does not try to fsck(8) the NFS filesystem on boot.
When accessing an NFS mount as the root user, the server automatically maps root's access to username nobody and group nobody . This is important to know when considering file permissions. For example, take a file with these permissions: If this file was on an NFS share and the root user tried to access this file from the NFS client, access would be denied.
The user and group that root are mapped to are configurable via the exports(5) file on the NFS server.
Dynamic Host Configuration Protocol
The Dynamic Host Configuration Protocol (DHCP) is a way to configure network interfaces automatically. OpenBSD can be a DHCP server that configures other machines or a DHCP client that is configured by a DHCP server.
DHCP Server
To use OpenBSD as a DHCP server, enable the dhcpd(8) daemon at startup: On the next boot, dhcpd will run and attach to all NICs that have valid configurations in dhcpd.conf(5). Individual interfaces may be specified instead by naming them explicitly: An example /etc/dhcpd.conf file might look like this: There are two subnets in this example: a home network and a guest network. Clients will automatically be given an IP address and pointed to the gateway and DNS servers specified in their respective sections of the config file. See dhcp-options(5) for more options.
DNS Resolution
Default Hostname and Gateway
The /etc/myname and /etc/mygate files are read by the netstart(8) script. Both of these files consist of a single line, specifying the fully qualified domain name of the system and the address of the gateway host, respectively. The /etc/mygate file need not exist on all systems. See myname(5) for more details.
Checking Routes
Using NFS
This section will go through the steps for a simple NFS setup. The example details a server on a LAN, with clients accessing NFS on the LAN. It does not cover securing NFS.
Filtering on a Bridge
PF can be used to restrict what traffic goes through a bridge. Keep in mind, by the nature of a bridge, the same data flows through both interfaces, so filtering is only needed on one interface.
Setting Up Aliases on an Interface
In this example, two aliases are added to the interface dc0 , which was configured as 192.168.0.2 with a netmask of 255.255.255.0 . Once this file has been created, run netstart or reboot. To view all aliases, use ifconfig -A .
A Bridge Acting as a DHCP Server
Let's say we have a system which has four vr(4) interfaces, vr0 through vr3 . We want to bridge vr1 , vr2 and vr3 together, leaving out vr0 for the uplink. We also want to serve IP addresses through DHCP over the bridged interfaces. Being a DHCP server and an uplink router, the box needs to have an IP address on the bridged network.
- The DHCP server configuration is not described yet again in this section, but the addressing scheme used here is the same.
- This will also be the uplink router for the bridged network, so we will use IP address 192.168.1.1 to match the DHCP server configuration.
- We will not cover the uplink, routing or firewalling configuration here.
Equal-Cost Multipath Routing
Equal-cost multipath routing refers to having multiple routes in the routing table for the same network, such as the default route, 0.0.0.0/0 . When the kernel is doing a route lookup to determine where to send packets destined to that network, it can choose from any of the equal-cost routes. In most scenarios, multipath routing is used to provide redundant uplink connections, e.g., redundant connections to the internet.
The route(8) command is used to add/change/delete routes in the routing table. The -mpath argument is used when adding multipath routes. Verify the routes: In this example we can see that one default route points to 10.130.128.1 , which is accessible via the fxp1 interface, and the other points to 10.132.0.1 , which is accessible via fxp2 .
Since the mygate(5) file does not yet support multipath default routes, the above commands should be added to the bottom of the hostname.if(5) files for the fxp1 and fxp2 interfaces. The /etc/mygate file should then be deleted. Lastly, don't forget to activate the use of multipath routes by enabling the proper sysctl(8) variable. Be sure to edit sysctl.conf(5) to make the changes permanent.
Now try a traceroute to different destinations. The kernel will load balance the traffic over each multipath route. For more information about how the route is chosen, please refer to RFC2992, "Analysis of an Equal-Cost Multi-Path Algorithm".
It's worth noting that if an interface used by a multipath route goes down (i.e., loses carrier), the kernel will still try to forward packets using the route that points to that interface. This traffic will of course be blackholed and end up going nowhere. It's highly recommended to use ifstated(8) to check for unavailable interfaces and adjust the routing table accordingly.
Setting Up an NFS Server
First, enable the portmap(8), mountd(8) and nfsd(8) services on the server: Then configure the list of filesystems that will be made available.
In this example, we have a server with the IP address 10.0.0.1 . This server will be serving NFS only to clients within its own subnet. This is configured in the following exports(5) file: The local filesystem /docs will be made available via NFS. The -alldirs option specifies that clients will be able to mount at any point under /docs as well as /docs itself. The -ro option specifies that clients will only be granted read-only access. The last two arguments specify that only clients within the 10.0.0.0 network using a netmask of 255.255.255.0 will be authorized to mount this filesystem.
Now start the server-related services: If changes are made to /etc/exports while NFS is already running, mountd must be made aware of this.
Читайте также: