- unboxIT
- Правильная настройка сервера времени NTP на Linux
- Добавить комментарий
- Time Synchronization
- Synchronizing your systems time
- Configuring timedatectl and timesyncd
- Serve the Network Time Protocol
- chrony(d)
- Installation
- Chronyd Configuration
- Serving the NTP Protocol
- View status
- PPS Support
- Example configuration for GPSD to feed Chrony
- NTS Support
- NTS Server
- NTS Client
unboxIT
Если информация была полезной для вас, вы можете поблагодарить за труды Яндекс деньгами: 41001164449086 или пластиковой картой:
Правильная настройка сервера времени NTP на Linux
В интернете можно найти целое море мануалов по настройке сервера времени — ntpd, но ирония состоит в том, что 95% из них либо не совсем верны, и авторы этого даже не замечают, либо не дают необходимой информации. Далее я расскажу как организовать NTP сервер под Linux в локальной сети, который будет синхронизировать своё время с серверами в Интернете, а устройства в локальной сети будут уже синхронизировать время с ним.
Немного пред истории. Как и положено, всё началось неожиданно, сервер который я настраивал на кануне ночью, при следующей загрузки завис. «Шикарно» подумал я и полез в логи. В результате в том что сервер вис был повинен ntpd сервис, который из-за неправильной настройки сети не мог связаться внешним сервером для синхронизации. Посмотрев скрипт запуска, я наткнулся на интересную запись:
А теперь внимание на строку с номером 8. Это начало цикла, в котором целых 7-мь раз будет предпринята попытка начальной, грубой синхронизации времени. Всё бы хорошо, но если у вас неправильно настроена сеть, или DNS, то вызовет подвисание сервера, на 7*( 1 + время проверки доступности DNS, порядка 5 сек ) секунд. В общем ждать минуту меня явно не устраивало, итак приступим.
Настройка начальной, грубой синхронизации
В замечательном файле /etc/ntp/step-tickers, хранятся имена серверов с которыми производиться начальная, грубая (сотни милесекунд) корректировка. Если вы уверены что у вас всегда будет доступ к Internet, можете перечислить в нём имена серверов, например:
Но если у вас в момент начальной загрузки сервера связь с интернетом будет отсутствовать, то при определённых условиях, это вызовет подвисание консоли на довольно продолжительное время. Именно по этому я стёр все записи от туда. В конце концов я могу и в ручную сделать грубую корректировку времени. Есть ещё вариант поиграться с опциями и подправить скрипт запуска, но это не мой путь. По этому переходим непосредственно к настройки полноценного NTP сервера, который будет синхронизировать свое время с публичными серверами в Интернете, и предоставлять его участникам локальной сети в случае необходимости.
Задача: Организовать NTP сервер в локальной сети, который будет синхронизировать своё время с Интернетом, а устройства в локальной сети будут уже синхронизировать время с ним.
Дистрибутив: Mandriva 2010.2 free Версия ntpd: 4.2.4p8
Мир Linux действительно великолепен, все настройки в нём сводятся к простому редактированию файлов конфигураций. ntpd в этом плане не исключение. Итак если у вас ещё не стоит ntpd сервер установим его:
Желающие могут скомпилировать из исходников, или установить его другим способом, в мои же платны входит показать как настроить это чудо, по скольку в интернете можно найти целое море мануалов по настройке ntpd, но ирония состоит в том, что 95% из них либо не совсем верны (и авторы этого даже не замечают при вызове статусов) либо не дают необходимой информации. Итак файл с настройками храниться в /etc/ntp.conf, минимальные настройки примерно такие:
Каждая строчка указывает на сервер (списки серверов можно найти здесь http://www.pool.ntp.org), с которым будет происходить синхронизация. Четыре строчки с server, соответственно четыре сервера. Хотя на самом деле в данном примере это не совсем так. Каждая запись указывает на пул (группу) серверов. При обращении скажем по адресу 2.ru.pool.ntp.org будет выбран 1 IP адрес сервера, с которым будет происходить синхронизация. Соответствия обновляются 1 раз в час. Теперь на более простом примере. Всего у нас имеется 4 коробки с часами. Мы берём и наугад достаём из каждой коробки 1 часы, всего у нас получается 4 часов, с которыми мы будем сверять наше время. В течении часа, каждый раз когда мы будем сверять время, мы будем брать одни и те же часы. Через час если мы опять обратимся к этим коробкам, то вытащим уже другие часы. Таким образом наше время будет сверяться постоянно с разными часами, и если какие-то из них окажутся не рабочими, то ничего страшного не случиться, ведь за 1 час, наши локальные часы не слишком сильно рассинхронизируются. Ну да мы отвлеклись, продолжим. Прежде чем запускать сервер ntpd, необходимо произвести начальную, грубую установку времени. Можно просто выставить время руками, а можно выполнить команду (разумеется если у нас корректно работает связь с интернетом):
После того как время грубо синхронизировано можно запускать основной сервис (на всякий случае перезапустим его):
После чего выполним команду:
В результате должны увидеть что-то на подобии:
Небольшие пояснения что есть что. remote — FQDN или IP-адрес сервера; refid — IP-адрес сервера с которым в настоящий момент выполняется синхронизация сервера из столбца remote; st — stratum сервера; t — режим работы сервера: ‘u’ — unicast, ‘m’ — multicast, ‘b’ — broadcast, ‘-‘ — manycast; when — время, прошедшее с момента последнего ответа сервера в секундах или ‘-‘, если сервер еще ни разу не ответил (скорее всего, «умер», и сведения о нем пора удалить из файла конфигурации); poll — интервал опроса сервера в секундах (после запуска имеет небольшое значение, чтобы синхронизация происходила быстрее, с течением времени значение увеличивается); reach — состояние восьми последних попыток запроса времени у сервера в восьмеричном представлении (в случае успешной попытки устанавливается соответствующий бит); delay — задержка ответа сервера в секундах; offset — самое важное значение — различие локального времени и времени на сервере (с течением времени значение уменьшается, т.к. время становится более точным); jitter — дисперсия, дрожание фазы (более низкие значения обеспечивают более точную синхронизацию). Ждём 10 минут. Повторяем, команду и видем:
Ага, вот оно появились всякие дополнительные символы и вот что они означают: ‘*’ — сервер, с которым в настоящий момент выполняется синхронизация, ‘#’ — сервер отобран для синхронизации, но дистанция до него превышает максимально возможную, ‘?’ — сервер отобран для синхронизации и использует сигнал PPS, ‘+’ — сервер добавлен в список серверов, отобранных для синхронизации, ‘x’ — сервер использует некорректный алгоритм, ‘.’ — сервер выбран из конца списка серверов, отобранных для синхронизации, ‘-‘ — сервер отвергнут группирующим алгоритмом, пробел — сервер имеет слишком высокий stratum и/или не может быть проверен; Теперь по простому, если видем ‘+’, ‘-‘, ‘*’ синхронизация пошла. offset — отклонение нашего времени и времени удалённого сервера, если значение скажем больше 100, то синхронизация реально не произошла. На некоторых ресурсах можно увидеть следующую картину:
Видим что половина серверов (2, 3, 4) вообще не работает и реально происходит работа с локальным сервером и с 172.22.128.8. Смотрим значение offset которое говорит что никакой синхронизации нет и в помине! Из листинга можно сделать только один вывод, что сервер засинхронизирован сам с собой, и его время имеет мало общего с действительным. Будьте внимательны, не давайте вас нае. обмануть 🙂 На этом бы можно и остановиться но теперь как говориться усложняем задачу. Нам надо чтоб наш сервер являлся источником времени для локальной сети, но при этом никто не смог сделать ничего плохого с вашим сервером. В чём проблема? В том что для нормальной синхронизации, даже если вы не планируете кому то давать синхронизировать время с вами, У ВАС ДОЛЖЕН быть открытым порт udp 123. После прочтения множества мануалов и дня потерянного времени вот что в /etc/ntp.conf получилось у меня:
Вникаем внимательно. Наш сервер засинхронизирован с 6-тью внешними пулами серверов, строки с 02 по 07. Строка 10, мы запрещаем кому либо чтобы-то не было делать с нашим сервером. Теперь нам надо внести исключение для серверов с которыми наш сервер будет синхронизироваться, строки с 13 по 18. При этом параметры nomodify notrap, говорят о том что запрещено изменять состояние НАШЕГО сервера и отправлять сообщения об исключениях ВНЕШНИМИ серверами, т. е. чтоб никто из этих серверов ничего не натворил. Строка 22, мы разрешаем участникам локальной сети синхронизировать время с нашим сервером, но при этом тоже вводим ограничение. Теперь самая важная строка — 25, будем считать что это локальная петля. Без неё работать не будет. В итоге, наш сервер синхронизируется с внешними серверами, при этом сам является сервером но только для нашей локальной сети, всем остальным доступ запрещён. Ещё раз перезапустим сервис:
Пойдём покурим, выпьем чаю, кофе (нужное подчеркнуть), после чего выполним команду:
Видим, наш сервер засинхронизирован, отклонение не превышают и 50мс. Настройка NTPD практически одинакова для всех Xnix систем, и отличается по сути только способом запуска. Всем советую ознакомиться также со статьёй где расписан вариант настройки для FreeBSD. http://www.sergeysl.ru/freebsd-ntpd/ Вот собственно и всё.
Добавить комментарий
Если информация была полезной для вас, вы можете поблагодарить за труды Яндекс деньгами: 41001164449086 или пластиковой картой:
Источник
Time Synchronization
NTP is a TCP/IP protocol for synchronizing time over a network. Basically a client requests the current time from a server, and uses it to set its own clock.
Behind this simple description, there is a lot of complexity — there are tiers of NTP servers, with the tier one NTP servers connected to atomic clocks, and tier two and three servers spreading the load of actually handling requests across the Internet. Also the client software is a lot more complex than you might think — it has to factor out communication delays, and adjust the time in a way that does not upset all the other processes that run on the server. But luckily all that complexity is hidden from you!
Ubuntu by default uses timedatectl / timesyncd to synchronize time and users can optionally use chrony to serve the Network Time Protocol.
Synchronizing your systems time
Since Ubuntu 16.04 timedatectl / timesyncd (which are part of systemd) replace most of ntpdate / ntp.
timesyncd is available by default and replaces not only ntpdate, but also the client portion of chrony (or formerly ntpd). So on top of the one-shot action that ntpdate provided on boot and network activation, now timesyncd by default regularly checks and keeps your local time in sync. It also stores time updates locally, so that after reboots monotonically advances if applicable.
If chrony is installed timedatectl steps back to let chrony do the time keeping. That shall ensure that no two time syncing services are fighting. While no more recommended to be used, this still also applies to ntpd being installed to retain any kind of old behavior/config that you had through an upgrade. But it also implies that on an upgrade from a former release ntp/ntpdate might still be installed and therefore renders the new systemd based services disabled.
ntpdate is considered deprecated in favor of timedatectl (or chrony) and thereby no more installed by default. timesyncd will generally do the right thing keeping your time in sync, and chrony will help with more complex cases. But if you had one of a few known special ntpdate use cases, consider the following:
If you require a one-shot sync use: chronyd -q
If you require a one-shot time check, without setting the time use: chronyd -Q
Configuring timedatectl and timesyncd
The current status of time and time configuration via timedatectl and timesyncd can be checked with timedatectl status .
If chrony is running it will automatically switch to:
Via timedatectl an admin can control the timezone, how the system clock should relate to the hwclock and if permanent synronization should be enabled or not. See man timedatectl for more details.
timesyncd itself is still a normal service, so you can check its status also more in detail via.
The nameserver to fetch time for timedatectl and timesyncd from can be specified in /etc/systemd/timesyncd.conf and additional config files can be stored in /etc/systemd/timesyncd.conf.d/ . The entries for NTP= and FallbackNTP= are space separated lists. See man timesyncd.conf for more.
Serve the Network Time Protocol
If in addition to synchronizing your system you also want to serve NTP information you need an NTP server. There are several options with chrony, ntpd and open-ntp. The recommended solution is chrony.
chrony(d)
The NTP daemon chronyd calculates the drift and offset of your system clock and continuously adjusts it, so there are no large corrections that could lead to inconsistent logs for instance. The cost is a little processing power and memory, but for a modern server this is usually negligible.
Installation
To install chrony, from a terminal prompt enter:
This will provide two binaries:
chronyd — the actual daemon to sync and serve via the NTP protocol
chronyc — command-line interface for chrony daemon
Chronyd Configuration
Edit /etc/chrony/chrony.conf to add/remove server lines. By default these servers are configured:
See man chrony.conf for more details on the configuration options. After changing the any of the config file you have to restart chrony:
Of the pool 2.ubuntu.pool.ntp.org as well as ntp.ubuntu.com also support ipv6 if needed. If one needs to force ipv6 there also is ipv6.ntp.ubuntu.com which is not configured by default.
Serving the NTP Protocol
You can install chrony (above) and configure special Hardware (below) for a local synchronization
and as-installed that is the default to stay on the secure and conservative side. But if you want to serve NTP you need adapt your configuration.
To enable serving the NTP protocol you’ll need at least to set the allow rule to which controls which clients/networks you want chrony to serve NTP to.
An example would be
See the section “NTP server” in the man page for more details on how you can control and restrict access to your NTP server.
View status
Use chronyc to see query the status of the chrony daemon. For example to get an overview of the currently available and selected time sources.
Certain chronyc commands are privileged and can not be run via the network without explicitly allowing them. See section Command and monitoring access in man chrony.conf for more details. A local admin can use sudo as usually as this will grant him access to the local admin socket /var/run/chrony/chronyd.sock .
PPS Support
Chrony supports various PPS types natively. It can use kernel PPS API as well as PTP hardware clock. Most general GPS receivers can be leveraged via GPSD. The latter (and potentially more) can be accessed via SHM or via a socket (recommended). All of the above can be used to augment chrony with additional high quality time sources for better accuracy, jitter, drift, longer-or-short term accuracy (Usually each kind of clock type is good at one of those, but non-perfect at the others). For more details on configuration see some of the external PPS/GPSD resource listed below.
Note: at the release of 20.04 there was a bug which until fixed you might want to add this content to your /etc/apparmor.d/local/usr.sbin.gpsd .
Example configuration for GPSD to feed Chrony
For the setup you need
$ sudo apt install gpsd chrony
But you will want to test/debug your setup and especially the GPS reception, therefore also install
$ sudo apt install pps-tools gpsd-clients
GPS devices usually will communicate via serial interfaces, yet the most common type these days are USB GPS devices which have a serial converter behind USB. If you want to use this for PPS please be aware that the majority does not signal PPS via USB. Check the GPSD hardware list for details. The examples below were run with a Navisys GR701-W.
When plugging in such a device (or at boot time) dmesg should report serial connection of some sorts, example:
We see above that it appeared as ttyUSB0 . To later on have chrony accept being feeded time information by that we have to set it up in /etc/chrony/chrony.conf (Please replace USB0 to whatever applies to your setup):
Then restart chrony to make the socket available and waiting.
sudo systemctl restart chrony
Next one needs to tell gpsd which device to manager, therefore in /etc/default/gpsd we set:
DEVICES=»/dev/ttyUSB0″
Furthermore the default use-case of gpsd is, well for gps position tracking. Therefore it will normally not consume any cpu since it is not running the service but waiting on a socket for clients. Furthermore the client will then tell gpsd what it requests and gpsd will only do that.
For the use case of gpsd as PPS-providing-daemon you want to set the option to:
- immediately start even without a client connected, this can be set in GPSD_OPTIONS of /etc/default/gpsd :
- GPSD_OPTIONS=»-n»
- enable the service itself and not wait for a client to reach the socket in the future:
- sudo systemctl enable /lib/systemd/system/gpsd.service
Restarting gpsd will now initialize the PPS from GPS and in dmesg you will see
In case you have multiple PPS the tool ppsfind might be useful to identify which PPS belongs to which GPS. You could check that with:
To get any further you need your GPS to get a lock.
Tools like cgps or gpsmon need to report a 3D Fix for the data being any good.
Then you’d want to check to really have PPS data reported on that with ppstest
Next one might want to ensure that the pps device really submits PPS data, to do so run ppstest :
Ok, gpsd is now running, the GPS reception has found a fix and this is fed into chrony .
Now lets check that from the point of view of chrony .
Initially (e.g. before gpsd has started or before it has a lock) those will be new and “untrusted” sources marked with an “?”. If your devices stay in the “?” state and won’t leave it even after quite some time then gpsd seems not to feed any data to chrony and you’d need to debug why.
Over time chrony will classify them as good or bad.
In the example case the raw GPS had too much deviation but PPS is good.
And finally after a while it used the hardware PPS input as it was better:
The PPS might also be ok but used in a combined way with e.g. the selected server.
See man chronyc for more details about how all these combinations will look like.
And if you wonder if your shm based GPS data is any good, you can check for that as well.
First of all chrony will not only tell you if it classified it as good or bad. Via sourcestats you can also check the details
You can also track the raw data that gpsd or other ntpd compliant refclocks are sending via shared memory by using ntpshmmon :
NTS Support
In Chrony 4.0 (first appeared in Ubuntu 21.04 Hirsute) support for Network Time Security “NTS” as added.
NTS Server
To set up your server with NTS you’ll need certificates so that the server can authenticate itself and based on that allow to encrypt and verify the NTP traffic.
In addition to the allow statement that any chrony working as NTP server needs there are two mandatory config entries that will be needed. Those for the certificates like
Example entries would look like:
It is important to note that for isolation reasons chrony by default runs as user and group _chrony . Therefore you need to grant access to the certificates for that user.
$ sudo chown _chrony:_chrony /etc/chrony/*.pem
Then restart chrony systemctl restart chrony and it will be ready to provide NTS based time service.
A running chrony server has various statistics, one also accounts the number of NTS connections that were established (or dropped):
And there is also a per-client statistic which can be enabled by the -p option of the clients command.
For more complex scenarios there are more advanced options to configure NTS documented in the man page.
A Note about certificate placement:
Chrony by default is isolated via apparmor and in addition uses all kind of protect* features of systemd. Due to that there are not many paths chrony can access for the certificates. But /etc/chrony/* is allowed as read-only and that is enough.
Check /etc/apparmor.d/usr.sbin.chronyd if you want other paths or allow custom paths in /etc/apparmor.d/local/usr.sbin.chronyd .
NTS Client
The client needs to specify server as usual ( pool directives do not work with NTS). As usual after the server adress options can be listed and there nts has to be added.
server iburst nts
One can check the authdata of the connections the client established like
Again there are more advanced options documented in the man page. Common use cases are specifying an explicit trusted certificate.
Bad Clocks and secure time syncing — “A Chicken and Egg” Problem:
There is one problem with systems that have very bad clocks. NTS is based on TLS and that needs a a somewhat correct clock. Due to that an NTS based sync might fail. On Hardware affected by this one can consider using the nocerttimecheck option which allows to set a number of times time can be synced without checking validation and expiration.
Источник