When UTI_OpenFile() is removing an existing file to be replaced by a new
file, it could potentially get stuck in an infinite loop if something
was able to consistently win the race and create a new file before
chronyd.
Log a warning message after 100 failed attempts and repeat on each 10x
increase to make it more obvious to the admin, if it ever happens.
Reported-by: Eric Sesterhenn <eric.sesterhenn@x41-dsec.de>
After (re)loading symmetric NTP keys from the key file, there is an
attempt to erase the strings from the stack by calling memset() on the
buffer. However, compilers are free (and have been shown to do) optimize
this call out.
Remove the memset() call to not pretend the stack cannot not contain any
sensitive information. There is no such attempt made for the server and
client NTS keys.
Reported-by: Eric Sesterhenn <eric.sesterhenn@x41-dsec.de>
Ahmad Fatoum [Fri, 27 Jun 2025 11:58:35 +0000 (13:58 +0200)]
leapdb: fix ordered comparison against NULL pointer
fgets returns either a valid pointer with the same value as its first
argument or NULL on error or EOF.
GCC 12.2.0 -Wextra warns against relational comparison of the return
value:
leapdb.c:127:38: warning: ordered comparison of pointer with integer zero [-Wextra]
For clarity, and because the C standard doesn't mandate that valid pointers
have to compare greater than the null pointer constant, replace the
relational expression with an equality expression
Anthony Brandon [Fri, 30 May 2025 14:47:21 +0000 (16:47 +0200)]
tls: move gnutls code into tls_gnutls.c
Currently nts_ke_session.c directly calls into gnutls.
This patch moves the calls to gnutls into tls_gnutls.c with an API
defined in tls.h. This way it becomes possible to use different TLS
implementations in future patches.
Signed-off-by: Anthony Brandon <anthony@amarulasolutions.com>
Miroslav Lichvar [Tue, 24 Jun 2025 12:55:02 +0000 (14:55 +0200)]
sys_linux: drop support for kernels before 2.6.39
Linux 2.6.39 was released in 2011.
Refuse to start if a kernel version before 2.6.39 is detected. Assume
the ADJ_SETOFFSET adjtimex mode is always supported. Its verification
briefly reset the timex maxerror value to 0, which possibly confused
applications checking the value at that moment.
Drop the unneeded workaround for slow frequency updates in versions
2.6.27-2.6.32.
Miroslav Lichvar [Wed, 11 Jun 2025 12:53:47 +0000 (14:53 +0200)]
examples: improve chrony.conf examples
Add a note that three servers is the generally recommended minimum for
an NTP client to be able to detect a falseticker. Mention that the pool
directive uses four servers. Update the links to the pool join page and
list of public servers.
Miroslav Lichvar [Wed, 11 Jun 2025 11:30:57 +0000 (13:30 +0200)]
refclock_rtc: fix finalization with closed descriptor
If the RTC file descriptor was closed and removed after a read error,
don't try to close and remove it again in the driver finalization to
avoid an assertion failure on the negative descriptor.
Fixes: 4f22883f4e71 ("refclock: add new refclock for RTCs")
Miroslav Lichvar [Wed, 11 Jun 2025 07:03:48 +0000 (09:03 +0200)]
logging: don't close stderr in finalization
When logging to stderr, don't close it in finalization in case something
else still wanted to write to it. Leave it as it is together with stdin
and stdout.
conf: fix sourcedir reloading to not multiply sources
The sourcedir reload triggered by the chronyc "reload sources"
command incorrectly assumed that NSR_AddSourceByName() can return
only the NSR_Success status when a source is added. It ignored the
NSR_UnresolvedName status returned for a source whose name needs to
be resolved after the call (i.e. not specified with an IP address)
and added the source again, effectively multiplying it if the name
can be resolved to a different IP address.
Fix the code to check for the NSR_UnresolvedName status to correctly
determine whether the source was already added before and should not be
added again.
Reported-by: MichaelR <MichaelR42@runbox.com> Fixes: 916ed70c4a81 ("conf: save source status in sourcedir reload")
Miroslav Lichvar [Thu, 22 May 2025 07:17:42 +0000 (09:17 +0200)]
main: improve error message about failed notification
Mention the NOTIFY_SOCKET variable to make it more obvious what is
preventing chronyd from starting in case it's unexpectedly inherited in
a chroot etc.
Miroslav Lichvar [Tue, 20 May 2025 14:02:09 +0000 (16:02 +0200)]
socket: drop messages from unterminated Unix paths
On some systems (e.g. FreeBSD) the source Unix domain socket path
provided by recvmsg() as msg_name is not always null-terminated even if
more space than required for sockaddr_un is provided due to the padding
in the sockaddr_all union, and the returned msg_namelen value does not
indicate it is missing the termination. If a cmdmon client bound its
socket to a maximum-length path (chronyc doesn't allow that), the path
would be overread when printing a debug message and trying to send a
response.
Drop messages from paths not shorter than sun_path to avoid working with
un-printf()able and/or unreachable addresses. The clients are expected
to not use the maximum-length paths.
Miroslav Lichvar [Tue, 20 May 2025 05:59:38 +0000 (07:59 +0200)]
local+reference: fix tracking offset after failed step
If a clock step enabled by the makestep directive or requested by the
makestep command fails, accumulate the missing step back to keep the
tracking offset valid.
This fixes time served by an instance configured with the makestep
directive and the -x option (the null driver cannot perform steps) at
the same time. It will still generate error log messages.
Andreas Fenkart [Mon, 12 May 2025 08:32:57 +0000 (10:32 +0200)]
examples: fix unset OPTIONS variable warning in systemd services
Modify chronyd.service to handle cases where OPTIONS is undefined,
which occurs when /etc/sysconfig/chronyd doesn't exist or doesn't set
the variable. This prevents the warning:
"chronyd.service: Referenced but unset environment variable
evaluates to an empty string: OPTIONS"
refclock_phc: support ethernet ifname as specifier
This commit allows the user to select a PHC refclock associated with
an Ethernet interface by specifying the interface name. This allows
the user to handle situations where multiple NICs are exposing PHC
devices (or non-NIC PHC device files exist in the system) in a more
streamline manner.
Miroslav Lichvar [Wed, 30 Apr 2025 09:33:38 +0000 (11:33 +0200)]
socket: open IPv6 socket by default if IPv4 is disabled
When no remote and local address is specified, and IPv4 is disabled by
the -6 option, open an IPv6 socket. This is used by the Linux-specific
timestamping configuration and socket option checking. It enables
operation on a system that has no support for IPv4 sockets.
Paul Donald [Fri, 25 Apr 2025 00:18:43 +0000 (02:18 +0200)]
doc: improve the usage of however
However at the start means "in whatever way"/"to whatever extent".
("However chrony is configured, it won't let you in without allow")
However incorrectly at the start usually means "But" was intended.
sys_timex: detect clock interference from other processes
After an ntp_adjtime()/adjtimex() call, check if the frequency, PLL time
constant and PLL status are as expected from the previous call. If they
changed, log a warning message to indicate that another NTP client might
be running on the system and interfering with the system clock.
Switch from memcmp() to the new constant-time function to compare the
received and expected authentication data generated with a symmetric key
(NTP MAC or AES CMAC).
While this doesn't seem to be strictly necessary with the current
code, it is a recommended practice to prevent timing attacks. If
memcmp() compared the MACs one byte at a time (a typical memcmp()
implementation works with wider integers for better performance) and
chronyd as an NTP client/server/peer was leaking the timing of the
comparison (e.g. in the monitoring protocol), an attacker might be able
for a given NTP request or response find in a sequence the individual
bytes of the MAC by observing differences in the timing over a large
number of attempts. However, this process would likely be so slow the
authenticated request or response would not be useful in a MITM attack
as the expected origin timestamp is changing with each poll.
Extend the keys unit test to compare the time the function takes to
compare two identical MACs and MACs differing in the first byte
(maximizing the timing difference). It should fail if the compiler's
optimizations figure out the function can return early. The test is not
included in the util unit test to avoid compile-time optimizations with
the function and its caller together. The test can be disabled by
setting NO_TIMING_TESTS environment variable if it turns out to be
unreliable.
util: add function for constant-time memory comparison
Add a function to check if two buffers of the same length contain the
same data, but do the comparison in a constant time with respect to the
returned value to avoid creating a timing side channel, i.e. the time
depends only on the buffer length, not on the content.
Use the gnutls_memcmp() or nettle_memeql_sec() functions if available,
otherwise use the same algorithm as nettle - bitwise ORing XORed data.
Miroslav Lichvar [Thu, 20 Mar 2025 11:57:37 +0000 (12:57 +0100)]
logging: try to reopen message log on cyclelogs command
When the cyclelogs command is issued, check if the file specified by the
-l option is still in its place and if not try opening it again. If that
fails (e.g. due to chrony no longer having root privileges), keep the
old file handle to avoid losing log messages.
Miroslav Lichvar [Wed, 19 Mar 2025 13:35:54 +0000 (14:35 +0100)]
conf+cmdparse: check sanity of configured integer values
Verify that integer values specified in the configuration are sane:
interval log2 values are between -32 and 32, ports between 0 and 65535,
stratum between 0 and 16, values that should not be negative are not
negative, numbers that specify large intervals in seconds fit in the
32-bit integer, numbers don't have non-digit characters, etc.
Miroslav Lichvar [Thu, 13 Mar 2025 14:00:06 +0000 (15:00 +0100)]
reference: add wait options for local reference activation
Add "waitunsynced" option to specify how long chronyd needs to wait
before it can activate the local reference when the clock is not
synchronized to give the configured sources a chance to synchronize the
local clock after start. The default is 300 seconds when the orphan
option is enabled (same as the ntpd's default orphanwait), 0 otherwise.
Add "waitsynced" option to specify how long it should wait when the
clock is synchronized. It is an additional requirement to the distance
and activate options.
Include the number of unreachable sources in the "Can't synchronise: no
selectable sources" log message to provide a hint whether it might be a
networking issue.
Avoid logging the new warning messages about exceeded maxjitter or
maxdistance when only a small number of samples is collected after the
source becomes reachable and the values are unstable. Log the messages
only when a replacement attempt is made.
Some assertions are written as "if (x) assert(0)" to avoid having
the text of a long argument compiled in the binary. Rewrite them
to use a new BRIEF_ASSERT macro to make the condition easier to read in
its non-negated form and make it easier to turn it back to the full-text
assert if needed.
Add the number of sources that form an agreement (overlapping
intervals), if at least two agree with each other, and number of
reachable sources to the "Can't synchronize: no majority" log message to
better explain why synchronization is failing and hint that adding more
sources might help.
sources: warn about sources exceeding maxdistance or maxjitter
Log a warning message if a source is rejected in the source selecting
due to exceeding the maxdistance or maxjitter limit to make it more
obvious when synchronization is failing for this reason. Delay the
message until the reachability register is full (8 updates), or a
replacement of the source is attempted.
sources: refactor logging of source-specific selection status
Move logging of falsetickers and system peers to the mark_source()
function. Use an array to flag already logged messages in preparation
for logging of other status. Support variable number of arguments in the
logging functions.
Miroslav Lichvar [Tue, 11 Feb 2025 11:27:23 +0000 (12:27 +0100)]
cmdmon: make open commands configurable
Replace the hardcoded list of open commands (accessible over UDP),
with a list that can be configured with a new "opencommands" directive.
The default matches the original list. All read-only commands except
accheck and cmdaccheck can be enabled. The naming follows the chronyc
naming. Enable the N_SOURCES request only when needed.
This makes it possible to have a full monitoring access without access
to the Unix domain socket. It also allows restricting the monitoring
access to a smaller number of commands if some commands from the default
list are not needed.
Mention in the man page that the protocol of the non-default commands is
not consider stable and the information they provide may have security
implications.
Miroslav Lichvar [Mon, 10 Feb 2025 14:32:26 +0000 (15:32 +0100)]
cmdmon: refactor command authorization checks
Try to simplify the code and make it more robust to potential bugs.
Instead of maintaing a table mapping all commands to open/auth
permissions, use a short list of open commands. Split the processing
of the commands into two groups, read-write commands and read-only
(monitoring) commands, where the first group is processed only with full
access. Check both the socket descriptor and address type before giving
full access. While moving the code, reorder the commands alphabetically.
Miroslav Lichvar [Mon, 10 Feb 2025 14:08:03 +0000 (15:08 +0100)]
cmdmon: drop handling of NULL and LOGON requests
Handle the NULL and LOGON requests as unknown (invalid) instead of
returning the success and failed status respectively. They have
been unused for very long time now.
Add a function to fill the Unix sockaddr for binding, connecting and
sending to avoid code duplication. Use memcpy() instead of snprintf()
and provide the minimum length of the address containing the terminating
null byte. This makes it easier to support abstract sockets if needed in
future (e.g. for systemd support).
On Linux, if the NOTIFY_SOCKET variable is set, send a "READY=1"
and "STOPPING=1" message to the Unix domain socket after initialization
and before finalization respectively. This is used with the systemd
"notify" service type as documented in the sd_notity(3) man page. It's
a recommended alternative to the "forking" service type, which does not
need the PID file to determine the main process.
Support pathname Unix sockets only. Abstract sockets don't seem to be
used by systemd for notifications since version 212.
Switch the example services to the notify type, but keep the PID
file. It's still useful to prevent start of other chronyd instances.
systemd doesn't seem to care about the content of the file and should
just remove it in case chronyd didn't terminate cleanly.
Miroslav Lichvar [Wed, 11 Dec 2024 10:16:30 +0000 (11:16 +0100)]
refclock: drop filter length adjustment for polling drivers
In the refclock initialization, if the driver provides a poll()
function and 2^(poll-dpoll) is smaller than the configured length of the
median filter (64 by default), the filter is shortened to 2^(poll-dpoll)
samples, assuming the driver provides samples only in the poll()
function and at most one per call, to avoid wasting memory and before
commit 12237bf28393 ("refclock: stop requiring 4 samples in median
filter") also simplify configuration (for polling drivers only)
But this assumption is not always correct. The PHC driver can read
external PPS timestamps independently from the driver polling and the
RTC driver can timestamp interrupts. If the dpoll was too large to cover
the sample rate, some samples would be lost.
Drop the adjustment of the filter length to avoid this unexpected impact
on filtering and make it work as documented.
Uwe Kleine-König [Wed, 30 Jun 2021 14:47:21 +0000 (16:47 +0200)]
refclock: add new refclock for RTCs
This refclock uses an RTC as reference source. If the RTC doesn't
support reporting an update event this source is quite coarse as it
usually needs a slow bus access to be read and has a precision of only
one second. If reporting an update event is available, the time is read
just after such an event which improves precision.
Depending on hardware capabilities you might want to combine it with a
PPS reference clock sourced from the same chip.
Note that you can enable UIE emulation in the Linux kernel to make a RTC
without interrupt support look like one with irqs in return for some
system and bus overhead.
Co-authored-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
Ahmad Fatoum [Mon, 22 Jul 2024 15:46:44 +0000 (17:46 +0200)]
rtc: factor out RTC_Linux_ReadTimeNow
We have code to read RTC time and handle the error associated with
having no UIE interrupt, which we currently use as part of maintaining
the correction file.
In a later commit, we will need the same functionality for using the RTC
as reference clock, so export the function and give it a descriptive
name appropriate for a globally visible function.
Ahmad Fatoum [Wed, 17 Jul 2024 11:00:39 +0000 (13:00 +0200)]
rtc: factor out RTC_Linux_ReadTimeAfterInterrupt
We have code to read time after an RTC's UIE interrupt, which we
currently use as part of maintaining the correction file.
In a later commit, we will need the same functionality for using the RTC
as reference clock, so export the function and give it a descriptive
name appropriate for a globally visible function.
We have code to enable and disable the RTC's UIE interrupt, as well as
check whether it occurred and skip the first interrupt as it may be
bogus.
This is currently used as part of maintaining the correction file.
In a later commit, we will need the same functionality for using the RTC
as reference clock, so export the functions and give them descriptive
names appropriate for globally visible functions.
Ahmad Fatoum [Mon, 22 Jul 2024 11:40:59 +0000 (13:40 +0200)]
rtc: pass info whether RTC is on UTC as a function parameter
rtc_from_t() and t_from_rtc() call either gmtime or localtime depending
on the value of a global rtc_on_utc variable.
This will not be appropriate anymore when we start exporting functions
that call rtc_from_t() and t_from_rtc() for use outside of rtc_linux.c
as the rtc_on_utc variable may not have been initialized yet or at all.
Therefore make whether the RTC is on UTC a function parameter of these
functions, so the value can be propagated from the callers.
Miroslav Lichvar [Thu, 21 Nov 2024 13:30:14 +0000 (14:30 +0100)]
quantiles: add parameter to limit negative step
Add a new parameter to limit the negative value of the step state
variable. It's set as a maximum delay in number of updates before the
actual step applied to the quantile estimate starts growing from the
minimum step when the input value is consistently larger or smaller than
the estimate.
This prevents the algorithm from effectively becoming the slower 1U
variant if the quantile estimate is stable most of the time.
Set it to 100 updates for the NTP delay and 1000 updates for the hwclock
delay. An option could be added later to make it configurable.
Miroslav Lichvar [Thu, 21 Nov 2024 09:11:48 +0000 (10:11 +0100)]
quantiles: force step update with stable input values
The algorithm was designed for estimating quantiles in streams of
integer values. When the estimate is equal to the input value, the
step state variable does not change. This causes problems for the
floating-point adaptation used for measurents of delay in chrony.
One problem is numerical instability due to the strict comparison of
the input value and the current estimate.
Another problem is with signals that are so stable that the nanosecond
resolution of the system functions becomes the limitation. There is a
large difference in the value of the step state variable, which
determines how quickly the estimate will adapt to a new distribution,
between signals that are constant in the nanosecond resolution and
signals that can move in two nanoseconds.
Change the estimate update to never consider the input value equal to
the current estimate and don't set the estimate exactly to the input
value. Keep it off by a quarter of the minimum step to force jumping
around the input value if it's constant and decreasing the step variable
to negative values. Also fix the initial adjustment to step at least by
the minimum step (the original algorithm is described with ceil(), not
fabs()).
Miroslav Lichvar [Mon, 18 Nov 2024 15:18:40 +0000 (16:18 +0100)]
ntp+hwclock: add margin to estimated delay quantiles
Extend the interval of accepted delays by half of the quantile minimum
step in both directions to make room for floating-point errors in the
quantile calculation and an error that will be intentionally added in
the next commit.