Linux dhcp server leases
После установки dhcpd, файл БД не создается. Однако он требуется для нормальной работы сервера dhcp и поэтому необходимо самостоятельно создать пустой файл с названием: /var/state/dhcp/dhcpd.leases.
Для того что бы предотвратить бесконтрольный рост размеров файла он время от времени создается заново и перезаписывается. Сначала создается временный файл БД куда сбрасываются все актуальные записи, затем старый файл переименовывается в /var/state/dhcp/dhcpd.leases
. Ну и наконец, временный файл переименовывается в /var/state/dhcp/dhcpd.leases.
Здесь существует проблема с безопасностью системы в плане DoS. Если процесс dhcpd был принудительно завешен (убит)или система упала в момент когда старый файл уже переименован, а новый еще не перемещен на место, то после перезагрузки системы окажется что отсутствует файл /var/state/dhcp/dhcpd.leases. В этом случае dhcpd просто не сможет стартовать и потребуется ручное вмешательство. Первое что приходит на ум — создавать пустой файл. Никогда не делайте этого — таким образом вы рискуете ввергнуть систему в хаос, потеряв информацию о ранее распределенных адресах. Вместо этого просто переименуйте /var/state/dhcp/dhcpd.leases
в /var/state/dhcp/dhcpd.leases, тем самым восстановив предыдущее состояние.
ФОРМАТ
Каждая запись включает в себя единственный IP-адрес, тот что был выделен клиенту. Инструкции в скобках определяют кому и на какой срок выдан адрес.
Начало и окончание срока использования клиентом адреса записываются с использованием инструкций: «starts» и «ends»
starts дата ;
ends дата ;
дата — означает следующее:
день_недели год / месяц / день час : минута : секунда
день_недели присутствует для облегчения чтения и указывается цифрой от 0 до 6, где 0 — воскресение. День_недели игнорируется при вводе. Год указывается четырьмя цифрами. Месяц указывается числом начиная с 1 (Январь). Дни месяца также начинаются с 1. Часы — числа от 0 до 23, минуты и секунды 0 — 59
Время указывается по Гринвичу (GMT),а не согласно местной временной зоне.
MAC адрес сетевого интерфейса, который был использован при получении IP адреса записывается с помощью инструкции hardware :
hardware hardware-type mac-address ;
MAC адрес записывается последовательностью шестнадцатеричных октетов разделенных двоеточиями.
Если для получения адреса клиент использует идентификатор клиента (client identifier), то он фиксируется в инструкции uid :
uid client-identifier ;
Идентификатор клиента записывается последовательностью шестнадцатеричных октетов, независимо от того, указывает ли клиент строку ASCII или использует более новый формат — hardware type/MAC адрес.
Если клиент посылает серверу собственное имя используя опцию Client Hostname как указанно в некоторых версиях DHCP-DNS Interaction draft, то имя хоста записывается с использованием инструкции client-hostname .
client-hostname » hostname «;
Если клиент посылает серверу собственное имя используя опцию Hostname так как это делает Windows 95,то имя хоста записывается с использованием инструкции hostname .
hostname » hostname «;
Сервер DHCP, в некоторых случаях, может определить что выделенный адрес не правильно используется, например если клиент которому был выделен адрес не подтверждает его получение, или потому что при попытке проверить используется ли адрес перед тем как его выдать сервер обнаруживает что адрес занят. В таких случаях инструкция abandoned используется что бы показать что данный адрес «отказной» и не может быть переназначен.
abandoned;
Когда клиент запрашивает новый адрес и сервер обнаруживает что свободные адреса закончились, то в этом случае сервер просматривает адреса помеченные как abandoned и выдает клиенту адрес с наименьшим числом отказов. Если конфликты с выданным адресом продолжаются он повторно переводится в разряд «отказных». d.
Если клиент запрашивает «отказной» адрес, то сервер считает что причиной помещения этого адреса в разряд «отказных» было повреждение файла БД и данный клиент и есть та машина что отвечала при тестировании адреса перед его распределением. В этом случае адрес незамедлительно назначается клиенту.
Источник
isc-dhcpd очистка файла с leases ubuntu 14.04
Уважаемые коллеги, столкнулись с тем что у нас переполнился файл /var/lib/dhcp/dhcpd.leases — а именно, он, сволочь, достиг размера 2гб. Я так понимаю, что в ubuntu 14.04, это добро скомпилировано так, чтобы не очищать данный файл от не свежих записей об аренде. — Есть рецепт что делать, кроме как пере собирать из исходников?
Как только leases разрастается, dhcp сервер падает и не стартует. Пришлось грохать вместе со всеми актуальными арендами.
хм. Сколько лет использую isc-dhcpd, но с таким не сталкивался.
Интересный результат дает поиск в гугле «isc dhcpd large leases file» именно про убунту.
Если не пересобирать, а просто регулярно перезапускать (раз в сутки)? У меня он точно при старте чистит просроченные leases.
Возможно в сети есть кривой клиент, который засирает leases. Я бы простеньким скриптом подсчитал число leases в каждой подсети в файле dhcpd.leases — может быть найдется аномалия.
Если не секрет, а сколько адресов раздается и на сколько клиентов ? И какая версия dhcpd ?
Если не секрет, а сколько адресов раздается и на сколько клиентов ? И какая версия dhcpd ?
Да в том и дело, что клиентов совсем не много, не больше трех сотен.
Возможно в сети есть кривой клиент, который засирает leases. Я бы простеньким скриптом подсчитал число leases в каждой подсети в файле dhcpd.leases — может быть найдется аномалия.
Спасибо! Посмотрю на сей предмет!
Интересный результат дает поиск в гугле «isc dhcpd large leases file» именно про убунту.
Вот по-этому и пришёл на форум. Думаю может кто-то сталкивался.
хм. Сколько лет использую isc-dhcpd, но с таким не сталкивался.
Мы сделали привязку ip, к порту свитча. Чтобы менять принтера без заморочек. — Пришёл, один выклчил, другой поставил — дальше работаешь. Идея юзать стандартный драйвер PCL6. Сделали аренду сроком на одну минуту. — По идее, мы это делали только для подсети принтеров. — Я погляжу. Может накосячили где-то и сделали сразу на всех клиентов. — Была идея или привязать ip к порту и делать короткую аренду, или плевать на аренду, привязать ip к порту и ловить трапы snmp, после поимки трапов выполнять скрипт на сервере. — Выбрал первый вариант, т.к. посчитал что возня с snmp слишком сложна для этих целей. — Может ещё есть способ решения моего вопроса?
Если не пересобирать, а просто регулярно перезапускать (раз в сутки)? У меня он точно при старте чистит просроченные leases.
Тоже про это вычитал. Попробую.
Спасибо за ответ по делу!
Мы сделали привязку ip, к порту свитча. Чтобы менять принтера без заморочек. — Пришёл, один выклчил, другой поставил — дальше работаешь. Идея юзать стандартный драйвер PCL6. Сделали аренду сроком на одну минуту. — По идее, мы это делали только для подсети принтеров.
IMHO Если в этой сети принтеров нет клиентов (т.е. весь трафик идет через роутер), то проще сделать фиксированые «виртуальные» адреса для принтеров и делать DNAT на реальный адрес при выдаче адреса принтеру (скриптом в «on commit»)
Источник
dhcpd.leases(5) — Linux man page
Description
When dhcpd is first installed, there is no lease database. However, dhcpd requires that a lease database be present before it will start. To make the initial lease database, just create an empty file called /var/lib/dhcpd/dhcpd.leases. You can do this with: In order to prevent the lease database from growing without bound, the file is rewritten from time to time. First, a temporary lease database is created and all known leases are dumped to it. Then, the old lease database is renamed /var/lib/dhcpd/dhcpd.leases
. Finally, the newly written lease database is moved into place.
Format
The lease file is a log-structured file — whenever a lease changes, the contents of that lease are written to the end of the file. This means that it is entirely possible and quite reasonable for there to be two or more declarations of the same lease in the lease file at the same time. In that case, the instance of that particular lease that appears last in the file is the one that is in effect.
Group, subgroup and host declarations in the lease file are handled in the same manner, except that if any of these objects are deleted, a rubout is written to the lease file. This is just the same declaration, with in the scope of the declaration. When the lease file is rewritten, any such rubouts that can be eliminated are eliminated. It is possible to delete a declaration in the dhcpd.conf file; in this case, the rubout can never be eliminated from the dhcpd.leases file.
the Lease Declaration
Each lease declaration includes the single IP address that has been leased to the client. The statements within the braces define the duration of the lease and to whom it is assigned.
The start and end time of a lease are recorded using the starts and ends statements. The tstp statement is specified if the failover protocol is being used, and indicates what time the peer has been told the lease expires. The tsfp statement is also specified if the failover protocol is being used, and indicates the lease expiry time that the peer has acknowledged. The atsfp statement is the actual time sent from the failover partner. The cltt statement is the client’s last transaction time.
The date is specified in two ways, depending on the configuration value for the db-time-format parameter. If it was set to default, then the date fields appear as follows:
The weekday is present to make it easy for a human to tell when a lease expires — it’s specified as a number from zero to six, with zero being Sunday. The day of week is ignored on input. The year is specified with the century, so it should generally be four digits except for really long leases. The month is specified as a number starting with 1 for January. The day of the month is likewise specified starting with 1. The hour is a number between 0 and 23, the minute a number between 0 and 59, and the second also a number between 0 and 59.
Lease times are specified in Universal Coordinated Time (UTC), not in the local time zone. There is probably nowhere in the world where the times recorded on a lease are always the same as wall clock times. On most unix machines, you can display the current time in UTC by typing date -u.
If the db-time-format was configured to local, then the date fields appear as follows:
The seconds-since-epoch is as according to the system’s local clock (often referred to as «unix time»). The # symbol supplies a comment that describes what actual time this is as according to the system’s configured timezone, at the time the value was written. It is provided only for human inspection.
If a lease will never expire, date is never instead of an actual date.
hardware hardware-type mac-address;
The hardware statement records the MAC address of the network interface on which the lease will be used. It is specified as a series of hexadecimal octets, separated by colons.
The uid statement records the client identifier used by the client to acquire the lease. Clients are not required to send client identifiers, and this statement only appears if the client did in fact send one. Client identifiers are normally an ARP type (1 for ethernet) followed by the MAC address, just like in the hardware statement, but this is not required.
The client identifier is recorded as a colon-separated hexadecimal list or as a quoted string. If it is recorded as a quoted string and it contains one or more non-printable characters, those characters are represented as octal escapes — a backslash character followed by three octal digits.
Most DHCP clients will send their hostname in the host-name option. If a client sends its hostname in this way, the hostname is recorded on the lease with a client-hostname statement. This is not required by the protocol, however, so many specialized DHCP clients do not send a host-name option.
The abandoned statement indicates that the DHCP server has abandoned the lease. In that case, the abandoned statement will be used to indicate that the lease should not be reassigned. Please see the dhcpd.conf(5) manual page for information about abandoned leases.
binding state state; next binding state state;
The binding state statement declares the lease’s binding state. When the DHCP server is not configured to use the failover protocol, a lease’s binding state will be either active or free. The failover protocol adds some additional transitional states, as well as the backup state, which indicates that the lease is available for allocation by the failover secondary.
The next binding state statement indicates what state the lease will move to when the current state expires. The time when the current state expires is specified in the ends statement.
option agent.circuit-id string; option agent.remote-id string;
The option agent.circuit-id and option agent.remote-id statements are used to record the circuit ID and remote ID options send by the relay agent, if the relay agent uses the relay agent information option. This allows these options to be used consistently in conditional evaluations even when the client is contacting the server directly rather than through its relay agent.
The set statement sets the value of a variable on the lease. For general information on variables, see the dhcp-eval(5) manual page.
The ddns-text variable is used to record the value of the client’s TXT identification record when the interim ddns update style has been used to update the DNS for a particular lease.
The ddns-fwd-name variable records the value of the name used in updating the client’s A record if a DDNS update has been successfully done by the server. The server may also have used this name to update the client’s PTR record.
If the server is configured to use the interim ddns update style, and is also configured to allow clients to update their own fqdns, and the client did in fact update its own fqdn, then the ddns-client-fqdn variable records the name that the client has indicated it is using. This is the name that the server will have used to update the client’s PTR record in this case.
If the server successfully updates the client’s PTR record, this variable will record the name that the DHCP server used for the PTR record. The name to which the PTR record points will be either the ddns-fwd-name or the ddns-client-fqdn.
on events < statements. > The on statement records a list of statements to execute if a certain event occurs. The possible events that can occur for an active lease are release and expiry. More than one event can be specified — if so, the events are separated by ‘|’ characters.
bootp; reserved; These two statements are effectively flags. If present, they indicate that the BOOTP and RESERVED failover flags, respectively, should be set. BOOTP and RESERVED dynamic leases are treated differently than normal dynamic leases, as they may only be used by the client to which they are currently allocated.
Источник