1

Тема: Пара вопросов udhcpd и dnsmasq

Никак не могу решить 2 проблемы. Помогите советом.

Как предотвратить замену /var/udhcpd.conf . При старте заменяю его на свой, но он тут же меняется обратно на стандартный. Необходимо выдавать адреса dns серверов из resolv.conf, а не адрес роутера.

И по dnsmasq. Как заставить его висеть только на br0. -i br0 и -a [ip-address] нужного результата не дают.
К тому же dnsmasq при переподключении к интернету перезапускается с заводскими параметрами.

2

Re: Пара вопросов udhcpd и dnsmasq

Ну вот по второму вопросу: ps у меня выдает
dnsmasq -u root --all-servers -k
Далее смотрим

~ # dnsmasq --help
Usage: dnsmasq [options]

Valid options are:
-a, --listen-address=ipaddr             Specify local address(es) to listen on.
-A, --address=/domain/ipaddr            Return ipaddr for all hosts in specified domains.
-b, --bogus-priv                        Fake reverse lookups for RFC1918 private address ranges.
-B, --bogus-nxdomain=ipaddr             Treat ipaddr as NXDOMAIN (defeats Verisign wildcard).
-c, --cache-size=cachesize              Specify the size of the cache in entries (defaults to 150).
-C, --conf-file=path                    Specify configuration file (defaults to /etc/dnsmasq.conf).
-d, --no-daemon                         Do NOT fork into the background: run in debug mode.
-D, --domain-needed                     Do NOT forward queries with no domain part.
-e, --selfmx                            Return self-pointing MX records for local hosts.
-E, --expand-hosts                      Expand simple names in /etc/hosts with domain-suffix.
-f, --filterwin2k                       Don't forward spurious DNS requests from Windows hosts.
-F, --dhcp-range=ipaddr,ipaddr,time     Enable DHCP in the range given with lease duration.
-g, --group=groupname                   Change to this group after startup (defaults to dip).
-G, --dhcp-host=<hostspec>              Set address or hostname for a specified machine.
    --dhcp-hostsfile=<filename>         Read DHCP host specs from file.
    --dhcp-optsfile=<filename>          Read DHCP option specs from file.
    --tag-if=tag-expression             Evaluate conditional tag expression.
-h, --no-hosts                          Do NOT load /etc/hosts file.
-H, --addn-hosts=path                   Specify a hosts file to be read in addition to /etc/hosts.
-i, --interface=interface               Specify interface(s) to listen on.
-I, --except-interface=int              Specify interface(s) NOT to listen on.
-j, --dhcp-userclass=set:<tag>,<class>  Map DHCP user class to tag.
    --dhcp-circuitid=set:<tag>,<circuit>Map RFC3046 circuit-id to tag.
    --dhcp-remoteid=set:<tag>,<remote>  Map RFC3046 remote-id to tag.
    --dhcp-subscrid=set:<tag>,<remote>  Map RFC3993 subscriber-id to tag.
-J, --dhcp-ignore=tag:<tag>...          Don't do DHCP for hosts with tag set.
    --dhcp-broadcast[=tag:<tag>...]     Force broadcast replies for hosts with tag set.
-k, --keep-in-foreground                Do NOT fork into the background, do NOT run in debug mode.
-K, --dhcp-authoritative                Assume we are the only DHCP server on the local network.
-l, --dhcp-leasefile=path               Specify where to store DHCP leases (defaults to /var/lib/misc/dnsmasq.leases).
-L, --localmx                           Return MX records for local hosts.
-m, --mx-host=host_name,target,pref     Specify an MX record.
-M, --dhcp-boot=<bootp opts>            Specify BOOTP options to DHCP server.
-n, --no-poll                           Do NOT poll /etc/resolv.conf file, reload only on SIGHUP.
-N, --no-negcache                       Do NOT cache failed search results.
-o, --strict-order                      Use nameservers strictly in the order given in /etc/resolv.conf.
-O, --dhcp-option=<optspec>             Specify options to be sent to DHCP clients.
    --dhcp-option-force=<optspec>       DHCP option sent even if the client does not request it.
-p, --port=number                       Specify port to listen for DNS requests on (defaults to 53).
-P, --edns-packet-max=<size>            Maximum supported UDP packet size for EDNS.0 (defaults to 4096).
-q, --log-queries                       Log DNS queries.
-Q, --query-port=number                 Force the originating port for upstream DNS queries.
-R, --no-resolv                         Do NOT read resolv.conf.
-r, --resolv-file=path                  Specify path to resolv.conf (defaults to /etc/resolv.conf).
-S, --server=/domain/ipaddr             Specify address(es) of upstream servers with optional domains.
    --local=/domain/                    Never forward queries to specified domains.
-s, --domain=<domain>[,<range>]         Specify the domain to be assigned in DHCP leases.
-t, --mx-target=host_name               Specify default target in an MX record.
-T, --local-ttl=time                    Specify time-to-live in seconds for replies from /etc/hosts.
    --neg-ttl=time                      Specify time-to-live in seconds for negative caching.
    --max-ttl=time                      Specify time-to-live in seconds for maximum TTL to send to clients.
-u, --user=username                     Change to this user after startup. (defaults to nobody).
-U, --dhcp-vendorclass=set:<tag>,<class>Map DHCP vendor class to tag.
-v, --version                           Display dnsmasq version and copyright information.
-V, --alias=addr,addr,mask              Translate IPv4 addresses from upstream servers.
-W, --srv-host=name,target,...          Specify a SRV record.
-w, --help                              Display this message. Use --help dhcp for known DHCP options.
-x, --pid-file=path                     Specify path of PID file (defaults to /var/run/dnsmasq.pid).
-X, --dhcp-lease-max=number             Specify maximum number of DHCP leases (defaults to 1000).
-y, --localise-queries                  Answer DNS queries based on the interface a query was sent to.
-Y, --txt-record=name,txt....           Specify TXT DNS record.
    --ptr-record=name,target            Specify PTR DNS record.
    --interface-name=name,interface     Give DNS name to IPv4 address of interface.
-z, --bind-interfaces                   Bind only to interfaces in use.
-Z, --read-ethers                       Read DHCP static host information from /etc/ethers.
-1, --enable-dbus                       Enable the DBus interface for setting upstream servers, etc.
-2, --no-dhcp-interface=interface       Do not provide DHCP on this interface, only provide DNS.
-3, --bootp-dynamic[=tag:<tag>]...      Enable dynamic address allocation for bootp.
-4, --dhcp-mac=set:<tag>,<mac address>  Map MAC address (with wildcards) to option set.
    --bridge-interface=iface,alias,..   Treat DHCP requests on aliases as arriving from interface.
-5, --no-ping                           Disable ICMP echo address checking in the DHCP server.
-6, --dhcp-script=path                  Script to run on DHCP lease creation and destruction.
-7, --conf-dir=path                     Read configuration from all the files in this directory.
-8, --log-facility=<facilty>|<file>     Log to this syslog facility or file. (defaults to DAEMON)
-9, --leasefile-ro                      Do not use leasefile.
-0, --dns-forward-max=<queries>         Maximum number of concurrent DNS queries. (defaults to 150)
    --clear-on-reload                   Clear DNS cache when reloading /etc/resolv.conf.
    --dhcp-ignore-names[=tag:<tag>]...  Ignore hostnames provided by DHCP clients.
    --dhcp-no-override                  Do NOT reuse filename and server fields for extra DHCP options.
    --enable-tftp[=<interface>]         Enable integrated read-only TFTP server.
    --tftp-root=<dir>[,<iface>]         Export files by TFTP only from the specified subtree.
    --tftp-unique-root                  Add client IP address to tftp-root.
    --tftp-secure                       Allow access only to files owned by the user running dnsmasq.
    --tftp-max=<connections>            Maximum number of conncurrent TFTP transfers (defaults to 50).
    --tftp-no-blocksize                 Disable the TFTP blocksize extension.
    --tftp-port-range=<start>,<end>     Ephemeral port range for use by TFTP transfers.
    --log-dhcp                          Extra logging for DHCP.
    --log-async[=<log lines>]           Enable async. logging; optionally set queue length.
    --stop-dns-rebind                   Stop DNS rebinding. Filter private IP ranges when resolving.
    --rebind-localhost-ok               Allow rebinding of 127.0.0.0/8, for RBL servers.
    --rebind-domain-ok=/domain/         Inhibit DNS-rebind protection on this domain.
    --all-servers                       Always perform DNS queries to all servers.
    --dhcp-match=set:<tag>,<optspec>    Set tag if client includes matching option in request.
    --dhcp-alternate-port[=<ports>]     Use alternative ports for DHCP.
    --dhcp-scriptuser=<username>        Run lease-change script as this user.
    --naptr-record=<name>,<naptr>       Specify NAPTR DNS record.
    --min-port=<port>                   Specify lowest port available for DNS query transmission.
    --dhcp-fqdn                         Use only fully qualified domain names for DHCP clients.
    --dhcp-generate-names[=tag:<tag>]...Generate hostnames based on MAC address for nameless clients.
    --dhcp-proxy[=<ip_address>]...      Use these DHCP relays as full proxies.
    --cname=<alias>,<target>            Specify alias name for LOCAL DNS name.
    --pxe-prompt=<prompt>,[<timeout>]   Prompt to send to PXE clients.
    --pxe-service=<service>             Boot service for PXE menu.
    --test                              Check configuration syntax.

Я так понимаю, дело в ключе --all-servers Может, ещё что-то надо ему сказать (например, ключ -I)?
Ну и аналогично можно про udhcpc посмотреть... (хотя тут мне не понятно уже...)
А перезапуск бороть можно, используя скрипт в firewal.d (в нём перезапускать dnsmasq "как надо")

UPD

Кстати(о resolv.conf ):

~ # cat /bin/init.sh | grep udhcp
        rm -f /var/udhcpc/resolv.conf 2> /dev/null
                PIDFILE=/etc/udhcpc/udhcpc-$interface.pid
        PIDFILE=/var/run/udhcpd.pid
SAVE_IP="/var/udhcpc/saveip*"

P.S.
Думаю, вашу задачу можно решить только "подправив" скрипты в прошивке. Это легко можно сделать, используя этот метод: http://forum.zyxmon.org/topic213-proshi … ianty.html

Отредактировано Dr.Acid (2012-10-03 21:02:33)

3

Re: Пара вопросов udhcpd и dnsmasq

pgw, скрипт ext_init.sh срабатывает (с разными параметрами) при подъеме  и разрыве физлинка, сессии. Туда иногда и следует вставлять вызов своих скриптов.

4

Re: Пара вопросов udhcpd и dnsmasq

Dr.Acid :

Ну вот по второму вопросу: ps у меня выдает
dnsmasq -u root --all-servers -k

Так я о том и писал, тушу dnsmasq -u root --all-servers -k, запускаю dnsmasq -u root -i br0 -k, но он упорно слушает все, а не только br0. А надо, чтобы на ppp0 слушал iodined, на br0 dnsmasq.
В добавок ко всему /bin/ppp-up.sh вызывает /bin/dns.sh, который перезапускает dnsmasq по своему.

Думаю, вашу задачу можно решить только "подправив" скрипты в прошивке. Это легко можно сделать, используя этот метод: http://forum.zyxmon.org/topic213-proshi … ianty.html

А вот это, похоже, как раз то, что нужно. Спасибо.

5

Re: Пара вопросов udhcpd и dnsmasq

pgw :

Никак не могу решить 2 проблемы. Помогите советом.

Опишите задачу подробнее. Подозреваю, что Вы хотите странного, а не зная предпосылок трудно куда-то направить.

Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn...
Keenetic Giga & WD Mybook Live user

6

Re: Пара вопросов udhcpd и dnsmasq

ZimniY :
pgw :

Никак не могу решить 2 проблемы. Помогите советом.

Опишите задачу подробнее. Подозреваю, что Вы хотите странного, а не зная предпосылок трудно куда-то направить.

Опишу подробнее.
Задача повесить на ppp0 iodined, все остальное оставить как есть. Перезапускать iodined, если он вдруг упадет.

Имеется подключение к провайдеру по pppoe. Создается интерфейс ppp0.
На него необходимо повесить iodine слушать 53/udp порт. Но он уже занят dnsmasq'ом. Отлично, создаем стартовый скрипт, убиваем dnsmasq, запускаем iodined, запускаем dnsmasq со своими параметрами.
И тут начинается самое страшное. 53/udp уже занят iodined'ом и dns у клиентских устройств в локальной сети не работает, потому что на запросы теперь отвечает iodined.

Я вижу 3 способа решения проблемы,
1 - запускать dnsmasq так, чтобы он слушал все, кроме ppp0 или
2 - вообще убрать dnsmasq и передавать по dhcp адреса dns серверов провайдера, а не роутера
или же на крайний случай
3 - вообще выпилить и dhcp и dnsmasq, прописать все вручную и не париться. Но это как-то пошло.

Отредактировано pgw (2012-10-04 02:07:00)

7

Re: Пара вопросов udhcpd и dnsmasq

pgw, тогда действительно, только правка скриптов, чтобы добиться запуска dnsmasq именно на br0)

Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn...
Keenetic Giga & WD Mybook Live user

8

Re: Пара вопросов udhcpd и dnsmasq

Поднимаю старую тему, т.к. что-т уже запутался.
Требуется указать в настройках DHCP несколько шлюзов, которые выдаются по MAC'у (сейчас эту роль выполняет старенький ноутбук с debian, а хотелось бы перенести на роутер).
Думал найти хотя бы оригинальный conf с роутера ("курить" с него), но так и не нашёл (наверное из-за выключенного в данный момент DHCP).
Да и понять пока не могу, возможно ли вообще указать несколько шлюзов в заводском dnsmasq?

9

Re: Пара вопросов udhcpd и dnsmasq

Оставьте вы этот dnsmasq. Поставьте bind в связке dhcpd и будет счастье. Если чего могу помоч настроить и то и другое.

10

Re: Пара вопросов udhcpd и dnsmasq

dexter :

Оставьте вы этот dnsmasq. Поставьте bind в связке dhcpd и будет счастье. Если чего могу помоч настроить и то и другое.

Благодарю за помощь. В данный момент на ноуте используется ICS с таким dhcpd.conf (пример):

INTERFACES="eth0 wlan0";

ddns-update-style none;

option domain-name "workgroup";
option domain-name-servers 8.8.8.8, 8.8.4.4;
option broadcast-address 192.168.1.255;
default-lease-time 600000;
max-lease-time 608000;

log-facility local7;

subnet 192.168.1.0 netmask 255.255.255.0 {
    max-lease-time 604800;
    default-lease-time 604800;
    range 192.168.1.50 192.168.1.199;
    option routers 192.168.1.1;
    }

host D1abl093 {
        hardware ethernet 00:11:22:33:44:55;
        fixed-address 192.168.1.4;
        option routers 192.168.1.1;
}

host test-pc {
        hardware ethernet 01:11:22:33:44:55;
        fixed-address 192.168.1.201;
        option routers 192.168.1.200;
}
host test {
        hardware ethernet 02:11:22:33:44:55;
        fixed-address 192.168.1.15;
        option routers 192.168.1.100;
}

Интересует так же без установки статического адреса, т.е. будет ли работать выбранный шлюз на клиенте без указания статического адреса?
С BIND'ом не "колдовал", дык не знаю нужен ли он мне  smile

Отредактировано D1abl093 (2014-04-20 20:35:59)

11

Re: Пара вопросов udhcpd и dnsmasq

host test {
        hardware ethernet 02:11:22:33:44:55;
        option routers 192.168.1.100;
}

Этого будет достаточно для выдачи клиенту с таким маком нужного вам шлюза.

Отредактировано dexter (2014-04-20 21:30:10)

12

Re: Пара вопросов udhcpd и dnsmasq

dexter :
host test {
        hardware ethernet 02:11:22:33:44:55;
        option routers 192.168.1.100;
}

Этого будет достаточно для выдачи клиенту с таким маком нужного вам шлюза.

ICS поставил, кфг изменил под себя.
Перзапускал роутер командой reboot, ICS сам не запустился, вручную создал dhcpd.lease и запустил - работает.
Теперь вопрос: "После перезапуска роутера он сам запуститься или в крон добавлять?"

13

Re: Пара вопросов udhcpd и dnsmasq

Скрипт запуска в init.d есть?

Вот мой скрипт.

#!/bin/sh

MOUNTPNT="/media/DISK_A1"
MOUNT="$MOUNTPNT/system"
CONFFILE="$MOUNT/etc/dhcpd.conf"

export PATH=$MOUNT/bin:$MOUNT/sbin:$MOUNT/usr/bin:$MOUNT/usr/sbin:/sbin:/usr/sbin:/bin:/usr/bin
export LD_LIBRARY_PATH=$MOUNT/lib:$MOUNT/usr/lib:/lib:/usr/lib

start() {


   dhcpd br0
}

stop() {

killall dhcpd

}

case "$1" in
start)
    start
    ;;
stop)
stop
    ;;
restart)
stop
start
    ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        ;;
esac

В каталоге init.d нужно создать файл скрипта с именем S10dhcpd и сделать его исполняемым. Или скопировать любой из скриптов в этой папке, заменить содержимое и переименовать.

Отредактировано dexter (2014-04-20 21:44:38)

14

Re: Пара вопросов udhcpd и dnsmasq

Нету, потому и спросил  smile
Вот ещё интересно. я не убивал процесс dnsmasq (dhcp в web-интерфейсе выключен), он мне вообще нужен.
Хотя заинтересовал bind, точнее указание SRV

Отредактировано D1abl093 (2014-04-20 21:46:36)

15

Re: Пара вопросов udhcpd и dnsmasq

dnsmasq в кинетеке он просто как кеширующий DNS.
За выдачу адресов выступает udhcpd.
Т.к. у меня bind, то dnsmasq у меня убивается скриптом при старте бинда.

16

Re: Пара вопросов udhcpd и dnsmasq

dexter :

dnsmasq в кинетеке он просто как кеширующий DNS.
За выдачу адресов выступает udhcpd.
Т.к. у меня bind, то dnsmasq у меня убивается скриптом при старте бинда.

Ну значит будет, чем заняться ещё на днях  smile
Спасибо за помощь

17

Re: Пара вопросов udhcpd и dnsmasq

Не за что, вопросы будут - обращайтесь.

18

Re: Пара вопросов udhcpd и dnsmasq

Задался вопросом выдавать некоторым клиентам в сети другие сервера DNS.
Роутер KEENETIC GIGA V1.11.RU.NDMS 8-янв-2014 21:00. Стоит entware и isc-dhcp. Штатный udhcpd при загрузке убиваю.
Конфигурация dhcpd.conf

# dhcpd.conf

authoritative;

default-lease-time 3600;
max-lease-time 86400;

#option domain-name "homelan";
option broadcast-address 192.168.1.255;
option domain-name-servers 192.168.1.1;
option routers 192.168.1.1;

log-facility local7;

subnet 192.168.1.0 netmask 255.255.255.0 {
  range 192.168.1.33 192.168.1.62;
  option routers 192.168.1.1;
  option domain-name-servers 192.168.1.1;
}

host nas {
hardware ethernet xx:xx:xx:xx:xx:xx;
fixed-address 192.168.1.40;
option domain-name-servers 77.88.8.7;
option routers 192.168.1.1;
}

Клиент nas получает нужный dns сервер, но запросы к нему не проходят.

Правила iptables

#!/bin/sh
iptables -I FORWARD -i br0 -o tun0 -j ACCEPT
iptables -I FORWARD -i tun0 -o br0 -j ACCEPT
iptables -I INPUT -i tun0 -j ACCEPT
iptables -I INPUT -p udp --dport 1194 -j ACCEPT
iptables -I FORWARD -i tun0 -j ACCEPT
iptables -t nat -A POSTROUTING -o br0 -j MASQUERADE
iptables -A INPUT -i lo -j ACCEPT

Пробывал просто прописать на телефоне адрес dns гугла, вместо кинетика, и тоже ничего не работает.

Отредактировано kpox (2015-03-29 10:43:48)