For comparison purposes, a value of zero for a layer code is considered higher than any other value. Note that the maximum value of an integer encoded as a batch variable is limited by the parameter ntp.maxstratum.

Exchange period (sys.poll, peer.hostpoll, peer.peerpoll, pkt.poll). This is a signed integer variable that specifies the minimum interval between messages transmitted, measured in seconds and represented as a power of 2. For example, a value of 6 indicates a minimum interval of 64 seconds.

Accuracy (sys.precision, peer.precision, pkt.precision). This is a signed integer variable indicating the accuracy of the clock in seconds and is expressed as the nearest power of 2. The value should be rounded up to the nearest power of 2, for example, a 50-Hz (20 ms) or 60-Hz (16.67 ms) mains frequency ) will be assigned a value of -5 (31.25 ms), while the 1000-Hz quartz frequency (1 ms) will be assigned a value of -9 (1.95 ms).

Base Latency (sys.rootdelay, peer.rootdelay, pkt.rootdelay). This is the number with fixed point signed, which indicates the amount of total round-trip delay (RTT) to the primary frequency reference, expressed in seconds.

Base Variance (sys.rootdispersion, peer.rootdispersion, pkt.rootdispersion). This is the number with fixed point greater than zero, indicating the maximum value of the time error relative to the primary standard in seconds.

Reference clock identifier (sys.refid, peer.refid, pkt.refid). This is a 32-bit code that identifies a specific reference clock. In the case of layer 0 (unspecified) or layer 1 (primary reference source), this is a 4-octet ASCII string, left-justified and padded with zeros if necessary, for example:

Table 7.4. Watch ID codes
Layer Code Meaning
0 dcn dcn routing protocol
0 dts Digital time service
0 nist General nist modem
0 tsp Time protocol tsp
1 atom Atomic clock (calibrated)
1 vlf vlf -radio (omega, etc.)
1 call sign General radio
1 gps GPS UHF satellite positioning
1 lorc loran-c radio navigation
1 wwvb Radio wwvb LF (band 5)
1 goes Satellite goes UHF (band 9)
1 wwv Radio wwv HF (band 7)

In the case of layer 2 and higher (secondary reference), this is the 4-octet IP address of the partner selected for synchronization.

Reference timestamp (sys.reftime, peer.reftime, pkt.reftime) - local time in time stamp format corresponding to the moment of the last clock correction. If the local clock has not been synchronized, the variable contains zero.

Base timestamp(peer.org, pkt.org) - local time in timestamp format corresponding to the moment the last NTP message was sent. If the partner is unreachable, the variable takes the value zero.

Receipt timestamp(peer.rec, pkt.rec) - local time in timestamp format, which corresponds to the moment of arrival of the last NTP message received from the peer. If the partner is unreachable, the variable takes the value zero.

Transmission timestamp(peer.xmt, pkt.xmt) - local time in timestamp format corresponding to the moment the NTP message was sent.

System Variables

The following variables are used by the operating system to synchronize the local clock.

Variable local clock(sys.clock) contains the local clock in timestamp format. Local time is obtained from the hardware clock of a specific computer and increases discretely with design-specified increments.

Variable Basic hours(sys.peer) is a selector that identifies the clock source to use. Typically this is a pointer to a structure containing the partner's variables. A value of zero indicates that there is currently no clock source.

Partner Variables

Listed below are all partner variables that are used to control and implement measurement procedures.

Config bit(peer.config) - a bit indicating that the association was formed based on configuration information and should not be disbanded when the peer becomes unavailable.

Update timestamp(peer.update) - local time in timestamp format, marking the moment when the last NTP message was received. The variable is used to calculate the variance of the time shift.

Reachability Register(peer.reach) - shift register ntp .window bits used to determine the reachability status of the peer. Data entry is made from the low-order bits side (right). A peer is considered reachable if at least one bit of this register is 1.

Partner timer(peer.timer) - an integer counter used to control the interval between successively sent NTP messages. After setting the counter value, its contents are decreased by 1 (1sec) until it reaches zero. This calls the transfer procedure. Note that the operation of this timer should not depend on the local clock.

Batch Variables

Version number(pkt.version) - an integer indicating the version number of the sender. NTP messages are always sent with the current version value ntp .version and will be accepted only if the version codes match ( ntp.version). Exceptions are allowed only when the version number is changed.

Clock Filter Variables

When filters and selection algorithms are used, the following are additionally used: state variables.

Filter Register(peer.filter) - shift register ntp cascades. shift , where each stage stores the values ​​of the measured delay, offset, and calculated variance corresponding to one observation. These three parameters are entered from the high-order bits and are shifted towards the low-order bits (to the right). When the results of a new observation are received, the old results are lost.

Correct data counter(peer.valid) - an integer counter indicating valid samples remaining in the filter register. It is used to determine the availability status and to control the increase and decrease of the message distribution period.

Bias(peer.offset ) - number with fixed point signed, indicating the value of the offset of the partner's clock relative to the local clock in seconds.

Delay(peer.delay) - number s fixed point signed, indicating the total round-trip delay (RTT) of the peer's clock relative to the local clock, taking into account the message propagation and network response time in seconds. Note that the variable can take on either a positive or negative value depending on the accuracy of the clock and the accumulated offset error.

Dispersion(peer. dispersion) - number s fixed point, indicating the maximum peer clock error relative to the local clock, taking into account network latency in seconds. Only values ​​greater than zero are allowed.

Options

The following describes the parameters for all implementations running on the Internet. It is necessary to agree on the values ​​of these parameters in order to eliminate unnecessary redundancy and stabilize partner associations. The given parameters apply to all associations.

Version number ( ntp.version) - current NTP version number (3).

Port NTP ( ntp.port) - standard room port (123), assigned to the NTP protocol.

Maximum layer number ( ntp.maxstratum) - the maximum layer number that can be used when encoding a batch variable. This parameter is usually interpreted as a definition of infinity (unreachable by the subnet routing protocol).

Maximum watch age ( ntp.maxage) - the maximum interval in seconds during which the reference clock will be considered correct after the last reconciliation.

Maximum failure ( ntp.maxskew) - maximum offset error associated with local clock failure during ntp .maxage time, in seconds. The ratio of ntp .maxskew to ntp .maxage is interpreted as the maximum failure caused by the totality of factors.

Maximum distance ( ntp.maxdistance) - the maximum allowable distance between partners when synchronizing using a selection algorithm.

Minimum mailing period ( ntp.minpoll) - the minimum mailing period acceptable for any of the partners on the Internet. This period is expressed in seconds and is a power of 2.

Maximum mailing period ( ntp.maxpoll) - the maximum mailing period allowed for any of the partners on the Internet. This period is expressed in seconds and is a power of 2.

Minimum Favorite Hours ( ntp.minclock) - the minimum number of partners required for synchronization (when using a selection algorithm).

Maximum favorite hours> ( ntp.maxclock) - the maximum number of partners required to organize selection (when using a selection algorithm).

Minimum variance ( ntp.mindisperse) - the minimum value of the variance increment for each layer in seconds (when using the filtering algorithm).

Maximum variance ( ntp.maxdisperse) - maximum variance in seconds taking into account lost data (using a filtering algorithm).

Availability register size ( ntp.window) - size of the reach register (peer.reach) in bits.

Filter size ( ntp.shift) - size shift register clock filter (peer.filter) in cascades.

Filter weight ( ntp.filter) - And broadcast:

Symmetrically active (1). A computer operating in this mode periodically sends messages regardless of the reachability or layer of its partner. When operating in this mode, the computer notifies of its intention to synchronize and be synchronized by the partner.

Symmetrically passive (2). This type of association is initially created upon the arrival of a message from a peer operating in symmetrically active mode. It persists as long as the partner is reachable and operates in a layer lower than or equal to the given computer. Otherwise, the association disintegrates. However, the association will exist until at least one message is sent as a response. When operating in this mode, the computer notifies of its intention to synchronize and be synchronized by the partner.

a time server that operates in a broadcast environment) notifies that it intends to synchronize all partners.

A computer running in client mode sometimes sends an NTP message to a computer running in server mode, for example, immediately after a reboot and periodically thereafter. The server responds by changing addresses and port numbers, entering the necessary information and sending a message back to the client. Servers do not have to store any status information between client requests, while clients can vary the intervals between NTP messages to suit local requirements. In these modes, the protocol engine described in this article can be significantly simplified without noticeable loss of accuracy or reliability, especially when operating in high-speed environments. local network.

In symmetric modes, the difference between client and server practically disappears. Symmetrically passive mode is intended for use by temporary servers operating near the base nodes (lower layer) of the synchronization subnet and with a relatively large number of partners. In this mode, peer identification is not required in advance, since the association with its state variables is created only when an NTP message is received. Moreover, the stored state can be used later when the peer becomes unreachable or operates at a higher level and is therefore unsuitable as a synchronization source.

Symmetrically active mode is intended for use by time servers operating close to end nodes (highest the layer association, if it existed, will be eliminated due to the unreachability of the partner.

Broadcast mode is designed to work in high-speed local networks with a large number of workstations, where high accuracy is not required. In a typical scenario, one or more LAN timing servers periodically send broadcast messages to workstations, which then determine the timing based on a predefined propagation delay on the order of a few milliseconds.

Event Handling

Significant events from the point of view of the NTP protocol occur when the peer timers (peer. timer), one of which is targeted specifically at a given peer in an active association, expire, as well as when an NTP message is received from various peers. The event may occur as a result of an operator command or a detected error, such as a primary reference failure.

Good afternoon, guests and regular readers. I am gradually moving from the basics to a more in-depth study of Linux. Today I want to consider operation of the ntp protocol, as well as setting time server on Linux(ntp server). So, let's start with the theory.

NTP protocol

Network Time Protocol (NTP) - network protocol to synchronize the computer's internal clock using networks with variable latency (read "width"/quality of the channel).

NTP is used for its work UDP protocol and port 123.

Current protocol version - NTP 4. NTP uses a hierarchical system "hourly levels"(they are also called Stratum). Level 0 (or Stratum 0)- these are usually devices that are atomic clocks (molecular, quantum), GPS watch or clock radio. Device data is usually not published in worldwide network, and connect directly to level 1 time servers via the RS-232 protocol (indicated by yellow arrows in the illustration). Level 1 synchronized with high-precision clock level 0, usually work as sources for servers level 2. Level 2 synchronized with one of the machines level 1, and synchronization with servers of your level is also possible. Level 3 works similarly to the second one. Typically, servers of levels two and below are published on the network. NTP protocol supports up to 256 levels. I would also like to note that servers of levels 1 and 2, and sometimes even 3, are not always open to public access. Sometimes, in order to synchronize with them, you need to send a request by mail to domain administrators.

Why is there a restriction on access to servers? With the transition to each level, the error relative to the primary server increases slightly, but increases total number servers and therefore .

Assigning an NTP server on the local network

Why might we need an NTP server? For example, there are services in operating systems ah, which may depend on synchronized time. The most prominent example of such services is the Kerberos authentication protocol. For it to work, it is necessary that on computers accessed using this protocol, the system time differs by no more than 5 minutes. In addition, accurate time on all computers greatly facilitates the analysis of security logs when investigating incidents on the local network.

NTP server/client operating modes

Client/server

This mode is by far the most commonly used on the Internet. The work scheme is classic. The client sends a request, to which the server sends a response within some time. The client is configured using the server directive in the configuration file, where the DNS name of the time server is specified.

Symmetrical active/passive mode

This mode is used if time synchronization is performed between a large number of peer machines. In addition to the fact that each machine synchronizes with an external source, it also synchronizes with its neighbors (peers), acting as a client and time server for them. So even if a machine "loses" an external source, it will still be able to obtain accurate time from its neighbors. Neighbors can work in two modes – active and passive. Working in active mode, the machine itself transmits its time to all neighboring machines listed in the peers section of the ntp.conf configuration file. If neighbors are not indicated in this section, then the machine is considered to be operating in passive mode. To prevent an attacker from compromising other machines by posing as an active source, authentication must be used.

Broadcast Mode

This mode is recommended for use in cases where a small number of servers serve a large number of clients. When operating in this mode, the server periodically sends packets using the subnet's broadcast address. A client configured to synchronize in this manner receives the server's broadcast packet and synchronizes with the server. A feature of this mode is that time is delivered within one subnet (limiting broadcast packets). In addition, authentication must be used to protect against attackers.

Multicast mode

This mode is in many ways similar to broadcast. The difference is that multicast addresses of class D networks of the IP address space are used to deliver packets. For clients and servers, the address of the multicast group is specified, which they use for time synchronization. This makes it possible to synchronize groups of machines located in different subnets, provided that the routers connecting them support the IGMP protocol and are configured to transmit multicast traffic.

Manycast mode

This mode is an innovation in the fourth version of the NTP protocol. It involves the client searching for manycast servers among its network neighbors, receiving time samples from each of them (using cryptography) and selecting, based on this data, the three “best” manycast servers with which the client will synchronize. If one of the servers fails, the client automatically updates its list.

To transmit time samples, clients and servers operating in multicast mode use multicast group addresses (class D networks). Clients and servers using the same address form the same association. The number of associations is determined by the number of multicast addresses used.

Time in Linux

I’ll briefly tell you what time exists in Linux and how to set it. In Linux, as in other OS, there are 2 times. The first - hardware , sometimes called Real Time Clock, abbreviated ( RTC) (aka BIOS clock) they are usually associated with an oscillating quartz crystal that is accurate to several seconds per day. Accuracy depends on various fluctuations such as ambient temperature. The second clock is internal program clock , which occur continuously, including during interruptions in system operation. They are subject to variations due to heavy system load and interrupt latency. However, the system typically reads the hardware clock at boot and then uses the system clock.

Operating system date and time set at boot based on value hardware clock, as well as time zone settings. Time zone settings are taken from the file /etc/localtime. This file is a link (but more often a copy) of one of the files in the directory structure /usr/share/zoneinfo/.

Linux hardware clocks can store time in the format UTC(analogous to GMT), or the current territorial time. General recommendation what time to set (?) is as follows: if several operating systems are installed on the computer and one of them is Windows, then you need to use the current time (since Windows takes the time from the BIOS/CMOS and considers it local). If only operating ones are used UNIX systems family, it is advisable to store the time in the BIOS in UTC format.

Once the operating system boots, the operating system clock and BIOS clock are completely independent. The system kernel synchronizes the system clock with the hardware clock every 11 seconds.

After some time, there may be a difference of several seconds between the hardware and software clocks. What kind of watches contain right time? Neither one nor the other until we set it up time synchronization.

Note:

The Linux kernel always stores and calculates time as the number of seconds since midnight 1st January 1970 year, regardless of whether your clock is set to local or universal time. Conversion to local time is done during the request process.

Since the number of seconds since January 1, 1970 UTC is stored as a signed 32-bit integer (this is true on Linux/Intel systems), your clock will stop working sometime in 2038. Linux doesn't have a year 2000 problem, but it does have a year 2038 problem. Fortunately, by then all Linux systems will be running on 64-bit systems. A 64-bit integer will contain our clock until approximately the 292271-millionth year.

NTP Server Linux

Introduction

There are many implementations for time synchronization for Linux OS. The most famous are Xntpd (NTP version 3), ntpd (NTP version 4), Crony and ClockSpeed. In our example we will use the ntpd server.

The ntpd daemon is both a time server and a client, depending on the settings of the configuration file /etc/ntpd.conf (sometimes /etc/ntp.conf), the daemon can “receive” time from remote servers and “distribute” time to other hosts.

General time synchronization circuit on the local network is as follows: you need to have 1 or 2 servers with access to the global network, which will receive time from the Internet. All computers on the local network are synchronized with the specified servers that receive time from the Internet.

Installing ntpd

Actually, installing the daemon boils down to installing the following packages: ntp(package including the daemon itself), ntpdate(the utility for manual time synchronization is outdated), ntp-doc(package documentation), in some distributions you will need to install the same ntp-utils(diagnostic utilities), in some they are included in the ntp package. I described how to install programs on Linux in. After installing the package, in most distributions, the daemon will already be configured as an ntp client (for example, this was the case in Debian). Accordingly, the main configuration files were automatically created: /etc/ntp.conf and /var/lib/ntp/ntp.drift and the daemon was automatically launched.

Before setting up the daemon to synchronize with the outside world, I would recommend setting the current system date to a value as close to real time as possible. Setting the date in Linux produced by the command: date MMDDhhmmCCYY.ss, where MM - month, DD - day of the month, hh - hours, mm - minutes, CCYY - 4 digits of the year, ss - seconds. At the same time, the values CCYY.ss it is not necessary to indicate.

As you can see, the specified command will set the current date and time to December 27, 2010, 20:06:30. date command without parameters, display the current system time. This command has a bunch of parameters, which can be found in man date.

It is also necessary to correctly configure the hardware clock and time zone. As mentioned above, the time zone is configured by copying the required zone file from the directory /usr/share/zoneinfo/ to file /etc/localtime:

Ntp-server:~# cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime

Hardware I set the clock to UTC:

# cat /etc/sysconfig/clock | grep UTC # UTC=true indicates that the clock is set to UTC; UTC=true ntp2-server:~# cat /etc/default/rcS | grep UTC UTC=yes

The first example specifies a configuration file that defines the use of UTC for RH, the second for Deb distributions.

In addition to setting the settings to use UTC time, you must specify hardware time. (in most cases this is not necessary, because the specified system time is inevitably synchronized with the hardware, by the kernel). But still, if you have the desire to do it... hwclock command reads and sets the hardware clock based on the parameters passed to it. Available options are described in the command's manual page. Here are some examples of using hwclock:

Ntp-server# hwclock # reads time from hardware clock ntp-server# hwclock --systohc --utc # sets hardware clock time to # UTC based on system time ntp-server# hwclock --systohc # sets hardware clock time # to local time based on the system time ntp-server# hwclock --set --date "22 Mar 2002 13:17" # sets the hardware clock time # to the specified string

Another option for changing the time in the hardware clock is to access the BIOS when the system boots. Since OS time is independent of the hardware clock, any changes to the BIOS will be taken into account the next time you boot.

Now that we have everything prepared and installed, let's proceed to setting.

Managing the ntpd daemon

Control ntpd daemon no different from controlling any other demons. Start or restart the ntpd service:

#/etc/init.d/ntp start #/etc/init.d/ntp restart

Stop:

#/etc/init.d/ntp stop

#/bin/kill `cat /var/run/ntpd.pid`

The daemon has the following launch parameters:

P - PID file,
-g - allow transition to big time jump
-c - config file
-q - force manual synchronization

Setting up the ntpd server

First of all, I advise you to change the daemon launch parameters in the following configuration file:

Ntp-server:~# cat /etc/default/ntp NTPD_OPTS="-g"

# cat /etc/sysconfig/ntpd # Parameters for NTP daemon. # See ntpd(8) for more details. .... # Specifies additional parameters for ntpd. NTPD_ARGS="-g"

This parameter will allow you to synchronize the clock, even if there is a very large time difference.

So, as I said, the configuration information ntpd daemon is in the file /etc/ntp.conf. The file syntax is standard, as in many other configs: empty lines and lines starting with the "#" character are ignored. Here's a simple example:

Ntp-server:~# cat /etc/ntp.conf server ntplocal.example.com prefer server timeserver.example.org server ntp2a.example.net driftfile /var/db/ntp.drift

Parameter server specifies which servers will be used for synchronization, one on each line. If server is given with argument prefer, How ntplocal.example.com, then this server is given preference over the others. The response from the preferred server will be discarded if it differs significantly from the responses of other servers, otherwise it will be used without regard to other responses. Argument prefer Typically used for NTP servers that are known to be very accurate, such as those that use dedicated precision time equipment.

Parameter driftfile specifies the file that is used to store the system clock frequency offset. As far as I understand, this file permanently stores some value, which is formed based on the analysis of past time adjustments, and if external time sources become unavailable, then the time adjustment occurs according to the value from the file drift. It must not be modified by any other processes. And before indicating this file in the configuration - the file must be created.

By default, the NTP server will be accessible to all hosts on the Internet. Parameter restrict in the file /etc/ntp.conf allows you to control which machines can access your server. If you want prevent all machines from accessing your NTP server, add the following line to the file /etc/ntp.conf:

restrict default ignore

If you want allow sync your clock with your server only machines on your network, But prohibit them configure the server or be equal participants in time synchronization, then instead of the above, add the line:

restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

where 192.168.1.0 is the IP address of your network, and 255.255.255.0 is its netmask. /etc/ntp.conf may contain several restrict directives.

For correct and more accurate operation of the daemon, it is advisable to select servers of the level - from stratum 2 (you can, of course, stratum1, but you will have to waste time searching for such a server) and from the selected stratum 2 those to which there is a minimum “distance”. Typically, such servers may be provided by your ISP. The number of selected servers is desirable - more than 2-3, the more the better, but within reasonable limits. If you are too lazy to choose the best servers, then you can take the list open servers second level from here: http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers.

Selecting a list of reference NTP servers

We go to the specified address (http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers) and select a list of initial servers. From of this list we select servers that meet our requirements by analyzing the command output ntpdate. When executing the command, the following syntax is used:

ntpdate parameters servers_separated by_space

To ensure that our query does not make changes to the system, we must use the -q parameter, which specifies the use of the query without making changes. It is also possible to use the -d switch, indicating that the command will be executed in debug mode, with the output of additional information, without making real changes (with this switch, a bunch of other garbage is displayed :), which we do not need at the moment). Other parameters can be found in man 8 ntpdate. From the specified link, I selected all Open Access servers located in Russia (RU) + the one provided by the provider and ran the command, it turned out something like this:

Ntp-server:~# ntpdate -q ntp2.ntp-servers.net ntp1.vniiftri.ru ntp2.vniiftri.ru ntp4.vniiftri.ru ntp0.ntp-servers.net ntp1.ntp-servers.net ntp3.vniiftri.ru ntp.corbina.net server 88.147.255.85, stratum 1, offset 0.006494, delay 0.09918 server 62.117.76.142, stratum 1, offset 0.002552, delay 0.06920 server 62.117.76.141, stratum 1, offset 0.0031 47, delay 0.06918 server 62.117.76.140, stratum 1, offset 0.004823, delay 0.07350 server 88.147.254.228, stratum 1, offset -0.002355, delay 0.12030 server 88.147.254.229, stratum 1, offset -0.000922, delay 0.10577 server 62.117.76.13 8, stratum 1, offset 0.005331, delay 0.07401 server 195.14 .40.141, stratum 2, offset 0.002846, delay 0.07188 13 Jan 19:14:09 ntpdate: adjust time server 62.117.76.141 offset 0.003147 sec

In the example, our servers successfully issued the stratum1 level, which is good news (except for the provider’s server), offset is the time difference with this server in seconds, delay is the synchronization delay in seconds. Usually, b ABOUT Greater accuracy is obtained when using servers that have low latency in transmitting packets over the network. To identify this, you can use . Accordingly, first selecting those with shorter response times, and of these, those with fewer hops to reach. In order not to waste time, I will use all the specified servers and enter them into the configuration file. In total, knowing all of the above, I will describe my resulting file /etc/ntp.conf:

Ntp-server:~# cat /etc/ntp.conf # Local network servers (commented out, not used - there is one server on the network) #server 192.168.0.2 #server 192.168.0.5 # Internet servers server ntp2.ntp-servers.net server ntp1.vniiftri.ru server ntp2.vniiftri.ru server ntp4.vniiftri.ru server ntp0.ntp-servers.net server ntp1.ntp-servers.net server ntp3.vniiftri.ru server ntp.corbina.net # Server files driftfile /var/lib/ntp/ntp.drift logfile /var/log/ntpstats # restricting access to the server: # by default we ignore everything restrict default ignore # localhost without parameters - that means everything is allowed. The parameters only apply to prohibitions. restrict 127.0.0.1 # The following describes the servers with which we synchronize on the local network. # We allow them everything except traps and requests to us restrict 192.168.0.2 noquery notrap restrict 192.168.0.5 noquery notrap # for local we also allow everything except traps and modifications restrict 192.168.0.1 mask 255.255.255.0 nomodify notrap nopeer # allow external time sources access: restrict ntp2.ntp-servers.net restrict ntp1.vniiftri.ru restrict ntp2.vniiftri.ru restrict ntp4.vniiftri.ru restrict ntp0.ntp-servers.net restrict ntp1.ntp-servers.net restrict ntp3.vniiftri.ru restrict ntp.corbina.net # and this is a hack that sets the trust level of the server (strata) to itself equal to 3 # in a nutshell, the higher the level, the lower the number. 0 is the atomic clock, #1 is synchronized with it, 2 is with the first one, and so on. server 127.127.1.1 fudge 127.127.1.1 stratum 3

For a more in-depth understanding and configuration of the server, I will describe some ntpd configuration parameters that I did not mention::

  • enable/disable auth/monitor/pll/pps/stats - turn on/off operating mode:
    • auth- communicate with unmentioned neighbors only in authentication mode;
    • monitor- allow monitoring of requests;
    • pll- allow setting the local clock frequency via NTP;
    • stats- allow statistics collection;
  • statisticsloopstats- with each modification of the local clock, writes a line to a file loopstats;
  • statisticspeerstats- every communication with a neighbor is recorded in a log stored in a file peerstats;
  • statisticsclockstats- every message from the local clock driver is written to a log stored in a file clockstats;
  • statsdir(catalog_name_with_statistics)- specifies the name of the directory in which files with server statistics will be located;
  • filegen - defines an algorithm for generating file names, which consist of:
    • prefix- constant part of the file name, set either during compilation or by special configuration commands;
    • file name- added to the prefix without a slash, two dots are prohibited, can be changed with the file key;
    • suffix- generated depending on typename;
  • restrictnumeric-address- sets access restrictions: packets are sorted and masked, the source address is taken and compared sequentially, a flag is taken from the last successful comparison access:
    • no flags- give access;
    • ignore- ignore all packets;
    • noquery- ignore NTP 6 and 7 packets (request and state modification);
    • nomodify- ignore NTP 6 and 7 packets (state modification);
    • limited- serve only a limited number of clients from a given network;
    • nopeer- serve the host, but not synchronize with it;
  • clientlimitlimit- for the flag limited determines the maximum number of clients served (by default 3);

So, we got ntpd-server, which synchronizes with the outside world, allows you to receive time for clients from the local network 192.168.0.1 with a mask of 255.255.255.0, and can also be synchronized with the local server (if you uncomment a few lines). All we have to do is set up clients and learn how to monitor our server.

Monitoring the ntpd server and synchronization

Once you have everything set up. NTP will keep the time in sync. This process can be observed using the NTP Query (ntpq) command:

Ntp-server:~# ntpq -p remote refid st t when poll reach delay offset jitter =============================== ============================================================== -n3. time1.d6.hsd.PPS. 1 u 34 64 177 70.162 2.375 8.618 +ntp1.vniiftri.r .PPS. 1 u 33 64 177 43.479 -0.020 10.198 *ntp2.vniiftri.r .PPS. 1 u 6 64 177 43.616 -0.192 0.688 +ntp4.vniiftri.r .PPS. 1 u 4 64 177 43.623 0.440 0.546 -n1.time1.d6.hsd .PPS. 1 u 53 64 77 92.865 -11.358 38.346 -ns1.hsdn.org .GPS. 1 u 40 64 177 78.057 -3.292 35.083 -ntp3.vniiftri.r .PPS. 1 u 44 64 77 47.667 2.292 2.611 -scylla-l0.msk.c 192.43.244.18 2 u 62 64 77 41.565 -1.564 28.914

This command with the -p switch prints to standard output a list of time sources with their characteristics (the remaining command parameters are in man ntpq). The meaning of each column is as follows:

The name of the remote NTP server. If you specify the -n switch, you will get server IP addresses instead of names.

Indicates where each server is currently getting its time from. This could be a hostname or something like .GPS. indicating the source global system positioning (Global Positioning System).

Stratum (level) is a number from 1 to 16 indicating the accuracy of the server. One means maximum accuracy, 16 means the server is unavailable. Your level will be equal to the level of the least accurate remote server plus 1.

Interval between polls (in seconds). The value will change between the minimum and maximum polling rates. At the beginning, the interval will be small so that synchronization occurs quickly. Once the clocks are synchronized, the interval begins to increase to reduce traffic and load on popular time servers.

An octal representation of an 8-bit array reflecting the results of the last eight attempts to connect to the server. The bit is set if the remote server responded.

The amount of time (in seconds) required to receive an answer to the query “what time is it?”

The most important field. Difference between local and remote server time. As synchronization progresses, this value should decrease (closer to zero), indicating that the local machine's clock is becoming more accurate.

Dispersion (Jitter) is a measure of statistical deviations from the offset value (offset field) over several successful request-response pairs. A lower dispersion value is preferable because it allows for more accurate time synchronization.

Meaning of characters before server names

x - fake source according to the intersection algorithm;
. - excluded from the list of candidates due to long distance;
- - removed from the list of candidates by the clustering algorithm;
+ - included in the final list of candidates;
# - selected for synchronization, but there are 6 best candidates;
* - selected for synchronization;
o - selected for synchronization, but PPS is used;
space - too large a level, a loop or an obvious error;

ntpd service“smart” and itself weeds out sources of time that are too outside the bounds of reason. Some time after starting, ntpd will select the most reliable data sources and will synchronize with them. The list of reference NTP servers we present is regularly reviewed by the service.

You can check the possibility of synchronization locally on the server with the command:

Ntp-server:~# ntpdate -q localhost server 127.0.0.1, stratum 2, offset -0.000053, delay 0.02573 server::1, stratum 2, offset -0.000048, delay 0.02571 14 Jan 14:49:57 ntpdate: adjust time server ::1 offset -0.000048 sec

From the command output it is clear that our server has already become stratum 2. To achieve this level, it takes some time. Perhaps in the first 10-15 minutes the server level will be higher.

The correct operation of the ntp server can also be judged from the logs of the ntpd daemon:

Ntp-server:~# cat /var/log/ntpstats/ntp 13 Jan 20:13:16 ntpd: Listening on interface #5 eth0, fe80::a00:27ff:fec1:8059#123 Enabled 13 Jan 20:13: 16 ntpd: Listening on interface #6 eth0, 192.168.0.8#123 Enabled 14 Jan 14:31:00 ntpd: synchronized to 62.117.76.142, stratum 1 14 Jan 14:31:10 ntpd: time reset +10.291312 s 14 Jan 14 :31:10 ntpd: kernel time sync status change 0001 14 Jan 14:34:31 ntpd: synchronized to 88.147.255.85, stratum 1 14 Jan 14:36:04 ntpd: synchronized to 62.117.76.141, stratum 1 14 Jan 15: 04:36 ntpd: synchronized to 62.117.76.142, stratum 1 14 Jan 15:10:58 ntpd: synchronized to 62.117.76.140, stratum 1 14 Jan 15:17:54 ntpd: no servers reachable 14 Jan 15:31:49 ntpd : synchronized to 62.117.76.140, stratum 1 14 Jan 15:32:14 ntpd: time reset +13.139105 s

Setting up netfilter (iptables) for an NTP server

Having configured the server, it would be a good idea to protect it. We know that the server runs on port 123/udp, and requests are also sent from port 123/udp. After reading the article and familiarizing yourself with the practical ones, you can create rules for filtering network traffic:

Ntp ~ # iptables-save # typical iptables rules for DNS *filter:INPUT DROP :FORWARD DROP :OUTPUT DROP -A INPUT -i lo -j ACCEPT -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A INPUT -m conntrack --ctstate INVALID -j DROP # allow local network access to the NTP server: -A INPUT -s 192.168.1.1/24 -d 192.168.1.1/32 -p udp -m udp --dport 123 -m conntrack - -ctstate NEW -j ACCEPT -A OUTPUT -o lo -j ACCEPT -A OUTPUT -p icmp -j ACCEPT -A OUTPUT -p udp -m udp --sport 32768:61000 -j ACCEPT -A OUTPUT -p tcp -m tcp --sport 32768:61000 -j ACCEPT -A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT # allow NTP server access to make outgoing requests -A OUTPUT -p udp -m udp --sport 123 --dport 123 -m conntrack --ctstate NEW -j ACCEPT COMMIT

This is a typical example! To set iptables rules for your tasks and network configuration, you need to understand how netfilter works in Linux by reading the above articles.

Setting up client machines

To synchronize time on UNIX machines local network, it is advisable to use the ntpdate utility, running it several times a day, for example, every hour. To do this, you need to add the following line:

0 * * * * /usr/sbin/ntpdate -s

The -s switch directs the output of the command. If client machines have a couple of extra megabytes of RAM, then you can run the ntpd daemon, just like on the server with the following config:

Server restrict default ignore restrict noquery notrap restrict 127.0.0.1 nomodify notrap

I think everything is clear in this config: the time source (server) is a local ntpd server, deny access to everyone, allow only the local ntpd server.

Also, on clients it is necessary to correctly specify in which format to store time and select the correct time zone.

To configure the Windows NTP client, you need to run the following commands in the console:

C:\>net time /setsntp: The command completed successfully. C:\>net stop w32time The Windows Time service is stopping. The Windows Time service was stopped successfully. C:\>net start w32time The Windows Time service is starting. The Windows Time service was started successfully. C:\>net time /querysntp The current SNTP value is: The command completed successfully.

Conclusion

Well, that's it! The volume of the article turned out to be enormous... I didn’t even expect it. Let me summarize the above. In this article, I hope it became clear to us what is and how an NTP server works. Learned how to configure a server and clients on UNIX and Windows machines. In a few words, the structure of time synchronization in a local network is as follows: There are 1.2 or more time servers in the local network, they synchronize their time with external sources in global network. Server and client settings are based on the files /etc/ntp.conf (the main configuration file of the ntpd daemon), /etc/localtime (the current time zone file), as well as /etc/sysconfig/ntp (for RH) and /etc/default /ntp (for Deb) - daemon launch parameter files. For a local ntp server, the configuration file specifies external servers for obtaining time and allows access for these servers using the restrict parameter, as well as for local network computers, for clients the time source is specified - local servers on the local network, and also prohibits access for everyone except the time source on the local network. All. Thank you all for your attention! I will be glad to comments!

  • (article archive) describes how to connect GPS to the server to organize your own Stratum1 level exact time server.
  • describes how to configure authorization on an ntp server.

Answers to questions

26.09.2018

It is difficult to imagine the modern world without precise time. In many areas of life it is necessary to have very accurate clocks, and the accuracy must often be much higher than the accuracy of the clocks people use in everyday life. For example, requirements for the accuracy of the clocks of aviation control rooms, complexes, control spacecraft, or military systems are at the highest level. Also, high-precision clocks are also needed in systems with simpler functions - in billing and tariff systems mobile operators and Internet providers, in banking transaction systems, in exchange systems, in industrial and scientific complexes. On local networks, the Kerberos user authentication protocol also uses a comparison of the domain controller's time with the clock of user workstations. In computer networks, synchronization is usually performed with exact time servers using the protocol NTP or its “light” version - SNTP. In this article we will look at the features, differences and examples of application of these protocols.

NTP(English) Network Time Protocol– Network Time Protocol) – a network protocol for synchronizing a computer’s internal clock using networks with variable bandwidth. Provides high accuracy of time synchronization thanks to a special algorithm that allows you to select the most accurate sources to estimate the exact time. This algorithm allows you to minimize the impact of data from obviously incorrectly configured NTP servers on common system. The NTP protocol provides synchronization mechanisms with nanosecond precision, and contains facilities for characterizing and error estimating the local clock and the time server that performs the synchronization. The NTP protocol uses a hierarchical system of levels, or stratums. An NTP server is at the highest level (stratum 1) if it receives data directly from an accurate time source. Servers that synchronize their clocks with the stratum 1 server are on the level below (stratum 2), etc.

SNTP(English) Simple Network Time Protocol– simple network time protocol) – time synchronization protocol computer network. It is a simplified implementation of the NTP protocol; it lacks the complexity of the NTP algorithm. SNTP is used for network hosts that do not require full NTP functionality. A common practice is to synchronize the clocks of several nodes on a local network with other NTP nodes over the Internet and use these nodes to time synchronize services provided to other clients over the local network. This use case does not require high precision time synchronization. The SNTP protocol provides synchronization mechanisms with an accuracy of 1 to 50 ms

An example of using the NTP protocol: Bank N provides its clients with client-server application for stock trading. Servers that process information about stock quotes must have a clock with high precision synchronization with the universal time scale. In this case, each exchange trading server of bank N is synchronized with the most accurate of the exact time servers (“stratum 1”), which receives data directly from the exact time source. The most accurate server is selected using an algorithm built into the NTP protocol. An approximate architecture of such a solution is shown in the diagram below:

A classic example of using SNTP is time synchronization within a domain. The domain controller receives time from the global Internet from the public servers of Stratum 1 or Stratum 2. The remaining clients of the domain synchronize their clocks with the time on the domain controller. An approximate architecture is shown in the diagram.

MSK-IX NTP Server is a public time server supported by MSK-IX. The exact time server is designed to synchronize the internal clocks of computers and network equipment (servers, routers, smartphones, etc.) with the reference source using the NTP protocol.

MSK-IX NTP server belongs to the highest level of accuracy (Stratum One Time Servers) in the hierarchical system of time levels. The signal from the global satellite navigation systems GLONASS (priority) and GPS is used as a reference time signal.

MSK-IX NTP Server is implemented as a grouping of servers located in Moscow, St. Petersburg, Yekaterinburg and Novosibirsk. The use of anycast network technology ensures high reliability and fast response of the system throughout the country.

MSK-IX servers are also included in the international pool of NTP servers POOL.NTP.ORG, widely used in operating system settings.

How to start using the NTP Server service?

Use the following parameters when configuring your hardware:

Server name ntp.msk-ix.ru
IPv4 address 194.190.168.1
IPv6 address 2001:6d0:ffd4::1

How to establish peering with the MSK-IX NTP server network?

To shorten the network route to the MSK-IX NTP server, use the Route Server service or establish direct peering with the MSK-IX DNS Cloud network. Peer-to-peer interaction is established upon an additional application within the framework of the contract for connection to MSK-IX without additional payment.

NTP(Network Time Protocol) is a network protocol for synchronizing a computer's internal clock using networks with variable latency. The protocol was developed by David L. Mills, a professor at the University of Delaware, in 1985. The version for 2015 is NTPv4.

NTP, based on the Marzullo algorithm, uses the UDP protocol for its operation and takes into account transmission time. The NTP system is extremely resistant to changes in transmission media latency. In version 4 it is capable of achieving an accuracy of 10 ms (1/100 s) when working over the Internet, and up to 0.2 ms (1/5000 s) and better within local networks.

The NTP protocol is most widely used for synchronizing time servers. To achieve maximum accuracy it is preferable permanent job software NTP mode system service. In the operating room family Microsoft systems Windows is the W32Time service, Linux is the Ntpd service.

A simpler implementation of this algorithm is known as SNTP - Simple Network Time Protocol. Used in embedded systems and devices that do not require high precision, as well as in custom time programs.

Package structure

The packet structure is described in RFC 5905. The packet consists of an integer number of 32-bit words.

The header information will differ for different operating modes. For example, a client in the fields hour layer, source id, start time And appointment time must write zeros.

Heading

NTP header
Indentation Octet 0 1 2 3
Octet Bit 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0 0 IR Version Mode Hour layer Polling interval Accuracy
4 32 Delay
8 64 Dispersion
12 96 Source ID
16 128 Update time
20 160
24 192 Start time
28 224
32 256 Appointment time
36 288
40 320 Dispatch time
44 352

Correction indicator

Example of time synchronization using NTP

Length - 2 bits, from Leap Indicator. An integer indicating the leap second warning.

Version number

Length - 3 bits, from Version Number. An integer representing the protocol version.

Mode

Length - 3 bits, from Mode. An integer representing the mode. The values ​​are presented in the table below.

Hour layer

Length - 8 bits, from Stratum. An integer representing the hour layer.

Polling interval

Length - 8 bits, from Poll. A signed integer representing the maximum interval between consecutive messages. The value is equal to the binary logarithm of seconds. The default suggested limits for minimum and maximum surveys are 6 and 10, respectively.

Accuracy

Length - 8 bits, from Precision. A signed integer that represents the accuracy of the system clock. The value is equal to the binary logarithm of seconds. For example, a value of -18 will correspond to an accuracy of about 1 µs.

Delay

Length - 32 bits, from Root Delay. The total time of signal propagation in both directions in short NTP format.

Dispersion

Length - 32 bits, from Root Dispersion. Total variance for a time source in short NTP format.

Source ID

Length - 32 bits, from Reference ID. Synchronization source code. Depends on the value in the Hour layer field. For layer 0- These four ASCII characters, called "kiss code", are used for debugging and monitoring. See below for layer 1 are four octets of ASCII characters, padded on the left with zeros, assigned to the time reference. The table below shows the list maintained by IANA.
ID Source
GOES Geostationary satellite for environmental monitoring and surveillance system
GPS Global Positioning System
GAL Galileo positioning system
P.P.S. General radio signal with a pulse duration of 1 second
IRIG Telemetry Standardization Group, USA
WWVB Low Frequency Radio Transmitter, 60 kHz, Fort Collins, Colorado, USA
DCF Low frequency radio transmitter, 77.5 kHz, DCF77, Mainflingen, Germany
HBG Low frequency radio transmitter, 75 kHz, Prangins, Switzerland
MSF Low frequency radio transmitter, 60 kHz, Anthorn, UK
JJY Low frequency radio transmitter, 40 kHz, Fukushima, 60 kHz, Saga, Japan
LORC Medium frequency radio transmitter, 100 kHz, radio navigation, LORAN-C
TDF Medium frequency radio transmitter, 162 kHz, Allouis, France
CHU High Frequency Radio Transmitter, Ottawa, Ontario, Canada
WWV High Frequency Radio Transmitter, Fort Collins, Colorado, USA
WWVH High frequency radio transmitter, Kauai, Hawaii, USA
NIST
ACTS NIST telephone modem
USNO US National Observatory telephone modem
PTB Telephone modem of the National Metrological Institute of Germany
For layers 2 and above is the server identifier and can be used to capture time loops. If IPv4 is used, the identifier is four octets of the IP address. If IPv6 is used, then these are the first four octets of the MD5 hash of the address. It is worth noting that when using IPv6 addresses for a server with NTPv4 and a client with NTPv3, the identifier may take on a random value, which is why time loops may not be recorded.

Update time

Length - 64 bits, from Reference Timestamp. The time when the system last set or adjusted the time. NTP format.

Start time

Length - 64 bits, from Origin Timestamp. The client time when the request is sent to the server. NTP format.

Appointment time

Length - 64 bits, from Receive Timestamp. Server time when the request comes from the client. NTP format.

Dispatch time

Length - 64 bits, from Transmit Timestamp. The server time when the request is sent to the client. NTP format.

NTP message "Kiss-o"-Death"

For layer 0, which is considered undefined or invalid, field Source ID can be used to deliver messages that serve as system state information and access control. Such messages are called "Kiss-o"-Death" (KoD), and the ASCII data they deliver are called "kiss codes". A list of currently accepted "help" codes is presented in the table below.

Recipients of KoD messages are required to check them and perform the following actions:

  • When receiving code combinations DENY And RSTR the client is obliged to break virtual connections with this time server and stop sending messages to this server.
  • Upon receiving the code combination RATE the client must immediately reduce its polling interval for this server and continue to reduce it each time it receives this code combination.
  • When receiving a code combination starting with an ASCII character X, intended for experimental research and subsequent improvements, it should be ignored if it is not recognized.
  • All other code combinations and KoD messages not defined by this protocol are destroyed after verification.
Help codes
Code Description
ACST Virtual connection established by unicast server
AUTH Server authentication failed
AUTO Autokey sequence is incorrect
BCST Virtual connection established by broadcast server
CRYP Cryptographic authentication or identification failed
DENY The remote server denied access
DROP Loss of a remote time server in symmetric mode
RSTR Access denied due to local security policy
INIT The virtual connection was not established the first time
MCST Virtual synchronization connection established by dynamically discovered server
NKEY The key was not found (either it has never been loaded before, or it is unreliable)
RATE The speed is exceeded. The server has temporarily denied access because the client has exceeded the speed threshold
RMOT Changing the virtual connection from a remote IP host using the NTP protocol directly
STEP An iteration has occurred to change the system time, the virtual synchronization connection is not established

Hour layers

Yellow arrows indicate hardware connection; red arrows indicate network connection.

NTP uses a hierarchical network where each level has its own number, called a layer. Layer 1- primary servers that directly synchronize with national time services via satellite, radio or telephone modem. Layer 2- secondary servers, synchronized with primary servers, etc. Typically, NTP clients and servers with a relatively small number of clients are not synchronized with the primary servers. There are several hundred public secondary servers running on higher layers. They are the preferred choice.

Time format

Time is represented in the NTP system as a 64-bit number (8 bytes), consisting of a 32-bit second counter and a 32-bit fractional second counter, allowing time to be transmitted in the range of 2-32 seconds, with a theoretical accuracy of 2-32 seconds. Since the time scale in NTP repeats every 2 32 seconds (136 years), the recipient must at least approximately know the current time (with an accuracy of 68 years). Also note that time is measured from midnight on January 1, 1900, not 1970, so almost 70 years (including leap years) must be subtracted from NTP time to correctly match the time with Windows or Unix systems.

Regular time format
Bit 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0 Seconds
4 Fractional seconds
Date Format
Bit 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0 Era number
4 Era indentation
8 Shares
16

Close