This document (000020824) is provided subject to the disclaimer at the end of this document.
Environment
SUSE Linux Enterprise Server 15 SP4
SUSE Linux Enterprise Server 15 SP3
SUSE Linux Enterprise Server 15 SP2
SUSE Linux Enterprise Server 15 SP1
SUSE Linux Enterprise Server 12 SP5
SUSE Linux Enterprise Server 12 SP4
SUSE Linux Enterprise Server 12 SP3
SUSE Linux Enterprise Server 12 SP2
SUSE Linux Enterprise Server 12 SP1
Situation
chronyd is a daemon for synchronization of the system clock. When setting chrony to synchronize with a Windows NTP, for instance and using the default configuration file (/etc/chrony.conf), the server will be displayed as “unusable”. The output is similar to the following:
# /usr/bin/chronyc -n sources MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^? 172.16.96.11 1 6 377 61 -11.4s[ -11.4s] +/- 11.0s
On the above output, the server 172.16.96.11 is marked with ^?:
^ means this is a server
? means this server is currently unusable.
Alternatively, use /usr/bin/chronyc -n sources -v for further details and explanation of each column on the output displayed.
Resolution
Edit the /etc/chrony.conf making sure to add the maxdistance parameter. Example below:
server win-samba.mydomain.com iburst driftfile /var/lib/chrony/drift maxdistance 16.0 # <--- if your NTP is a Windows Server, then use this as starting value. Adapt if necessary. makestep 1.0 3 rtcsync keyfile /etc/chrony.keys leapsectz right/UTC logdir /var/log/chrony
From the chrony.conf man page:
By default, the maximum root distance is 3 seconds.
Setting maxdistance to a larger value can be useful to allow synchronisation with a server that only has a very infrequent connection to its sources and can accumulate a large dispersion between updates of its clock.
Cause
The default maximum root distance (of 3 seconds) is being used.
Additional Information
Reference:
- https://documentation.suse.com/sles/15-SP4/html/SLES-all/cha-ntp.html
- https://chrony.tuxfamily.org/doc/4.3/chrony.conf.html#maxdistance
Disclaimer
This Support Knowledgebase provides a valuable tool for SUSE customers and parties interested in our products and solutions to acquire information, ideas and learn from one another. Materials are provided for informational, personal or non-commercial use within your organization and are presented «AS IS» WITHOUT WARRANTY OF ANY KIND.
- Document ID:000020824
- Creation Date:
24-Oct-2022 - Modified Date:26-Oct-2022
-
- SUSE Linux Enterprise Server
< Back to Support Search
For questions or concerns with the SUSE Knowledgebase please contact: tidfeedback[at]suse.com
Установка и запуск
Настройка
Управление Chronyd
Окружение
- Версия РЕД ОС: 8
- Конфигурация: Рабочая станция
- Версия ПО: chrony-4.1-5
Chrony – альтернативный клиент и сервер протокола сетевого времени NTP. Chrony может быстрее синхронизировать системные часы с лучшей точностью времени, и он может быть особенно полезен для систем, которые не работают в сети все время.
Основные преимущества:
-
эффективная работа в среде, где доступ к временной связке прерывистый;
-
адаптация к внезапным изменениям частоты тактовых импульсов;
-
работа в перегруженной сети, даже если перегрузка продолжается длительное время;
-
время в конфигурации по умолчанию никогда не изменяется, чтобы не нарушать работу других запущенных программ;
-
использование меньшего объема памяти и запуск процессов только при необходимости в целях экономии энергии.
Установка и запуск
Действия по установке и настройке требуется производить под пользователем root или пользователем с правами администратора.
Chrony доступен по умолчанию в репозитории РЕД ОС.
Для установки Chrony необходимо выполнить следующую команду:
dnf install chrony
После установки необходимо добавить сервис chronyd.service в автозагрузку и запустить его командой:
systemctl enable --now chronyd.service
Настройка
Клиенты NTP должны знать, с какими серверами NTP они должны связаться, чтобы получить текущее время. Серверы NTP могут быть указаны в директиве server в файле конфигурации NTP.
Отредактируйте конфигурационный файл /etc/chrony.conf для добавления/удаления серверов.
Данные по умолчанию:
# Use public servers from the pool. ntp. org project.
# Please consider joining the pool (http: //www. pool. ntp. org/join.html).
server ntp1.vniiftri.ru iburst
server ntp2.vniiftri.ru iburst
server ntp3.vniiftri.ru iburst
server ntp4.vniiftri.ru iburst
Параметр iburst используется для ускорения начальной синхронизации.
Управление Chronyd
Для chrony есть утилита командной строки с именем chronyc для управления и мониторинга сервиса chrony (chronyd).
Для проверки синхронизации chrony, можно использовать команду tracking
, как показано ниже:
chronyc tracking
Вывод должен выглядеть следующим образом:
Reference ID : 596DFB17 (ntp3.vniiftri.ru) Stratum : 2 Ref time (UTC) : Wed May 24 08:18:40 2023 System time : 0.000260688 seconds fast of NTP time Last offset : +0.000226291 seconds RMS offset : 0.001286364 seconds Frequency : 8.707 ppm slow Residual freq : +0.024 ppm Skew : 3.054 ppm Root delay : 0.016705679 seconds Root dispersion : 0.000947660 seconds Update interval : 64.9 seconds Leap status : Normal
Перечисленные пункты содержат следующую информацию:
- Reference ID — идентификатор и имя сервера, с которым компьютер в настоящее время синхронизирован;
- Stratum — количество переходов к серверу с установленными эталонными часами;
- Ref time — время по Гринвичу, в которое было выполнено последнее измерение из эталонного источника;
- System time — задержка системных часов от синхронизированного сервера;
- Last offset — расчетное смещение последнего обновления часов;
- RMS offset — долгосрочное среднее арифметическое значения смещения;
- Frequency — частота, на которой часы системы будут работать неправильно, если хронограф не проведет коррекцию. Она выражена в ppm — ч/м (частей на миллион);
- Residual freq — остаточная частота указывает на разницу между измерениями от опорного источника и используемой в настоящее время частотой;
- Skew — расчетная погрешность, связанная с погрешностью частоты;
- Root delay — суммарная задержка сетевого пути к опорному серверу, с которым синхронизируется компьютер;
- Leap status — статус скачка (изменения) времени, который может иметь одно из следующих значений:
- «Normal» – означает нормальную корректировку времени;
- «Insert second» – означает, что произведена корректировка времени добавлением дополнительной секунды в последнюю минуту текущего месяца;
- «Delete second» – означает, что произведена корректировка времени удалением дополнительной секунды из последней минуты текущего месяца;
- «Not synchronised» – означает, что компьютер в данный момент времени не синхронизирован.
Также есть возможность проверить текущие источники времени, которые использует chrony:
chronyc sources
Вывод должен выглядеть следующим образом:
MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^+ ntp1.vniiftri.ru 1 6 272 271 -264us[ +347us] +/- 7394us ^+ ntp2.vniiftri.ru 1 6 377 77 +2910us[+3321us] +/- 9806us ^* ntp3.vniiftri.ru 1 6 377 13 +848us[+1296us] +/- 6958us ^+ ntp4.vniiftri.ru 1 6 377 11 +895us[ +895us] +/- 6879us
Утилита Chronyc может находить статистику каждого источника, например, скорость дрейфа и процесс оценки смещения, используя команду sourcestats:
chronyc sourcestats
Вывод должен выглядеть следующим образом:
Name/IP Address NP NR Span Frequency Freq Skew Offset Std Dev ============================================================================== ntp1.vniiftri.ru 7 5 517 -1.228 4.945 -1149us 242us ntp2.vniiftri.ru 7 5 388 +4.855 22.098 +1466us 1091us ntp3.vniiftri.ru 11 9 646 +1.307 6.637 -5544ns 1036us ntp4.vniiftri.ru 11 7 647 +1.544 3.566 +599us 501us
Чтобы сообщить Chrony, что вы больше не подключены к глобальной сети Интернет, выполните следующие действия:
chronyc offline
Для проверки статуса источников NTP, необходимо запустить следующую команду:
chronyc activity
Вывод должен выглядеть следующим образом:
200 0K 4 sources online 0 sources offline 0 sources doing burst (return to online) 0 sources doing burst (return to offline) 0 sources with unknown address
Когда система будет вновь подключена к Интернету, необходимо сообщить об этом chrony, используя команду:
chronyc online
Для более подробного объяснения всех параметров следует руководствоваться Справочными страницами.
man chronyc man chronyd
Эта информация оказалась полезной? ДА НЕТ
Дата последнего изменения: 10.03.2025
Если вы нашли ошибку, пожалуйста, выделите текст и нажмите Ctrl+Enter.
Configureg NTP client on Windows.
Procedure to configure NTP client on Windows
Windows Server (all releases)
- Windows server 2019
- Windows server 2016
- Windows server 2012 R2
- Windows server 2012
- Windows server 2008 R2
- Windows server 2008
Windows Desktop (all releases)
- Windows 10
- Windows 8.1
- Windows 8
- Windows 7
Configuring NTP client on Windows.
0. Before start.
To configure NTP client you need Administrator privileges or Administartor’s password.
It is not possible to change configuration without sufficient privileges.
Below are several times four very similar commands with following meaning:
- 1st line: define variable myKey with working key.
- 2st line: show current value of parameter ( QUERY ),
- 3nd line: add (if not defined) or change parameter to new value ( ADD ),
- 4rd line: show new parameter value ( QUERY ).
In situation when command fails or existing value is alredy set to desired value, result of commands in second and fourth line will be the same.
Please note, that commands may be splitted to several lines depending of device browser width.
1.) Open elevated Administrator command prompt.
- on keyboard press windows key to open start menu,
- after start menu opens type "cmd",
- choose option "Run As Administrator",
- if current user has not enough privileges, password popup will open.
Command «cmd» will start in «Elevated mode».
This mode is recognized with user name «Administrator» in title of cmd window.
Carefully enter (copy/paste) commands below from steps 2 to 8.
2.) Change MinPollInterval from default 0xa (2^10 = 1024sec) to 0x6 (2^6 = 64sec).
set myKey=HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Config
REG QUERY %myKey% /v MinPollInterval
REG ADD %myKey% /v MinPollInterval /t REG_DWORD /d 0x6 /f
REG QUERY %myKey% /v MinPollInterval
3.) Change MaxPollInterval from default 0xf (2^15 = 32768 sec) to 0xa (2^10 = 1024 sec).
set myKey=HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Config
REG QUERY %myKey% /v MaxPollInterval
REG ADD %myKey% /v MaxPollInterval /t REG_DWORD /d 0xa /f
REG QUERY %myKey% /v MaxPollInterval
4.) Change Client Type to NTP.
set myKey=HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Parameters
REG QUERY %myKey% /v Type
REG ADD %myKey% /v Type /t REG_SZ /d NTP /f
REG QUERY %myKey% /v Type
5.) Change NtpClient state to enabled.
set myKey=HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient
REG QUERY %myKey% /v Enabled
REG ADD %myKey% /v Enabled /t REG_DWORD /d 0x1 /f
REG QUERY %myKey% /v Enabled
6.) Register and restart NTP service.
w32tm /register
net stop w32time
net start w32time
7.) Select IP protocol version.
In order to align server connection to your network configuration it is advisable to define IP protocol version for time synchronization.
There are three possible variants — use one from list:
For dual stacked IPv4 and IPv6 connected device(s) use:
set myTld="pool.chrony.eu"
For IPv4 connected device(s) use:
set myTld="ipv4.pool.chrony.eu"
For and IPv6 connected device(s) use:
set myTld="ipv6.pool.chrony.eu"
8.) Configure NTP client.
Continue with this list of commands to configure Windoes NTP client:
set myServers="1.%myTld%,0x08 2.%myTld%,0x08 3.%myTld%,0x08 4.%myTld%,0x08"
set myKey=HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Parameters
REG QUERY %myKey%
w32tm /config /manualpeerlist:%myServers% /syncfromflags:manual /update
REG QUERY %myKey%
Description of operation
This procedure will enable NTP client, set minimum update interval to 64s (1min 4sec), maximum update interval to 1024s (17min 3sec) and configure NTP client depending on computer connectivity.
Correction of MinPollInterval and MaxPollInterval is necessary because default values are too coarse for built in CMOS clock, which may have time drift of several seconds for default MaxPollInterval configured of 32768s (9hours 6minutes 8seconds).
NTP client will slowly drift time in computer to correct NTP synchronized time.
How long will computer run synchronization is dependent from current skew from correct time.
Synchronization of computer time is maintained until computer is powered on.
Depending on duration of power off time, internal CMOS clock maintains coarse time.
At computer power on event NTP client reads configuration and starts with time synchronization.
If time difference between computer and reference source is reasonably small, time is adjusted in several steps and time synchronization is achieved quickly.
For long power off periods, when there is sufficient time difference between CMOS battery time and reference source synchronization time may be reasonably long.
2.1. What is the minimum recommended configuration for an NTP client?
First, the client needs to know which NTP servers it should ask for the current
time. They are specified by the server
or pool
directive. The pool
directive is used with names that resolve to multiple addresses of different
servers. For reliable operation, the client should have at least three servers.
The iburst
option enables a burst of requests to speed up the initial
synchronisation.
To stabilise the initial synchronisation on the next start, the estimated drift
of the system clock is saved to a file specified by the driftfile
directive.
If the system clock can be far from the true time after boot for any reason,
chronyd
should be allowed to correct it quickly by stepping instead of
slewing, which would take a very long time. The makestep
directive does
that.
In order to keep the real-time clock (RTC) close to the true time, so the
system time is reasonably close to the true time when it is initialised on the
next boot from the RTC, the rtcsync
directive enables a mode in which the
system time is periodically copied to the RTC. It is supported on Linux and
macOS.
If you wanted to use public NTP servers from the
pool.ntp.org project, the minimal chrony.conf file
could be:
pool pool.ntp.org iburst driftfile /var/lib/chrony/drift makestep 1 3 rtcsync
2.2. How do I make an NTP server?
By default, chronyd
does not operate as an NTP server. You need to add an
allow
directive to the chrony.conf file in order for chronyd
to open the
server NTP port and respond to client requests.
An allow
directive with no specified subnet allows access from all IPv4 and
IPv6 addresses.
2.3. Should all computers on a LAN be clients of an external server?
It depends on the requirements. Usually, the best configuration is to make one
computer the server, with the others as clients of it. Add a local
directive
to the server’s chrony.conf file. This configuration will be better because
-
the load on the external connection is less
-
the load on the external NTP server(s) is less
-
if your external connection goes down, the computers on the LAN
will maintain a common time with each other.
2.4. Must I specify servers by IP address if DNS is not available on chronyd
start?
No, chronyd
will keep trying to resolve
the names specified by the server
, pool
, and peer
directives in an
increasing interval until it succeeds. The online
command can be issued from
chronyc
to force chronyd
to try to resolve the names immediately.
2.5. How can I make chronyd
more secure?
If you do not need to use chronyc
, or you want to run chronyc
only
under the root or chrony user (which can access chronyd
through a Unix
domain socket), you can disable the IPv4 and IPv6 command sockets (by default
listening on localhost) by adding cmdport 0
to the configuration file.
You can specify an unprivileged user with the -u
option, or the user
directive in the chrony.conf file, to which chronyd
will switch after start
in order to drop root privileges. The configure script has a --with-user
option, which sets the default user. On Linux, chronyd
needs to be compiled
with support for the libcap
library. On other systems, chronyd
forks into
two processes. The child process retains root privileges, but can only perform
a very limited range of privileged system calls on behalf of the parent.
Also, if chronyd
is compiled with support for the Linux secure computing
(seccomp) facility, you can enable a system call filter with the -F
option.
It will significantly reduce the kernel attack surface and possibly prevent
kernel exploits from the chronyd
process if it is compromised. It is
recommended to enable the filter only when it is known to work on the version of
the system where chrony
is installed as the filter needs to allow also system
calls made from libraries that chronyd
is using (e.g. libc) and different
versions or implementations of the libraries might make different system calls.
If the filter is missing some system call, chronyd
could be killed even in
normal operation.
2.6. How can I make the system clock more secure?
An NTP client synchronising the system clock to an NTP server is susceptible to
various attacks, which can break applications and network protocols relying on
accuracy of the clock (e.g. DNSSEC, Kerberos, TLS, WireGuard).
Generally, a man-in-the-middle (MITM) attacker between the client and server
can
-
make fake responses, or modify real responses from the server, to create an
arbitrarily large time and frequency offset, make the server appear more
accurate, insert a leap second, etc. -
delay the requests and/or responses to create a limited time offset and
temporarily also a limited frequency offset -
drop the requests or responses to prevent updates of the clock with new
measurements -
redirect the requests to a different server
The attacks can be combined for a greater effect. The attacker can delay
packets to create a significant frequency offset first and then drop all
subsequent packets to let the clock quickly drift away from the true time.
The attacker might also be able to control the server’s clock.
Some attacks cannot be prevented. Monitoring is needed for detection, e.g. the
reachability register in the sources
report shows missing packets. The extent
to which the attacker can control the client’s clock depends on its
configuration.
Enable authentication to prevent chronyd
from accepting modified, fake, or
redirected packets. It can be enabled with a symmetric key specified by the
key
option, or Network Time Security (NTS) by the nts
option (supported
since chrony
version 4.0). The server needs to support the selected
authentication mechanism. Symmetric keys have to be configured on both client
and server, and each client must have its own key (one per server).
The maximum offset that the attacker can insert in an NTP measurement by
delaying packets can be limited by the maxdelay
option. The default value is
3 seconds. The measured delay is reported as the peer delay in the ntpdata
report and measurements
log. Set the maxdelay
option to a value larger than
the maximum value that is normally observed. Note that the delay can increase
significantly even when not under an attack, e.g. when the network is congested
or the routing has changed.
The maximum accepted change in time offset between clock updates can be limited
by the maxchange
directive. Larger changes in the offset will be ignored or
cause chronyd
to exit. Note that the attacker can get around this limit by
splitting the offset into multiple smaller offsets and/or creating a large
frequency offset. When this directive is used, chronyd
will have to be
restarted after a successful attack. It will not be able to recover on its own.
It must not be restarted automatically (e.g. by the service manager).
The impact of a large accepted time offset can be reduced by disabling clock
steps, i.e. by not using the makestep
and initstepslew
directives. The
offset will be slowly corrected by speeding up or slowing down the clock at a
rate which can be limited by the maxslewrate
directive. Disabling clock steps
completely is practical only if the clock cannot gain a larger error on its
own, e.g. when the computer is shut down or suspended, and the maxslewrate
limit is large enough to correct an expected error in an acceptable time. The
rtcfile
directive with the -s
option can be used to compensate for the RTC
drift.
A more practical approach is to enable makestep
for a limited number of clock
updates (the 2nd argument of the directive) and limit the offset change in all
updates by the maxchange
directive. The attacker will be able to make only a
limited step and only if the attack starts in a short window after booting the
computer, or when chronyd
is restarted without the -R
option.
The frequency offset can be limited by the maxdrift
directive. The measured
frequency offset is reported in the drift file, tracking
report, and
tracking
log. Set maxdrift
to a value larger than the maximum absolute
value that is normally observed. Note that the frequency of the clock can
change due to aging of the crystal, differences in calibration of the clock
source between reboots, migrated virtual machine, etc. A typical computer clock
has a drift smaller than 100 parts per million (ppm), but much larger drifts
are possible (e.g. in some virtual machines).
Use only trusted servers, which you expect to be well configured and managed,
using authentication for their own servers, etc. Use multiple servers, ideally
in different locations. The attacker will have to deal with a majority of the
servers in order to pass the source selection and update the clock with a large
offset. Use the minsources
directive to increase the required number of
selectable sources to make the selection more robust.
Do not specify servers as peers. The symmetric mode is less secure than the
client/server mode. If not authenticated, it is vulnerable to off-path
denial-of-service attacks, and even when it is authenticated, it is still
susceptible to replay attacks.
Mixing of authenticated and unauthenticated servers should generally be
avoided. If mixing is necessary (e.g. for a more accurate and stable
synchronisation to a closer server which does not support authentication), the
authenticated servers should be configured as trusted and required to not allow
the unauthenticated servers to override the authenticated servers in the source
selection. Since chrony
version 4.0, the selection options are enabled in
such a case automatically. This behaviour can be disabled or modified by the
authselectmode
directive.
An example of a client configuration limiting the impact of the attacks could
be
server ntp1.example.net iburst nts maxdelay 0.1 server ntp2.example.net iburst nts maxdelay 0.2 server ntp3.example.net iburst nts maxdelay 0.05 server ntp4.example.net iburst nts maxdelay 0.1 server ntp5.example.net iburst nts maxdelay 0.1 minsources 3 maxchange 100 0 0 makestep 0.001 1 maxdrift 100 maxslewrate 100 driftfile /var/lib/chrony/drift ntsdumpdir /var/lib/chrony rtcsync
2.7. How can I improve the accuracy of the system clock with NTP sources?
Select NTP servers that are well synchronised, stable and close to your
network. It is better to use more than one server. Three or four is usually
recommended as the minimum, so chronyd
can detect servers that serve false
time and combine measurements from multiple sources.
If you have a network card with hardware timestamping supported on Linux, it
can be enabled by the hwtimestamp
directive. It should make local receive and
transmit timestamps of NTP packets much more stable and accurate.
The server
directive has some useful options: minpoll
, maxpoll
,
polltarget
, maxdelay
, maxdelayratio
, maxdelaydevratio
, xleave
,
filter
.
The first three options set the minimum and maximum allowed polling interval,
and how should be the actual interval adjusted in the specified range. Their
default values are 6 (64 seconds) for minpoll
, 10 (1024 seconds) for
maxpoll
and 8 (samples) for polltarget
. The default values should be used
for general servers on the Internet. With your own NTP servers, or if you have
permission to poll some servers more frequently, setting these options for
shorter polling intervals might significantly improve the accuracy of the
system clock.
The optimal polling interval depends mainly on two factors, stability of the
network latency and stability of the system clock (which mainly depends on the
temperature sensitivity of the crystal oscillator and the maximum rate of the
temperature change).
Generally, if the sourcestats
command usually reports a small number of
samples retained for a source (e.g. fewer than 16), a shorter polling interval
should be considered. If the number of samples is usually at the maximum of 64,
a longer polling interval might work better.
An example of the directive for an NTP server on the Internet that you are
allowed to poll frequently could be
server ntp.example.net minpoll 4 maxpoll 6 polltarget 16
An example using shorter polling intervals with a server located in the same
LAN could be
server ntp.local minpoll 2 maxpoll 4 polltarget 30
The maxdelay options are useful to ignore measurements with an unusually large
delay (e.g. due to congestion in the network) and improve the stability of the
synchronisation. The maxdelaydevratio
option could be added to the example
with local NTP server
server ntp.local minpoll 2 maxpoll 4 polltarget 30 maxdelaydevratio 2
If your server supports the interleaved mode (e.g. it is running chronyd
),
the xleave
option should be added to the server
directive to enable the
server to provide the client with more accurate transmit timestamps (kernel or
preferably hardware). For example:
server ntp.local minpoll 2 maxpoll 4 xleave
When combined with local hardware timestamping, good network switches, and even
shorter polling intervals, a sub-microsecond accuracy and stability of a few
tens of nanoseconds might be possible. For example:
server ntp.local minpoll 0 maxpoll 0 xleave hwtimestamp eth0
For best stability, the CPU should be running at a constant frequency (i.e.
disabled power saving and performance boosting). Energy-Efficient Ethernet
(EEE) should be disabled in the network. The switches should be configured to
prioritize NTP packets, especially if the network is expected to be heavily
loaded. The dscp
directive can be used to set the Differentiated Services
Code Point in transmitted NTP packets if needed.
If it is acceptable for NTP clients in the network to send requests at a high
rate, a sub-second polling interval can be specified. A median filter
can be enabled in order to update the clock at a reduced rate with more stable
measurements. For example:
server ntp.local minpoll -6 maxpoll -6 filter 15 xleave hwtimestamp eth0 minpoll -6
Since chrony
version 4.3, the minimum minpoll
is -7 and a filter using a
long-term estimate of a delay quantile can be enabled by the maxdelayquant
option to replace the default maxdelaydevratio
filter, which is sensitive to
outliers corrupting the minimum delay. For example:
server ntp.local minpoll -7 maxpoll -7 filter 31 maxdelayquant 0.3 xleave
Since version 4.2, chronyd
supports an NTPv4
extension field containing an additional timestamp to enable frequency transfer
and significantly improve stability of synchronisation. It can be enabled by
the extfield F323
option. For example:
server ntp.local minpoll 0 maxpoll 0 xleave extfield F323
Since version 4.5, chronyd
can apply corrections from PTP one-step end-to-end
transparent clocks (e.g. network switches) to significantly improve accuracy of
synchronisation in local networks. It requires the PTP transport to be enabled
by the ptpport
directive, HW timestamping, and the extfield F324
option.
For example:
server ntp.local minpoll -4 maxpoll -4 xleave extfield F323 extfield F324 port 319 ptpport 319 hwtimestamp eth0 minpoll -4
2.8. Does chronyd
have an ntpdate mode?
Yes. With the -q
option chronyd
will set the system clock once and exit.
With the -Q
option it will print the measured offset without setting the
clock. If you do not want to use a configuration file, NTP servers can be
specified on the command line. For example:
# chronyd -q 'pool pool.ntp.org iburst'
The command above would normally take about 5 seconds if the servers were
well synchronised and responding to all requests. If not synchronised or
responding, it would take about 10 seconds for chronyd
to give up and exit
with a non-zero status. A faster configuration is possible. A single server can
be used instead of four servers, the number of measurements can be reduced with
the maxsamples
option to one (supported since chrony
version 4.0), and a
timeout can be specified with the -t
option. The following command would take
only up to about one second.
# chronyd -q -t 1 'server pool.ntp.org iburst maxsamples 1'
It is not recommended to run chronyd
with the -q
option periodically (e.g.
from a cron job) as a replacement for the daemon mode, because it performs
significantly worse (e.g. the clock is stepped and its frequency is not
corrected). If you must run it this way and you are using a public NTP server,
make sure chronyd
does not always start around the first second of a minute,
e.g. by adding a random sleep before the chronyd
command. Public servers
typically receive large bursts of requests around the first second as there is
a large number of NTP clients started from cron with no delay.
2.9. Can chronyd
be configured to control the clock like ntpd
?
It is not possible to perfectly emulate ntpd
, but there are some options that
can configure chronyd
to behave more like ntpd
if there is a reason to
prefer that.
In the following example the minsamples
directive slows down the response to
changes in the frequency and offset of the clock. The maxslewrate
and
corrtimeratio
directives reduce the maximum frequency error due to an offset
correction and the maxdrift
directive reduces the maximum assumed frequency
error of the clock. The makestep
directive enables a step threshold and the
maxchange
directive enables a panic threshold. The maxclockerror
directive
increases the minimum dispersion rate.
minsamples 32 maxslewrate 500 corrtimeratio 100 maxdrift 500 makestep 0.128 -1 maxchange 1000 1 1 maxclockerror 15
Note that increasing minsamples
might cause the offsets in the tracking
and
sourcestats
reports/logs to be significantly smaller than the actual offsets
and be unsuitable for monitoring.
2.10. Can NTP server be separated from NTP client?
Yes, it is possible to run multiple instances of chronyd
on a computer at the
same time. One can operate primarily as an NTP client to synchronise the system
clock and another as a server for other computers. If they use the same
filesystem, they need to be configured with different pidfiles, Unix domain
command sockets, and any other file or directory specified in the configuration
file. If they run in the same network namespace, they need to use different NTP
and command ports, or bind the ports to different addresses or interfaces.
The server instance should be started with the -x
option to prevent it from
adjusting the system clock and interfering with the client instance. It can be
configured as a client to synchronise its NTP clock to other servers, or the
client instance running on the same computer. In the latter case, the copy
option (added in chrony
version 4.1) can be used to assume the reference ID
and stratum of the client instance, which enables detection of synchronisation
loops with its own clients.
On Linux, starting with chrony
version 4.0, it is possible to run multiple
server instances sharing a port to better utilise multiple cores of the CPU.
Note that for rate limiting and client/server interleaved mode to work well
it is necessary that all packets received from the same address are handled by
the same server instance.
An example configuration of the client instance could be
pool pool.ntp.org iburst allow 127.0.0.1 port 11123 driftfile /var/lib/chrony/drift makestep 1 3 rtcsync
and configuration of the first server instance could be
server 127.0.0.1 port 11123 minpoll 0 maxpoll 0 copy allow cmdport 11323 bindcmdaddress /var/run/chrony/chronyd-server1.sock pidfile /var/run/chronyd-server1.pid driftfile /var/lib/chrony/drift-server1
2.11. How can chronyd
be configured to minimise downtime during restarts?
The dumpdir
directive in chrony.conf provides chronyd
a location to save
a measurement history of the sources it uses when the service exits. The -r
option then enables chronyd
to load state from the dump files, reducing the
synchronisation time after a restart.
Similarly, the ntsdumpdir
directive provides a location for chronyd
to save
NTS cookies received from the server to avoid making a NTS-KE request when
chronyd
is started. When operating as an NTS server, chronyd
also saves
cookies keys to this directory to allow clients to continue to use the old keys
after a server restart for a more seamless experience.
On Linux systems,
systemd
socket activation provides a mechanism to reuse server sockets across
chronyd
restarts, so that client requests will be buffered until the service
is again able to handle the requests. This allows for zero-downtime service
restarts, simplified dependency logic at boot, and on-demand service spawning
(for instance, for separated server chronyd
instances run with the -x
flag).
Socket activation is supported since chrony
version 4.5.
The service manager (systemd) creates sockets and
passes file descriptors to them to the process via the LISTEN_FDS
environment
variable. Before opening new sockets, chronyd
first checks for and attempts
to reuse matching sockets passed from the service manager. For instance, if an
IPv4 datagram socket bound on bindaddress
and port
is available, it will be
used by the NTP server to accept incoming IPv4 requests.
An example systemd socket unit is below, where chronyd
is configured with
bindaddress 0.0.0.0
, bindaddress ::
, port 123
, and ntsport 4460
.
[Unit] Description=chronyd server sockets [Socket] Service=chronyd.service # IPv4 NTP server ListenDatagram=0.0.0.0:123 # IPv6 NTP server ListenDatagram=[::]:123 # IPv4 NTS-KE server ListenStream=0.0.0.0:4460 # IPv6 NTS-KE server ListenStream=[::]:4460 BindIPv6Only=ipv6-only [Install] WantedBy=sockets.target
2.12. Should be a leap smear enabled on NTP server?
With the smoothtime
and leapsecmode
directives it is possible to enable a
server leap smear in order to hide leap seconds from clients and force them to
follow a slow server’s adjustment instead.
This feature should be used only in local networks and only when necessary,
e.g. when the clients cannot be configured to handle the leap seconds as
needed, or their number is so large that configuring them all would be
impractical. The clients should use only one leap-smearing server, or multiple
identically configured leap-smearing servers. Note that some clients can get
leap seconds from other sources (e.g. with the leapsectz
directive in
chrony
) and they will not work correctly with a leap smearing server.
2.13. How should chronyd
be configured with gpsd
?
A GPS or other GNSS receiver can be used as a reference clock with gpsd
. It
can work as one or two separate time sources for each connected receiver. The
first time source is based on timestamping of messages sent by the receiver.
Typically, it is accurate to milliseconds. The other source is much more
accurate. It is timestamping a pulse-per-second (PPS) signal, usually connected
to a serial port (e.g. DCD pin) or GPIO pin.
If the PPS signal is connected to the serial port which is receiving messages
from the GPS/GNSS receiver, gpsd
should detect and use it automatically. If
it is connected to a GPIO pin, or another serial port, the PPS device needs to
be specified on the command line as an additional data source. On Linux, the
ldattach
utility can be used to create a PPS device for a serial device.
The PPS-based time source provided by gpsd
is available as a SHM 1
refclock, or other odd number if gpsd
is configured with multiple receivers,
and also as SOCK /var/run/chrony.DEV.sock
where DEV
is the name of the
serial device (e.g. ttyS0).
The message-based time source is available as a SHM 0
refclock (or other even
number) and since gpsd
version 3.25 also as
SOCK /var/run/chrony.clk.DEV.sock
where DEV
is the name of the serial
device.
The SOCK refclocks should be preferred over SHM for better security
(the shared memory segment needs to be created by chronyd
or gpsd
with an
expected owner and permissions before an untrusted application or user has a
chance to create its own in order to feed chronyd
with false measurements).
gpsd
needs to be started after chronyd
in order to connect to the socket.
With chronyd
and gpsd
both supporting PPS, there are two different
recommended configurations:
# First option refclock SOCK /var/run/chrony.ttyS0.sock refid GPS # Second option refclock PPS /dev/pps0 lock NMEA refid GPS refclock SOCK /var/run/chrony.clk.ttyS0.sock offset 0.5 delay 0.1 refid NMEA noselect
They both have some advantages:
-
SOCK
can be more accurate thanPPS
ifgpsd
corrects for the
sawtooth error provided by the receiver in serial data -
PPS
can be used with higher PPS rates (specified by therate
option),
but it requires a second refclock or another time source to pair pulses
with seconds, and theSOCK
offset needs to be specified
correctly to compensate for the message delay, while
gpsd
can apply HW-specific information
If the PPS signal is not available, or cannot be used for some reason, the only
option is the message-based timing
refclock SOCK /var/run/chrony.clk.ttyS0.sock offset 0.5 delay 0.1 refid GPS
or the SHM equivalent if using gpsd
version before 3.25
refclock SHM 0 offset 0.5 delay 0.1 refid GPS
2.14. Does chrony
support PTP?
No, the Precision Time Protocol (PTP) is not supported as a protocol for
synchronisation of clocks and there are no plans
to support it. It is a complex protocol, which shares some issues with the
NTP broadcast mode. One of the main differences between NTP and PTP is that PTP
was designed to be easily supported in hardware (e.g. network switches and
routers) in order to make more stable and accurate measurements. PTP relies on
the hardware support. NTP does not rely on any support in the hardware, but if
it had the same support as PTP, it could perform equally well.
On Linux, chrony
supports hardware clocks that some NICs have for PTP. They
are called PTP hardware clocks (PHC). They can be used as reference clocks
(specified by the refclock
directive) and for hardware timestamping of NTP
packets (enabled by the hwtimestamp
directive) if the NIC can timestamp other
packets than PTP, which is usually the case at least for transmitted packets.
The ethtool -T
command can be used to verify the timestamping support.
As an experimental feature added in version 4.2, chrony
can use PTP as a
transport for NTP messages (NTP over PTP) to enable hardware timestamping on
hardware which can timestamp PTP packets only. It can be enabled by the
ptpport
directive. Since version 4.5, chrony
can also apply corrections
provided by PTP one-step end-to-end transparent clocks to reach the accuracy of
ordinary PTP clocks. The application of PTP corrections can be enabled by the
extfield F324
option.
2.15. How can I avoid using wrong PHC refclock?
If your system has multiple PHC devices, normally named by udev
as
/dev/ptp0, /dev/ptp1, and so on, their order can change randomly across
reboots depending on the order of initialisation of their drivers. If a PHC
refclock is specified by this name, chronyd
could be using a wrong refclock
after reboot. To prevent that, you can configure udev
to create a stable
symlink for chronyd
with a rule like this (e.g. written to
/etc/udev/rules.d/80-phc.rules):
KERNEL=="ptp[0-9]*", DEVPATH=="/devices/pci0000:00/0000:00:01.2/0000:02:00.0/ptp/*", SYMLINK+="ptp-i350-1"
You can get the full DEVPATH of an existing PHC device with the udevadm
command. You will need to execute the
infoudevadm trigger
command, or
reboot the system, for these changes to take effect.
2.16. Why are client log records dropped before reaching clientloglimit
?
The number of dropped client log records reported by the serverstats
command
can be increasing before the number of clients reported by the clients
command
reaches the maximum value corresponding to the memory limit set by the
clientloglimit
directive.
This is due to the design of the data structure keeping the client records. It
is a hash table which can store only up to 16 colliding addresses per slot. If
a slot has more collisions and the table already has the maximum size, the
oldest record will be dropped and replaced by the new client.
Note that the size of the table is always a power of two and it can only grow.
The limit set by the clientloglimit
directive takes into account that two
copies of the table exist when it is being resized. This means the actual
memory usage reported by top
and other utilities can be significantly smaller
than the limit even when the maximum number of records is used.
The absolute maximum number of client records kept at the same time is
16777216.
2.17. What happened to the commandkey
and generatecommandkey
directives?
They were removed in version 2.2. Authentication is no longer supported in the
command protocol. Commands that required authentication are now allowed only
through a Unix domain socket, which is accessible only by the root and chrony
users. If you need to configure chronyd
remotely or locally without the root
password, please consider using ssh and/or sudo to run chronyc
under the root
or chrony user on the host where chronyd
is running.
Установка и настройка NTP-сервера chrony на Rocky Linux / CentOS
Обновлено:
Опубликовано:
Тематические термины: NTP, Rocky Linux, CentOS.
Сервер синхронизации времени NTP помогает актуализировать время на всех узлах сети. В инструкции рассказано о его установке и настройке на Rocky Linux / CentOS.
Установка
Настройка
Тестирование
Настройка клиента Linux
chrony
ntp
ntpdate
Настройка клиента Windows
Установка сервера
Начиная с CentOS 8 (Rocky пакетом для синхронизации времени по умолчанию является chrony — он пришел на смену ntpd.
Устанавливаем его командой:
dnf install chrony
Разрешаем автозапуск и стартуем сервис:
systemctl enable chronyd —now
Открываем файл с настройками:
vi /etc/chrony.conf
Настраиваем серверы, с которых наш NTP будет брать эталонное время. Например:
#pool 2.centos.pool.ntp.org iburst
server 192.168.0.100 iburst prefer
server 192.168.0.110 iburst
server 127.127.1.0
* где:
- pool — указывает на выполнение синхронизации с пулом серверов.
- server — указывает на выполнение синхронизации с сервером.
- iburst — отправлять несколько пакетов (повышает точность).
- prefer — указывает на предпочитаемый сервер.
- server 127.127.1.0 — позволит в случае отказа сети Интернет брать время из своих системных часов.
* в данном примере мы закомментировали указанный пул по умолчанию и добавили свои серверы 192.168.0.100 и 192.168.0.110.
Настраиваем безопасность:
allow 192.168.0.0/24
* в данном примере мы разрешаем синхронизацию времени с нашим сервером для узлов сети 192.168.0.0/255.255.255.0.
Перезапускаем сервис:
systemctl restart chronyd
Добавляем правило в брандмауэр:
firewall-cmd —permanent —add-service=ntp
firewall-cmd —reload
Тестирование
Проверить состояние получения эталонного времени можно командой:
chronyc sources
Мы должны увидеть, примерно, следующее:
210 Number of sources = 2
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^? 127.127.1.0 0 6 0 — +0ns[ +0ns] +/- 0ns
^* server-01.dmosk.local 2 6 17 55 +629us[+1184us] +/- 152ms
Отобразить текущее время можно командой:
date
Для настройки часового пояса применяем команду:
timedatectl set-timezone Europe/Moscow
* московское время (GMT+3).
Проверить отдачу времени сервером можно введя команду на другом Linux:
ntpdate 192.168.0.15
* где 192.168.0.15 — адрес нашего NTP-сервера.
Правильный ответ имеет следующий вид:
ntpdate[3576]: adjust time server 192.168.0.15 offset 0.017657 sec
* время было рассинхронизировано на 0.017657 секунд.
Настройка клиента Linux
Для клиентов можно выбрать несколько стратегий настройки — мы рассмотрим 3:
- С помощью Chrony.
- Сервис ntpd.
- Утилиты ntpdate.
Начнем с Chrony.
Chrony
Команда для установки зависит от типа дистрибутива Linux.
а) DEB (Ubuntu / Debian / Astra):
apt-get install chrony
б) RPM (Rocky / CentOS / РЕД ОС):
yum install chrony
После установки открываем /etc/chrony.conf:
vi /etc/chrony.conf
… и в качестве сервера оставляем только наш локальный сервер, например:
server 192.168.156.215 iburst
Разрешаем автозапуск сервиса:
systemctl enable chronyd || systemctl enable chrony
Перезапускаем сервис:
systemctl restart chronyd || systemctl restart chrony
Проверить состояние работы можно командой:
chronyc sources
NTP
Устанавливаем ntp:
а) DEB (Ubuntu / Debian / Astra):
apt-get install ntp
б) RPM (Rocky / CentOS / РЕД ОС):
yum install ntp
В настройка /etc/ntp.conf в качестве сервера оставляем только наш локальный сервер, например:
server 192.168.0.15
Остальные pool и server удаляем или комментируем.
Перезапускаем NTP:
systemctl restart ntp || systemctl restart ntpd
Проверить состояние можно командой:
ntpq -p
ntpdate
Утилита командной строки выполняет разовую синхронизацию. Ее можно установить из репозитория.
а) DEB (Ubuntu / Debian / Astra):
apt-get install ntpdate
б) RPM (Rocky / CentOS / РЕД ОС):
yum install ntpdate
Чтобы автоматизировать процесс, добавляем задание в cron:
crontab -e
0 0 * * * /usr/sbin/ntpdate 192.168.0.15
* в данном примере задание будет выполняться раз в день в 00:00. /usr/sbin/ntpdate — полный путь расположения утилиты, в разных системах может быть разным — проверить стоит командой which ntpdate.
Настройка клиента Windows
В командной строке выполняем:
w32tm /config /manualpeerlist:»192.168.0.15,0×8″ /syncfromflags:manual /update