Compare commits

...

17 Commits

Author SHA1 Message Date
Miroslav Lichvar
5187c08c90 doc: update NEWS 2017-01-31 11:22:11 +01:00
Miroslav Lichvar
c8076ac10d makefile: fix distclean target to not print errors 2017-01-31 11:22:11 +01:00
Miroslav Lichvar
362d155558 examples: improve configuration examples 2017-01-31 11:22:11 +01:00
Miroslav Lichvar
7b7eb0a6e5 examples: improve systemd unit files
Add the PrivateTmp, ProtectHome, and ProtectSystem directives to better
secure the system from chronyd. It's taken from the Debian chrony
package.
2017-01-31 11:22:11 +01:00
Miroslav Lichvar
d96f49f67d test: add keys unit test 2017-01-31 11:22:11 +01:00
Miroslav Lichvar
43ba5d2126 doc: document rekey in chronyc man page
For some reason this useful command was never documented.
2017-01-31 11:22:11 +01:00
Miroslav Lichvar
48f7598fed client: add rekey to help text 2017-01-31 11:22:11 +01:00
Miroslav Lichvar
510b22e96b util: fix more coverity warnings
Coverity doesn't seem to like the new field in the IPAddr struct (used
as explicit padding of the structure) to be left uninitialized, even
though it's never used for anything and is cleared by memset() in
UTI_IPHostToNetwork() before leaving the process.
2017-01-31 11:22:10 +01:00
Miroslav Lichvar
0a0aff14d8 conf: add rawmeasurements log option
While the measurements log can be useful for debugging problems in NTP
configuration (e.g. authentication failures with symmetric keys), it
seems most users are interested only in valid measurements (e.g. for
producing graphs) and don't expect/handle entries where some of the RFC
5905 tests 1-7 failed. Modify the measurements log option to log only
valid measurements, and for debugging purposes add a new rawmeasurements
option.
2017-01-31 11:22:10 +01:00
Miroslav Lichvar
e225ac68bc test: update 110-chronyc 2017-01-27 11:54:12 +01:00
Miroslav Lichvar
58060c40a5 doc: improve FAQ 2017-01-27 11:45:50 +01:00
Miroslav Lichvar
2ac1b3d5c4 client: print tracking delay/dispersion in nanosecond resolution 2017-01-27 11:35:38 +01:00
Miroslav Lichvar
c174566982 ntp: check supported flags before enabling HW timestamping 2017-01-27 11:35:38 +01:00
Miroslav Lichvar
60fca19d40 ntp: log info message when HW timestamping is enabled 2017-01-27 10:55:28 +01:00
Miroslav Lichvar
8bcb15b02f doc: improve description of some server options 2017-01-27 10:55:28 +01:00
Miroslav Lichvar
65c2cebcd5 reference: report zero root dispersion with local reference
The server's precision is supposed to be included in client's
dispersion. Don't include it in the server's dispersion.
2017-01-27 10:55:28 +01:00
Miroslav Lichvar
2a51b45a43 test: fix memory leaks in unit tests 2017-01-27 10:55:28 +01:00
23 changed files with 308 additions and 88 deletions

View File

@@ -64,10 +64,10 @@ chronyc : $(CLI_OBJS)
$(CC) $(CFLAGS) -o chronyc $(CLI_OBJS) $(LDFLAGS) $(LIBS) $(EXTRA_CLI_LIBS)
distclean : clean
-rm -f .DS_Store
-rm -f Makefile config.h config.log
$(MAKE) -C doc distclean
$(MAKE) -C test/unit distclean
-rm -f .DS_Store
-rm -f Makefile config.h config.log
clean :
-rm -f *.o *.s chronyc chronyd core *~

2
NEWS
View File

@@ -5,6 +5,8 @@ Enhancements
------------
* Add support for precise cross timestamping of PHC on Linux
* Add minpoll, precision, nocrossts options to hwtimestamp directive
* Add rawmeasurements option to log directive and modify measurements
option to log only valid measurements from synchronised sources
* Allow sub-second polling interval with NTP sources
Bug fixes

View File

@@ -1242,6 +1242,7 @@ give_help(void)
"Other daemon commands:\0\0"
"cyclelogs\0Close and re-open log files\0"
"dump\0Dump all measurements to save files\0"
"rekey\0Re-read keys from key file\0"
"\0\0"
"Client commands:\0\0"
"dns -n|+n\0Disable/enable resolving IP addresses to hostnames\0"
@@ -2215,8 +2216,8 @@ process_cmd_tracking(char *line)
"Frequency : %.3F\n"
"Residual freq : %+.3f ppm\n"
"Skew : %.3f ppm\n"
"Root delay : %.6f seconds\n"
"Root dispersion : %.6f seconds\n"
"Root delay : %.9f seconds\n"
"Root dispersion : %.9f seconds\n"
"Update interval : %.1f seconds\n"
"Leap status : %L\n",
(unsigned long)ref_id, name,

9
conf.c
View File

@@ -97,6 +97,7 @@ static double combine_limit = 3.0;
static int cmd_port = DEFAULT_CANDM_PORT;
static int raw_measurements = 0;
static int do_log_measurements = 0;
static int do_log_statistics = 0;
static int do_log_tracking = 0;
@@ -814,7 +815,10 @@ parse_log(char *line)
log_name = line;
line = CPS_SplitWord(line);
if (*log_name) {
if (!strcmp(log_name, "measurements")) {
if (!strcmp(log_name, "rawmeasurements")) {
do_log_measurements = 1;
raw_measurements = 1;
} else if (!strcmp(log_name, "measurements")) {
do_log_measurements = 1;
} else if (!strcmp(log_name, "statistics")) {
do_log_statistics = 1;
@@ -1468,8 +1472,9 @@ CNF_GetDumpDir(void)
/* ================================================== */
int
CNF_GetLogMeasurements(void)
CNF_GetLogMeasurements(int *raw)
{
*raw = raw_measurements;
return do_log_measurements;
}

2
conf.h
View File

@@ -52,7 +52,7 @@ extern char *CNF_GetDriftFile(void);
extern char *CNF_GetLogDir(void);
extern char *CNF_GetDumpDir(void);
extern int CNF_GetLogBanner(void);
extern int CNF_GetLogMeasurements(void);
extern int CNF_GetLogMeasurements(int *raw);
extern int CNF_GetLogStatistics(void);
extern int CNF_GetLogTracking(void);
extern int CNF_GetLogRtc(void);

View File

@@ -71,7 +71,7 @@ This is always defined as a power of 2, so *minpoll 5* would mean that the
polling interval cannot drop below 32 seconds. The default is 6 (64 seconds),
the minimum is -4 (1/16th of a second), and the maximum is 24 (6 months). Note
that intervals shorter than 6 (64 seconds) should generally not be used with
public servers on the Internet as their administrators may consider it abuse.
public servers on the Internet, because it might be considered abuse.
*maxpoll* _poll_:::
In a similar way, the user might want to constrain the maximum polling interval.
Again this is specified as a power of 2, *maxpoll 9* indicates that the polling
@@ -176,9 +176,12 @@ the interleaved mode requires the servers to keep some state for each client
and the state might be dropped when there are too many clients (e.g.
<<clientloglimit,*clientloglimit*>> is too small), or it might be overwritten
by other clients that have the same IP address (e.g. computers behind NAT or
someone sending requests with a spoofed source address). The *presend* option
can be used to shorten the interval in which the server has to keep the state
for this computer and be able to respond in the interleaved mode.
someone sending requests with a spoofed source address).
+
With longer polling intervals, it is recommended to combine the *xleave* option
with the *presend* option in order to shorten the interval in which the server
has to keep the state to be able to respond in the interleaved mode. The
shorter interval also improves accuracy of the measured offset and delay.
*polltarget* _target_:::
Target number of measurements to use for the regression algorithm which
*chronyd* will try to maintain by adjusting the polling interval between
@@ -1515,10 +1518,12 @@ The log files are written to the directory specified by the <<logdir,*logdir*>>
directive. A banner is periodically written to the files to indicate the
meanings of the columns.
+
*measurements*:::
*rawmeasurements*:::
This option logs the raw NTP measurements and related information to a file
called _measurements.log_. An example line (which actually appears as a single
line in the file) from the log file is shown below.
called _measurements.log_. An entry is made for each packet received from the
source. This can be useful when debugging a problem. An example line (which
actually appears as a single line in the file) from the log file is shown
below.
+
----
2016-11-09 05:40:50 203.0.113.15 N 2 111 111 1111 10 10 1.0 \
@@ -1560,6 +1565,12 @@ from the example line above):
. Source of the local receive timestamp
(_D_=daemon, _K_=kernel, _H_=hardware). [K]
+
*measurements*:::
This option is identical to the *rawmeasurements* option, except it logs only
valid measurements from synchronised sources, i.e. measurements which passed
the RFC 5905 tests 1 through 7. This can be useful for producing graphs of the
source's performance.
+
*statistics*:::
This option logs information about the regression processing to a file called
_statistics.log_. An example line (which actually appears as a single line in

View File

@@ -130,15 +130,15 @@ performance. An example of the output is shown below.
----
Reference ID : CB00710F (foo.example.net)
Stratum : 3
Ref time (UTC) : Fri Feb 3 15:00:29 2012
System time : 0.000001501 seconds slow of NTP time
Last offset : -0.000001632 seconds
RMS offset : 0.000002360 seconds
Frequency : 331.898 ppm fast
Residual freq : 0.004 ppm
Skew : 0.154 ppm
Root delay : 0.373169 seconds
Root dispersion : 0.024780 seconds
Ref time (UTC) : Fri Jan 27 09:49:17 2017
System time : 0.000006523 seconds slow of NTP time
Last offset : -0.000006747 seconds
RMS offset : 0.000035822 seconds
Frequency : 3.225 ppm slow
Residual freq : -0.000 ppm
Skew : 0.129 ppm
Root delay : 0.013639022 seconds
Root dispersion : 0.001100737 seconds
Update interval : 64.2 seconds
Leap status : Normal
----
@@ -187,9 +187,6 @@ The '`frequency`' is the rate by which the system's clock would be wrong if
For example, a value of 1 ppm would mean that when the system's clock thinks it
has advanced 1 second, it has actually advanced by 1.000001 seconds relative to
true time.
+
As you can see in the example, the clock in the computer is not a very
good one; it would gain about 30 seconds per day if it was not corrected!
*Residual freq*:::
This shows the '`residual frequency`' for the currently selected reference
source. This reflects any difference between what the measurements from the
@@ -1133,6 +1130,10 @@ directory into which the dump files will be written. This can only be
done in the configuration file with the <<chrony.conf.adoc#dumpdir,*dumpdir*>>
directive.
[[rekey]]*rekey*::
The *rekey* command causes *chronyd* to re-read the key file specified in the
configuration file by the <<chrony.conf.adoc#keyfile,*keyfile*>> directive.
=== Client commands
[[dns]]*dns* _option_::

View File

@@ -79,7 +79,7 @@ rtcsync
You need to add an `allow` directive to the _chrony.conf_ file in order to open
the NTP port and allow `chronyd` to reply to client requests. `allow` with no
specified subnet allows all IPv4 and IPv6 addresses.
specified subnet allows access from all IPv4 and IPv6 addresses.
=== I have several computers on a LAN. Should be all clients of an external server?
@@ -97,7 +97,7 @@ _chrony.conf_ file. This configuration will be better because
No. Starting from version 1.25, `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 try to resolve them immediately.
`chronyc` to force `chronyd` to try to resolve the names immediately.
=== How can I make `chronyd` more secure?
@@ -161,7 +161,7 @@ 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 have
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 may significantly improve the accuracy of the system
clock.
@@ -195,15 +195,27 @@ server ntp.local minpoll 2 maxpoll 4 polltarget 30 maxdelaydevratio 2
----
If your server supports the interleaved mode, the `xleave` option should be
added to the `server` directive in order to receive server's more accurate
hardware or kernel transmit timestamps. When combined with local hardware
timestamping, a sub-microsecond accuracy may be possible. An example could be
added to the `server` directive in order to allow the server to send the
client more accurate hardware or kernel transmit timestamps. When combined with
local hardware timestamping, sub-microsecond accuracy may be possible. An
example could be
----
server ntp.local minpoll 2 maxpoll 2 xleave
hwtimestamp eth0
----
=== 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 don't want to use a configuration file, NTP servers can be
specified on the command line. For example:
----
# chronyd -q 'pool pool.ntp.org iburst'
----
=== What happened to the `commandkey` and `generatecommandkey` directives?
They were removed in version 2.2. Authentication is no longer supported in the
@@ -242,8 +254,17 @@ MS Name/IP address Stratum Poll Reach LastRx Last sample
=== Are NTP servers specified with the `offline` option?
Check that you're using ``chronyc``'s `online` and `offline` commands
appropriately. Again, check in _measurements.log_ to see if you're getting any
data back from the server.
appropriately. The `activity` command prints the number of sources that are
currently online and offline. For example:
----
200 OK
3 sources online
0 sources offline
0 sources doing burst (return to online)
0 sources doing burst (return to offline)
0 sources with unknown address
----
=== Is `chronyd` allowed to step the system clock?
@@ -396,15 +417,15 @@ option for all time sources in the _chrony.conf_ file.
=== What happens if the network connection is dropped without using ``chronyc``'s `offline` command first?
`chronyd` will keep trying to access the server(s) that it thinks are online.
When the network is connected again, it will take some time (on average half of
the maximum polling interval) before new measurements are made and the clock is
corrected. If the servers were set to offline and the `online` command was
issued when the network was connected, `chronyd` would make new measurements
immediately.
`chronyd` will keep trying to access the sources that it thinks are online, and
it will take longer before new measurements are actually made and the clock is
corrected when the network is connected again. If the sources were set to
offline, `chronyd` would make new measurements immediately after issuing the
`online` command.
The `auto_offline` option to the `server` entry in the _chrony.conf_ file may
be useful to switch the servers to the offline state automatically.
Unless the network connection lasts only few minutes (less than the maximum
polling interval), the delay is usually not a problem, and it may be acceptable
to keep all sources online all the time.
== Operating systems

View File

@@ -1,5 +1,6 @@
[Unit]
Description=Wait for chrony to synchronize system clock
Documentation=man:chronyc(1)
After=chronyd.service
Requires=chronyd.service
Before=time-sync.target

View File

@@ -4,8 +4,8 @@ pool pool.ntp.org iburst
# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift
# In first three updates step the system clock instead of slew
# if the adjustment is larger than 1 second.
# Allow the system clock to be stepped in the first three updates
# if its offset is larger than 1 second.
makestep 1.0 3
# Enable kernel synchronization of the real-time clock (RTC).

View File

@@ -5,17 +5,24 @@ pool pool.ntp.org iburst
# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift
# In first three updates step the system clock instead of slew
# if the adjustment is larger than 1 second.
# Allow the system clock to be stepped in the first three updates
# if its offset is larger than 1 second.
makestep 1.0 3
# Enable kernel synchronization of the real-time clock (RTC).
rtcsync
# Allow NTP client access from local network.
#allow 192.168/16
# Enable hardware timestamping on all interfaces that support it.
#hwtimestamp *
# Serve time even if not synchronized to any NTP server.
# Increase the minimum number of selectable sources required to adjust
# the system clock.
#minsources 2
# Allow NTP client access from local network.
#allow 192.168.0.0/16
# Serve time even if not synchronized to a time source.
#local stratum 10
# Specify file containing keys for NTP authentication.

View File

@@ -33,42 +33,30 @@
! pool pool.ntp.org iburst
# However, for dial-up use you probably want these instead. The word
# 'offline' means that the server is not visible at boot time. Use
# chronyc's 'online' command to tell chronyd that these servers have
# become visible after you go on-line.
! server foo.example.net offline
! server bar.example.net offline
! server baz.example.net offline
! pool pool.ntp.org offline
# You may want to specify NTP 'peers' instead. If you run a network
# with a lot of computers and want several computers running chrony to
# have the 'front-line' interface to the public NTP servers, you can
# 'peer' these machines together to increase robustness.
! peer foo.example.net
# There are other options to the 'server' and 'peer' directives that you
# might want to use. For example, you can ignore measurements whose
# round-trip-time is too large (indicating that the measurement is
# probably useless, because you don't know which way the measurement
# message got held up.) Consult the full documentation for details.
#######################################################################
### AVOIDING POTENTIALLY BOGUS CHANGES TO YOUR CLOCK
#
# To avoid changes being made to your computer's gain/loss compensation
# when the measurement history is too erratic, you might want to enable
# one of the following lines. The first seems good for dial-up (or
# other high-latency connections like slow leased lines), the second
# seems OK for a LAN environment.
# one of the following lines. The first seems good with servers on the
# Internet, the second seems OK for a LAN environment.
! maxupdateskew 100
! maxupdateskew 5
# If you want to increase the minimum number of selectable sources
# required to update the system clock in order to make the
# synchronisation more reliable, uncomment (and edit) the following
# line.
! minsources 2
# If your computer has a good stable clock (e.g. it is not a virtual
# machine), you might also want to reduce the maximum assumed drift
# (frequency error) of the clock (the value is specified in ppm).
! maxdrift 100
#######################################################################
### FILENAMES ETC
# Chrony likes to keep information about your computer's clock in files.
@@ -181,13 +169,12 @@ driftfile /var/lib/chrony/drift
# machine accesses it. The information can be accessed by the 'clients'
# command of chronyc. You can disable this facility by uncommenting the
# following line. This will save a bit of memory if you have many
# clients.
# clients and it will also disable support for the interleaved mode.
! noclientlog
# The clientlog size is limited to 512KB by default. If you have many
# clients, especially in many different subnets, you might want to
# increase the limit.
# clients, you might want to increase the limit.
! clientloglimit 4194304
@@ -196,7 +183,7 @@ driftfile /var/lib/chrony/drift
# clients that are sending requests too frequently, uncomment and edit
# the following line.
! limitrate interval 3 burst 8
! ratelimit interval 3 burst 8
#######################################################################
### REPORTING BIG CLOCK CHANGES
@@ -243,7 +230,17 @@ driftfile /var/lib/chrony/drift
# Rate limiting can be enabled also for command packets. (Note,
# commands from localhost are never limited.)
! cmdratelimit interval 1 burst 16
! cmdratelimit interval -4 burst 16
#######################################################################
### HARDWARE TIMESTAMPING
# On Linux, if the network interface controller and its driver support
# hardware timestamping, it can significantly improve the accuracy of
# synchronisation. It can be enabled on specified interfaces only, or it
# can be enabled on all interfaces that support it.
! hwtimestamp eth0
! hwtimestamp *
#######################################################################
### REAL TIME CLOCK
@@ -274,6 +271,12 @@ driftfile /var/lib/chrony/drift
! rtcdevice /dev/misc/rtc
# Alternatively, if not using the -s option, this directive can be used
# to enable a mode in which the RTC is periodically set to the system
# time, with no tracking of its drift.
! rtcsync
#######################################################################
### REAL TIME SCHEDULER
# This directive tells chronyd to use the real-time FIFO scheduler with the

View File

@@ -10,6 +10,9 @@ Type=forking
PIDFile=/var/run/chronyd.pid
EnvironmentFile=-/etc/sysconfig/chronyd
ExecStart=/usr/sbin/chronyd $OPTIONS
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
[Install]
WantedBy=multi-user.target

View File

@@ -49,6 +49,7 @@
/* ================================================== */
static LOG_FileID logfileid;
static int log_raw_measurements;
/* ================================================== */
/* Enumeration used for remembering the operating mode of one of the
@@ -353,7 +354,7 @@ NCR_Initialise(void)
do_size_checks();
do_time_checks();
logfileid = CNF_GetLogMeasurements() ? LOG_FileOpen("measurements",
logfileid = CNF_GetLogMeasurements(&log_raw_measurements) ? LOG_FileOpen("measurements",
" Date (UTC) Time IP Address L St 123 567 ABCD LP RP Score Offset Peer del. Peer disp. Root del. Root disp. Refid MTxRx")
: -1;
@@ -1687,7 +1688,7 @@ receive_packet(NCR_Instance inst, NTP_Local_Address *local_addr,
}
/* Do measurement logging */
if (logfileid != -1) {
if (logfileid != -1 && (log_raw_measurements || synced_packet)) {
LOG_FileWrite(logfileid, "%s %-15s %1c %2d %1d%1d%1d %1d%1d%1d %1d%1d%1d%d %2d %2d %4.2f %10.3e %10.3e %10.3e %10.3e %10.3e %08"PRIX32" %1d%1c %1c %1c",
UTI_TimeToLogForm(sample_time.tv_sec),
UTI_IPToString(&inst->remote_addr.ip_addr),

View File

@@ -103,7 +103,7 @@ add_interface(CNF_HwTsInterface *conf_iface)
struct ethtool_ts_info ts_info;
struct hwtstamp_config ts_config;
struct ifreq req;
int sock_fd, if_index, phc_fd;
int sock_fd, if_index, phc_fd, req_hwts_flags;
unsigned int i;
struct Interface *iface;
@@ -143,6 +143,14 @@ add_interface(CNF_HwTsInterface *conf_iface)
return 0;
}
req_hwts_flags = SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_TX_HARDWARE |
SOF_TIMESTAMPING_RAW_HARDWARE;
if ((ts_info.so_timestamping & req_hwts_flags) != req_hwts_flags) {
DEBUG_LOG(LOGF_NtpIOLinux, "HW timestamping not supported on %s", req.ifr_name);
close(sock_fd);
return 0;
}
ts_config.flags = 0;
ts_config.tx_type = HWTSTAMP_TX_ON;
ts_config.rx_filter = HWTSTAMP_FILTER_ALL;
@@ -179,7 +187,7 @@ add_interface(CNF_HwTsInterface *conf_iface)
iface->clock = HCL_CreateInstance(UTI_Log2ToDouble(MAX(conf_iface->minpoll, MIN_PHC_POLL)));
DEBUG_LOG(LOGF_NtpIOLinux, "Enabled HW timestamping on %s", iface->name);
LOG(LOGS_INFO, LOGF_NtpIOLinux, "Enabled HW timestamping on %s", iface->name);
return 1;
}

View File

@@ -1214,7 +1214,7 @@ REF_GetReferenceParams
*leap_status = LEAP_Normal;
*root_delay = 0.0;
*root_dispersion = LCL_GetSysPrecisionAsQuantum();
*root_dispersion = 0.0;
} else {

View File

@@ -20,8 +20,8 @@ RMS offset : 0\.000...... seconds
Frequency : (99|100)\.... ppm fast
Residual freq : [+-][0-9]\.... ppm
Skew : [0-9]\.... ppm
Root delay : 0\.000... seconds
Root dispersion : 0\.000... seconds
Root delay : 0\.000...... seconds
Root dispersion : 0\.000...... seconds
Update interval : [0-9]+\.. seconds
Leap status : Normal
210 Number of sources = 1

View File

@@ -68,5 +68,7 @@ test_unit(void)
}
}
HCL_DestroyInstance(clock);
LCL_Finalise();
}

147
test/unit/keys.c Normal file
View File

@@ -0,0 +1,147 @@
/*
**********************************************************************
* Copyright (C) Miroslav Lichvar 2017
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
**********************************************************************
*/
#include <keys.c>
#include "test.h"
#define KEYS 100
#define KEYFILE "keys.test-keys"
static
uint32_t write_random_key(FILE *f)
{
const char *hash_name;
char key[128];
uint32_t id;
int i, length;
length = random() % sizeof (key) + 1;
length = MAX(length, 4);
UTI_GetRandomBytes(&id, sizeof (id));
UTI_GetRandomBytes(key, length);
switch (random() % 6) {
#ifdef FEAT_SECHASH
case 0:
hash_name = "SHA1";
break;
case 1:
hash_name = "SHA256";
break;
case 2:
hash_name = "SHA384";
break;
case 3:
hash_name = "SHA512";
break;
#endif
case 4:
hash_name = "MD5";
break;
default:
hash_name = "";
}
fprintf(f, "%u %s %s", id, hash_name, random() % 2 ? "HEX:" : "");
for (i = 0; i < length; i++)
fprintf(f, "%02hhX", key[i]);
fprintf(f, "\n");
return id;
}
static void
generate_key_file(const char *name, uint32_t *keys)
{
FILE *f;
int i;
f = fopen(name, "w");
TEST_CHECK(f);
for (i = 0; i < KEYS; i++)
keys[i] = write_random_key(f);
fclose(f);
}
void
test_unit(void)
{
int i, j, data_len, auth_len;
uint32_t keys[KEYS], key;
unsigned char data[100], auth[MAX_HASH_LENGTH];
char conf[][100] = {
"keyfile "KEYFILE
};
CNF_Initialise(0);
for (i = 0; i < sizeof conf / sizeof conf[0]; i++)
CNF_ParseLine(NULL, i + 1, conf[i]);
generate_key_file(KEYFILE, keys);
KEY_Initialise();
for (i = 0; i < 100; i++) {
DEBUG_LOG(0, "iteration %d", i);
if (i) {
generate_key_file(KEYFILE, keys);
KEY_Reload();
}
UTI_GetRandomBytes(data, sizeof (data));
for (j = 0; j < KEYS; j++) {
TEST_CHECK(KEY_KeyKnown(keys[j]));
TEST_CHECK(KEY_GetAuthDelay(keys[j]) >= 0);
TEST_CHECK(KEY_GetAuthLength(keys[j]) >= 16);
data_len = random() % (sizeof (data) + 1);
auth_len = KEY_GenerateAuth(keys[j], data, data_len, auth, sizeof (auth));
TEST_CHECK(auth_len >= 16);
TEST_CHECK(KEY_CheckAuth(keys[j], data, data_len, auth, auth_len, auth_len));
if (j > 0 && keys[j - 1] != keys[j])
TEST_CHECK(!KEY_CheckAuth(keys[j - 1], data, data_len, auth, auth_len, auth_len));
auth_len = random() % auth_len + 1;
if (auth_len < MAX_HASH_LENGTH)
auth[auth_len]++;
TEST_CHECK(KEY_CheckAuth(keys[j], data, data_len, auth, auth_len, auth_len));
auth[auth_len - 1]++;
TEST_CHECK(!KEY_CheckAuth(keys[j], data, data_len, auth, auth_len, auth_len));
}
for (j = 0; j < 1000; j++) {
UTI_GetRandomBytes(&key, sizeof (key));
if (KEY_KeyKnown(key))
continue;
TEST_CHECK(!KEY_GenerateAuth(j, data, data_len, auth, sizeof (auth)));
TEST_CHECK(!KEY_CheckAuth(j, data, data_len, auth, auth_len, auth_len));
}
}
unlink(KEYFILE);
KEY_Finalise();
CNF_Finalise();
HSH_Finalise();
}

View File

@@ -295,4 +295,5 @@ test_unit(void)
SCH_Finalise();
LCL_Finalise();
CNF_Finalise();
HSH_Finalise();
}

View File

@@ -96,4 +96,5 @@ test_unit(void)
SCH_Finalise();
LCL_Finalise();
CNF_Finalise();
HSH_Finalise();
}

View File

@@ -134,4 +134,5 @@ test_unit(void)
SCH_Finalise();
LCL_Finalise();
CNF_Finalise();
HSH_Finalise();
}

4
util.c
View File

@@ -329,12 +329,14 @@ UTI_StringToIP(const char *addr, IPAddr *ip)
if (inet_pton(AF_INET, addr, &in4) > 0) {
ip->family = IPADDR_INET4;
ip->_pad = 0;
ip->addr.in4 = ntohl(in4.s_addr);
return 1;
}
if (inet_pton(AF_INET6, addr, &in6) > 0) {
ip->family = IPADDR_INET6;
ip->_pad = 0;
memcpy(ip->addr.in6, in6.s6_addr, sizeof (ip->addr.in6));
return 1;
}
@@ -344,6 +346,7 @@ UTI_StringToIP(const char *addr, IPAddr *ip)
n = sscanf(addr, "%lu.%lu.%lu.%lu", &a, &b, &c, &d);
if (n == 4) {
ip->family = IPADDR_INET4;
ip->_pad = 0;
ip->addr.in4 = ((a & 0xff) << 24) | ((b & 0xff) << 16) |
((c & 0xff) << 8) | (d & 0xff);
return 1;
@@ -442,6 +445,7 @@ void
UTI_IPNetworkToHost(IPAddr *src, IPAddr *dest)
{
dest->family = ntohs(src->family);
dest->_pad = 0;
switch (dest->family) {
case IPADDR_INET4: