Setting up an NTP server in Windows

Starting with Windows 2000, all Windows operating systems include a time service W32Time. This service is designed to synchronize time within an organization. W32Time is responsible for the operation of both the client and server parts of the time service, and the same computer can be both an NTP (Network Time Protocol) client and server.

By default, the Windows time service is configured as follows:

When the operating system is installed, Windows starts an NTP client and synchronizes with an external time source;
When you add a computer to a domain, the synchronization type changes. All client computers and member servers in the domain use a domain controller to synchronize time, authenticating them;
When a member server is promoted to a domain controller, an NTP server is launched on it, which uses a controller with the PDC emulator role as a time source;
The PDC emulator, located in the forest root domain, is the primary time server for the entire organization. At the same time, it is also synchronized with an external time source.

This scheme works in most cases and does not require intervention. However, the Windows time service structure may not follow a domain hierarchy, and any computer can be designated as a reliable time source. As an example, I will describe setting up an NTP server in Windows Server 2008 R2, although the procedure has not changed much since Windows 2000.

Starting an NTP server

I note right away that the time service in Windows Server (from 2000 to 2012) does not have a graphical interface and is configured either from command line, or by direct editing system registry. Personally, the second method is closer to me, so we go to the registry.

So, the first thing we need to do is start the NTP server. Open the registry branch
HKLM\System\CurrentControlSet\services\W32Time\TimeProviders\NtpServer.
Here to enable the NTP server parameter Enabled you need to set the value 1 .

Then we restart the time service with the command net stop w32time && net start w32time

After restarting the NTP service, the server is already active and can serve clients. You can verify this using the w32tm /query /configuration command. This command displays a complete list of service options. If section NtpServer contains the string Enabled:1, then everything is in order, the time server is working.

In order for the NTP server to serve clients, do not forget to open UDP port 123 on the firewall for incoming and outgoing traffic.

Basic NTP server settings

The NTP server has been enabled, now you need to configure it. Open the registry branch HKLM\System\CurrentControlSet\services\W32Time\Parameters. Here we are primarily interested in the parameter type A that specifies the type of sync. It can take the following values:

NoSync- The NTP server is not synchronized with any external time source. The clock built into the CMOS chip of the server itself is used;
NTP- The NTP server is synchronized with external time servers, which are specified in the registry setting NtpServer;
NT5DS- The NTP server synchronizes according to the domain hierarchy;
AllSync- The NTP server uses all available sources for synchronization.

The default value for a computer that is a member of a domain is NT5DS, for a stand-alone computer - NTP.

And parameter NtpServer, which specifies the NTP servers with which this server will synchronize time. By default, this parameter contains the Microsoft NTP server (time.windows.com, 0x1), if necessary, you can add several more NTP servers by entering their DNS names or IP addresses separated by a space. The list of available time servers can be viewed for example.

You can add a flag at the end of each name (ex. ,0x1) which specifies the mode to synchronize with the time server. The following values ​​are allowed:

0x1– SpecialInterval, use of a special polling interval;
0x2– UseAsFallbackOnly mode;
0x4– SymmetricActive, symmetrical active mode;
0x8– Client, sending a request in client mode.

When using the SpecialInterval flag, the interval value set in the key is required SpecialPollInterval. If the UseAsFallbackOnly flag is set, the time service is told that this server will be used as a fallback server and that other servers in the list will be contacted before synchronizing with it. Symmetric active mode is used by default by NTP servers, and client mode can be used in case of synchronization problems. You can see more about synchronization modes, or don’t fool around and just put it everywhere ,0x1(as advised by Microsoft).

Another important parameter Announce Flags located in the registry key HKLM\System\CurrentControlSet\services\W32Time\Config. It is responsible for how the NTP server declares itself and can take the following values:

0x0( Not a time server) - the server does not advertise itself through NetLogon as a time source. It can respond to NTP requests, but neighbors will not be able to recognize it as a time source;
0x1(Always time server) - the server will always announce itself regardless of the status;
0x2(Automatic time server) - the server will only announce itself if it receives reliable time from another neighbor (NTP or NT5DS);
0x4(Always reliable time server) - the server will always declare itself as a reliable time source;
0x8(Automatic reliable time server) - a domain controller is automatically declared reliable if it is a forest root domain PDC emulator. This flag allows the forest master PDC to assert itself as the authorized time source for the entire forest, even if it is not connected to the upstream NTP servers. No other controller or member server (which has the default flag 0x2) cannot claim to be a reliable source of time if it cannot find a source of time for itself.

Meaning Announce Flags is the sum of its constituent flags, for example:

10=2+8 - The NTP server declares itself as a reliable time source, provided that it receives time from a reliable source or is a root domain PDC. Flag 10 is set by default for both domain members and standalone servers.

5=1+4 - The NTP server always claims to be a reliable time source. For example, to declare a member server (not a domain controller) as a reliable time source, flag 5 is needed.

Well, let's set the interval between updates. The key already mentioned above is responsible for it. SpecialPollInterval, located in the registry key HKLM\System\CurrentControlSet\services\W32Time\TimeProviders\NtpClient. It is in seconds and defaults to 604800, which is 1 week. This is a lot, so it's worth reducing the value of SpecialPollInterval to a reasonable value, say 1 hour (3600).

After configuration, you need to update the service configuration. You can do this with the w32tm /config /update command. And a few more commands for configuring, monitoring and diagnosing the time service:

w32tm /monitor - using this option, you can find out how much the system time of this computer differs from the time on the domain controller or other computers. For example: w32tm /monitor /computers:time.nist.gov
w32tm /resync - With this command, you can force the computer to synchronize with the time server it uses.
w32tm /stripchart - shows the time difference between the current and remote computer, and can display the result in graphical form. For example, the command w32tm /stripchart /computer:time.nist.gov /samples:5 /dataonly will make 5 comparisons with the specified source and display the result in text form.

w32tm /config is core team Used to configure the NTP service. With its help, you can set the list of time servers used, the type of synchronization, and much more. For example, you can override the default values ​​and set up time synchronization with an external source using the command w32tm /config /syncfromflags:manual /manualpeerlist:time.nist.gov /update
w32tm /query - Shows the current service settings. For example, w32tm /query /source will show the current time source, and w32tm /query /configuration will show all service parameters.

Well, as a last resort 🙁
w32tm /unregister - Removes the time service from the computer.
w32tm /register - Registers the time service on the computer. In this case, the entire parameter branch in the registry is recreated.

The exact time server is designed to synchronize time-frequency indicators. The device generates frequency and time signals with high accuracy and synchronizes these parameters at remote sites.

The time synchronization server can operate using various signals and protocols, including the common NTP protocol and the more popular PTP protocol. Receiving signals from satellites of global positioning systems GPS and GLONASS, the server transmits them to client devices and synchronizes time parameters.

Description of SSV-1G

Frequency and time server "SSV-1G" is a stand-alone device 1.5 U high, installed in a 19" telecommunication rack, designed to generate frequency and time signals.

Unlike many other products on the market, the SSV-1G time server is not based on industrial servers, but uses its own hardware platform, which significantly reduces its cost, increases reliability, and eliminates dependence on the manufacturer of the operating system and server platform .

Synchronization of the exact time server is carried out from the signals of satellite radio navigation systems (SRNS) of both the Russian GLONASS and GPS, which increases the accuracy of time determination and reduces the risks of the operator's dependence on foreign navigation systems.

The 1PPS signal input, the E1/2.048 MHz input, or the 5 (10) MHz input can be used as backup clock sources for the master oscillator.

The RS232 input of the COMB module can be used as a backup source of time scale synchronization using the TOD, Sirf protocols.

The SSV-1G is powered by two inputs (Main / Backup) from independent sources AC 220 V 50Hz / DC 48 V. A delivery option is available with two DC 48 V power inputs and an additional external converter AC 220 V 50Hz - DC 48 V, which allows to supply power to the SSV-1G through one input AC 220 V 50 Hz, and through the other input DC 48 V. Power consumption depends on the configuration and does not exceed 40 W.

Maintenance of the device is simplified as much as possible. Operating personnel can receive information and control the device using the Maintenance System software, or using the control tools built into the device - a graphic indicator and a keyboard.

Specifications SSV-1G

Characteristic Meaning
General
Type of internal generator Piezoelectric thermostatted ultra-precision
External clock inputs GLONASS, GPS, Galileo, 1 PPS, Е1/2.048 MHz, 5 MHz, 10 MHz
External clock inputs GLONASS, GPS, Galileo, ToD, SIRF
Synchronization outputs NTP server, PTP master, 1 PPS, Е1/2.048 MHz, SIRF, IRIG-B, 5 MHz, 10 MHz, current loop
Control
Autonomous built-in keyboard and display
Local USB port and maintenance software
network Ethernet and Maintenance Software, SNMP v2C (RFC 1158)
network interface 10/100 Base-T Ethernet
Supported protocols
transport layer TCP, UDP
IP protocol IP v4
IP v6 (optional)
automatic configuration DHCP (RFC 2131)
NetBios Name Service (NBNS)
NTP (Network Time Protocol) NTP v2 (RFC 1119)
NTP v3 (RFC 1305)
NTP v4 (RFC 5905),
SNTP v3 (RFC 1769)
SNTP v4 (RFC 2030)
PTP (Precision Time Protocol) PTP v2 (IEEE Std 1588-2008)
SNMP protocol SNMPv2c (RFC 1158)
RS-232 protocol SIRF
TOD
Interface 1PPS (1Hz)
output level 5V (TTL compatible)
pulse duration 5 µs (IEEE Std 1344 - 1995)
pulse polarity positive/negative
line resistance 50 ohm
5 MHz and 10 MHz clock signals
waveform nominally rectangular
output signal level at a load of 50 ohms 1 V
Clock signal 2.048 MHz (G.703/10)
waveform nominally rectangular
1.5 V
1.9V
Clock signal 2.048 Mbps (G.703/6)
waveform bipolar
output signal level at a load of 75 ohms (coaxial pair) 1.5 V
output signal level at a load of 120 ohms (balanced pair) 1.9V
Metrological characteristics
limits of permissible relative error in frequency in the mode of synchronization by GNSS GLONASS/GPS signals ±5.0×10 -11
limits of permissible root-mean-square relative deviation of the random component of the measurement error of the frequency of the output signal over a measurement time interval of 100 s ±5.0×10 -11
limits of permissible absolute error of binding the leading edge of the output pulse with a frequency of 1 Hz to the UTC time scale in the synchronization mode using GNSS GLONASS/GPS signals ±110 ns
limits of permissible absolute error of binding the leading edge of the output pulse with a frequency of 1 Hz to the UTC time scale in the autonomous operation mode per day ±20 µs
limits of permissible absolute error of time scale reference relative to UTC(SU) time scale via NTP protocol via Ethernet interface ±10 µs
Number of expansion modules up to 8 pieces
Performance
NTP server speed per 10/100 Base-T Ethernet port, requests per second, not less than 123 000
Power supply
number of power inputs
2
power supply voltage
(depending on execution type)
═ 60 V (36 to 72) V
~ 220 V (from 198 to 242) 50 Hz
Power consumption no more than 50 W in the "working" mode
no more than 60 W in the "warm-up" mode
dimensions 483×255×65mm
Weight no more than 6 kg
Working mode round the clock
average service life at least 20 years

Advantages of the SSV-1G time source

    • Optimal price-quality ratio

The SSV-1G source has one of the best price-quality ratios in its equipment class. This is achieved by two technological solutions.

Firstly, the SSV-1G is built on the basis of a hardware platform of its own production. In addition, there is no third-party licensed software in the SSV-1G device.

Secondly, instead of expensive high-precision rubidium oscillators with a short service life, quartz oscillators are used with double temperature control, which ensures a constant temperature level necessary to ensure a stable operating mode. This solution is similar in accuracy to rubidium generators, but it costs significantly less and is more reliable.

    • Information Security

All SSV-1G expansion modules, including the NTP-server module, have a hardware implementation built on the basis of a rigid automaton.

This solution provides the highest performance and as a result:

  1. High accuracy of time stamp transmission due to the absence of internal delays that affect the asymmetry of the NTP packets transmission and reception channel.
  2. The impossibility of disrupting the functioning of the NTP server due to DDOS attacks. The speed of the local NTP server is higher than the speed of the Ethernet channel.
  3. The impossibility of disrupting the functioning of the NTP server due to unauthorized access to resources through the Ethernet port. The NTP time server only provides functionality and does not respond to any other IP packets.

Modular design

The base chassis of the SSV-1G source is a 19-inch case with installed control modules, a SRNS signal receiver, a thermally stabilized quartz oscillator with a phase-locked loop, and a backplane for installing functional expansion modules.

The modular design allows you to create up to 16 NTP servers on the basis of one device in physically separated networks.

Expansion modules are installed in accordance with the required configuration of input / output signals based on the specification determined at the time of order.

When changing the configuration, there is no need to buy a new device, it is enough to install an additional required number of expansion modules.

In total, up to 8 expansion modules can be installed.

Frequency and time source modules SSV-1G

MLAN module

  • Simple Network Time Protocol (RFC 1769, RFC 2030);
  • Time Protocol (RFC 868);
  • Daytime Protocol (RFC 867).

MLANP module

The module is designed to receive requests from clients and generate a packet with the exact current time according to the following protocols:

  • Network Time Protocol (RFC 1119, RFC 1305, RFC 5905);

The Precision Time Protocol (PTP) is designed for a single client connection. The operating mode is determined by any combination of the following parameters:

Transmit protocol Ethernet, UDP
addressing mode Unicast, Multicast, Mixed
two steps yes, no

When using the Network Time Protocol (NTP), it is possible to send packets to the specified IP address (including broadcast Broadcast), with the specified frequency.

The module has two independent channels with identical functionality and the same set of configuration parameters. Channels are configured individually. The load capacity of each channel is about 123,000 packets per second.

MGLAN module (NTP/PTP)

The module is designed to receive requests from clients and generate a packet with the exact current time according to the following protocols:

  • Precision Time Protocol V2 (IEEE Std 1588-2008);
  • Network Time Protocol (RFC 1119, RFC 1305, RFC 5905);
  • Simple Network Time Protocol (RFC 1769, RFC 2030).

MPPS module

The module is designed to receive a PPS signal (1Hz) and form a signal, the shape of which is set in the configuration, has two identical channels, each of which can operate in the receive or transmit mode.

Module "MSYNC 120", "MSYNC 75"

The module is designed to receive and generate 2.048 MHz (G.703/10) or 2.048 Mbps (G.703/6) signals and has two identical channels, each of which can operate in the signal reception or transmission mode.

MCOMB module

The MCOMB module is designed to receive/transmit the exact current time in the specified format via the RS-232 interface, as well as to receive and generate a 1 PPS time stamp pulse.

Supported RS-232 interface protocols: TOD; Sirf, TimeString, NMEA.

Module "M10M"

The module is designed to receive and generate 5 MHz or 10 MHz signals and has two identical channels, each of which can operate in the mode of receiving or transmitting a signal.

Module "MTP" (Current Loop)

The module is designed to generate a time stamp pulse via the "Current loop" or "Dry contact" interface and has two independent, galvanically isolated channels.

MIRIG module

The MIRIG module is designed to generate a signal according to the IRIG STANDARD 200-04 protocol specification.

Module "M422"

Module "M422" is designed to receive/transmit the exact current time in the specified format via the RS-422/485 interface, as well as receive and generate a time stamp pulse via the RS-422/485 interface.

Supported RS-422/485 interface protocols: TOD, Sirf, TimeString, NMEA.

Centralized Management

Control and management of the operation of synchronization devices installed on the operator's network can be provided by a specialized network software"Maintenance", developed by CJSC "COMSET-service".

Troubleshooting Management

  • collection of messages about accidents, malfunctions and events requiring attention from connected devices;
  • getting a list of accidents;
  • filtration of accidents with assignment of severity degree to them;
  • display of accidents and malfunctions, as well as their characteristics;
  • control of the accessibility of the control device (the presence of a communication channel between the device and the control system);
  • generation of reports on accidents and events.

Security Management

  • protection of access to the system using a username and password;
  • user authorization in the control system;
  • four levels of user rights from administrator (with full rights) to a user with read-only rights;
  • control of actions of operators on processing of malfunctions.

Configuration Management

  • adding a new device;
  • for each supported device remote display of information about the device: information on the inputs/outputs used, device configuration, device operation modes, parameters that determine the operation of the device;
  • automatic recognition serial numbers devices (inventory function).

Performance management

  • displaying the current characteristics of devices in real time.

Output and user interface

  • data on the state of network elements are displayed in a tabular form with the possibility of printing them;
  • the system has a convenient user interface, making it easy to view:
    • a list of devices, their current state and state information elements;
    • list of users, access rights granted to users;
    • current state of all device modules;
    • the state of the satellite signal receiver, the state of the satellite constellation visible at the installation point;
    • and much more.
  • “Maintenance” software has advanced tools for visualization and analysis of fault signals with the possibility of sound notification of various tones, easily customizable by the user of the system.

The time server "SSV-1G" is a proprietary development of the KOMSET-service company. It has an independent hardware platform, high timing accuracy, user-friendly interface and two power supplies: main and backup. You can buy a time synchronization server in Moscow from us in a standard or extended version. It is also possible to supply the device throughout Russia. You can get prices for equipment by submitting a request for a commercial offer from the company.

Where is the NTP time server used?

The scope of the equipment is quite wide. NTP servers are used at all facilities where it is extremely important to regulate time parameters:

  • Companies mobile operators and telecommunications.
  • Internet providers.
  • Airports, railway and bus stations.
  • In commercial automated accounting systems.

Time synchronization is an important task, although not many people have thought about it. Well, what's wrong with running away on the server time? Did you know that many clock issues affect protocols related to cryptography? For this reason, in Active Directory, a clock difference of more than 5 minutes will result in Kerberos authentication problems.

hourly levels. Strata.

To understand an NTP device, you should know about the concept strata or stratum. Authoritative time sources such as GPS satellites, cesium atomic clocks, WWVB radio waves - all this stratum 0. They are authoritative on the grounds that they have some way of maintaining highly accurate timekeeping. You can, of course, use ordinary quartz watches, but knowing that it is easy to lose 15 seconds with them in a month, it is better not to use them as a measure of time. Stratum 0 this is when a second is not lost in 300,000 years!

Computers that directly (not over the network!) take time from stratum 0- this is stratum 1. Since there are always delays due to signal transmission and costs for setting time, computers stratum 1 not as accurate as stratum 0, but in real life the difference reaches a couple of microseconds (1 µs = 10 -6 s), which is quite an acceptable deviation.

The next level of computers taking time over the network from stratum 1- it's... drumroll... intrigue... stratum 2! Again, due to various delays (network for sure), stratum 2 a bit behind stratum 1 and certainly from stratum 0. In practice, this difference ranges from a few microseconds (1 µs = 10 -6 s) to a few milliseconds (1 ms = 10 -3 s). Many want to sync with the layer no further stratum 2.

As is clear from the diagram, stratum 4 takes time from superiors stratum 3. stratum 5 at stratum 4 and so on. stratum 16 is considered the lowest layer and time is considered there out of sync.

To synchronize the time using the NTP protocol, you must first manually set your time. More than 1000 seconds difference between your exact time and your watch is not allowed. If the time server you are using lies for more than 1000 milliseconds (1 second), then it will be delisted and others will be used instead. This mechanism allows you to filter out bad sources of time.

Time client.

In the /etc/ntp.conf file, the Server lines are important for the client. There can be several - up to 10 pieces!

How much to add? Keep in mind:

  • If you have only one server (one server line), then if this server starts lying, then you will blindly follow it. If his time runs out by 5 seconds and you run after him.
  • If 2 servers are added (2 server lines), then NTP will mark both of them as false tickers. If one of them lies, then NTP cannot understand who is lying, since there is no quorum.
  • If 3 or more time servers are added, then one liar can be calculated false tickers. If there are 5 or 6 time servers, then you can find 2 liars false tickers. If there are 7 or 8 servers, then 3 false tickers. If there are 9 and 10 servers, then 4 false tickers.

NTP Pool project.

There is such a NTP Pool project at the address of which pool.ntp.org/zone/ru/ you can find time servers recommended for Russian users.

server0.ru.pool.ntp.org
server1.ru.pool.ntp.org
server2.ru.pool.ntp.org
server3.ru.pool.ntp.org

Operating systems such as Debian and Ubuntu offer users their own time servers.

server0.debian.pool.ntp.org
server1.debian.pool.ntp.org
server2.debian.pool.ntp.org
server3.debian.pool.ntp.org

server0.ubuntu.pool.ntp.org
server1.ubuntu.pool.ntp.org
server2.ubuntu.pool.ntp.org
server3.ubuntu.pool.ntp.org

If you call ntpq -pn on your Linux machine that uses NTP

Remote refid st t when poll reach delay offset jitter ======================================= ===================================== +93.180.6.3 77.37.134.150 2 u 62 1024 377 53.658 -0.877 1.174 +85.21.78.23 193.190.230.65 2 u 1027 1024 377 54.651 0.167 1.531 *62.173.138.130 89.109.251.24 2 u 940 1024 377 52.796 -0.143 1.001 +91.206.16.3 194.190.168.1 2 u 258 1024 377 93.882 -0.680 2.196 -91.189.94.4 193.79.237.14 2 u 596 1024 377 100.219 1.562 1.482

What do the column names say?

  • remote- remote servers with which you synchronize time.
  • refid- superior stratum for this server.
  • st- stratum level. From 0 (not available to us) to 16 (not desirable for us). Ideal - 2.
  • t- connection type. " u"- unicast or manycast, " b"-broadcast or multicast, " l" local reference clock, " s" - symmetrical node, " A" - manycast server, " B"-broadcast server, " M"- multicast server.
  • when- the time when the server last answered us. The parameter displays the number in seconds, but may be in minutes if the number is m or hours if h.
  • poll- polling frequency. Minimum 16 seconds, maximum 32 hours. The number must be 2 n . Usually in this parameter there is either 64 seconds or 1024.
  • reach- An 8 bit octet indicating the status of communication with the remote time server: success or failure. If the bits are set, then success, otherwise, failure. The value 377 is binary 0000 0000 1111 1111.
  • delay- the value in milliseconds shows the time between sending and receiving a response (round trip time - RTT).
  • offset- offset in milliseconds between you and the time servers. Can be positive or negative number.
  • jitter- an absolute value in milliseconds indicating the standard deviation of your offset.

Before the IP address of the NTP server there is a symbol - this is tally code. Kinds tally code:

  • " " - discarded as invalid. For example, there is no connection with him or he is offline, he is too high in rank and does not serve people like you.
  • "x"- discarded by the "intersection" algorithm. The intersection algorithm prepares a list of candidate partners that can become synchronization sources and calculates a confidence interval for each of them.
  • "." - dropped due to table overflow.
  • "-" - discarded by the cluster algorithm. The clustering algorithm sorts the list of candidates by layer codes and synchronization distances.
  • "+" - the server is enabled by the "combine algorithm". This server is a great candidate if your current time server starts to fail you.
  • "#" - the server is a great alternative time server. The server with # can only be seen if you have more than 10 server entries in /etc/ntp.conf
  • "*" - current time server. Its readings are used to synchronize your clocks.
  • "o"- Pulse per second (PPS) server. This usually means that this time server uses time sources such as GPS satellites and other precise time signals. If drawn about, then other types of tally code will no longer be displayed.

In field refid can be the following values:

  • IP address - address of the remote time server.
  • .ACST.- NTP manycast server.
  • .ACTS.- Automated Computer Time Service from the American National Institute of Standards and Technology.
  • .AUTH.- authentication error.
  • .AUTO. - error in Autokey sequences.
  • .BCST.- NTP broadcast server.
  • .CHU.- Shortwave radio receiver from CHU station in Ottawa, Ontario, Canada.
  • .CRYPT. - Autokey protocol error.
  • .DCFx.- LF radio receiver from station DCF77 in Mainflingen, Germany.
  • .DENY.- Access denied.
  • .GAL.-European Galileo satellite receiver.
  • .GOES.- American Geostationary Operational Environmental Satellite receiver.
  • .GPS.-American Global Positioning System receiver.
  • .HBG.- LF radio receiver from HBG station in Prangins, Switzerland.
  • .INIT.- Peer association initialized.
  • .IRIG.- Inter Range Instrumentation Group time code.
  • .JJY.- LF radio receiver from JJY Station at Mount Otakadoya, near Fukushima or Mount Hagane on Kyushu Island, Japan.
  • .LFx.- Regular LF radio receiver.
  • .LOCL. - local clock of the host.
  • .LORC.- LF radio receiver from Long Range Navigation (LORAN-C).
  • .MCST.- NTP multicast server.
  • .MSF.- Anthorn Radio Station near Anthorn, Cumbria.
  • .NIST.-American National Institute of Standards and Technology.
  • .PPS.- clock Pulse per second.
  • .PTB.- Physikalisch-Technische Bundesanstalt from Brunswick and Berlin, Germany.
  • .RATE.- NTP poll threshold exceeded.
  • .STEP.- change the NTP step. Bias offset less than 1000 milliseconds, but more than 125 milliseconds.
  • .TDF.- LF radio receiver from TéléDiffusion de France station in Allouis, France.
  • .TIME.- NTP association timeout.
  • .USNO.- United States Naval Observatory.
  • .WWV.- HF radio receiver from the WWV station at Fort Collins, Colorado, United States.
  • .WWVB.- LF radio receiver from the WWVB station at Fort Collins, Colorado, United States.
  • .WWVH.- HF radio receiver from the WWVH station at Kekaha, on the island of Kauai in Hawaii, United States.

First, get rid of the thought of how to get time from stratum 1, they say they are closest to the exact time. They are closer to the most accurate time on the planet, only they themselves are overloaded and have high RTT delays for regular servers. Better find a normal one stratum 2 and don't worry about it. Do not forget that we are talking about microseconds and milliseconds, which in ordinary life is quite enough.

Second, remember that connecting to the nearest time server is not always ideal. More important is not territorial proximity, but the level of stratum. The NTP Pool project publishes a list of servers only at the level stratum 1 and stratum 2 and it is better to take up to 10 time servers from this list, which will be just fine.

Thirdly, if you are a simple home user-client, then the servers recommended for you in your operating system will be an ideal option that does not require extra gestures.

For large offices, the best option would be to set up your own time server for work computers. This server will receive the exact time from Internet time servers and provide it local computers. On Debian and Ubuntu servers, just uncomment the line

Restrict 192.168.0.0 mask 255.255.0.0 nomodify notrap

in the ntpd daemon configuration file - /etc/ntp.conf

Users from the 192.168/16 network will be able to get the most accurate clock from your server. For internal Linux-based servers that are not time servers and do their own thing, instead of running the ntpd daemon in client mode, it is enough to specify in the /etc/cron.daily/syncntpd file. It is recommended that you read the differences between ntpdate and ntp and decide for yourself.
#!/bin/sh
/usr/sbin/ntpdate your server's IP address > /dev/null 2>&1
exit 0

and once a day, thanks to the ntpdate command, time synchronization will be performed. To avoid misunderstandings, do not be lazy before implementing a time server and synchronizing everything and everything via the NTP protocol - manually set the correct time on all servers and workstations available to you. If your unsynchronized time is too different from the correct one, then you can start a lot of unnecessary problems in the beginning.

Fourthly, NTP is not connected in any way in which country and what time zones are used and how the transition to summer and winter time occurs and whether such a transition is made in this country. This responsibility lies with the operating system, which you need to update if there are changes in watchmaking in the country. On Debian and Ubuntu systems, the tzdata package is responsible for this and should be up to date.

Fifth, it is better not to raise your NTP server on a highly loaded system.

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

NTP protocol

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

NTP uses for its work UDP protocol and port 123.

Current protocol version - NTP 4. NTP uses a hierarchical system "hour levels"(they are also called Stratum). Level 0 (or Stratum 0)- these are usually devices that are atomic clocks (molecular, quantum), GPS clocks or radio clocks. These devices are usually not published to the World Wide Web, but are connected directly to Tier 1 time servers via the RS-232 protocol (marked with 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 it is also possible to synchronize with servers of your level. Level 3 works similarly to the second. Usually servers of levels from the second and below are published in the network. NTP protocol supports up to 256 levels. I would also like to note that servers of levels 1 and 2, and sometimes 3 are not always open to the public. 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 increasing the total number of servers and hence .

Assigning an NTP server on the local network

Why do we need an NTP server? For example, there are services in operating systems, which may depend on synchronized time. The most notable 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, the exact time on all computers greatly facilitates the analysis of security logs when investigating incidents in local network.

NTP server/client operating modes

Client/Server

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

Symmetric 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 peers, acting as a client and time server for them. Therefore, even if the machine "loses" the external source, it will still be able to get the exact time from its neighbors. Neighbors can work in two modes - active and passive. When operating in active mode, the machine itself transfers its time to all neighbor machines listed in the peers section of the ntp.conf configuration file. If neighbors are not specified in this section, then the machine is considered to be in passive mode. Authentication must be used to prevent an attacker from compromising other machines by posing as an active source.

Broadcast mode

This mode is recommended when a small number of servers serve a large number of clients. When operating in this mode, the server periodically broadcasts 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 the time is delivered within the same subnet (restriction of broadcast packets). In addition, authentication must be used to protect against intruders.

Multicast mode

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

Manycast Mode

This mode is new to the fourth version of the NTP protocol. It implies that the client searches for manycast servers among its network neighbors, receives time samples from each of them (using cryptography) and, based on these data, selects the three “best” manycast servers with which the client will synchronize. In the event of a failure of one of the servers, the client automatically updates its list.

To transmit time samples, clients and servers operating in manycast mode use addresses of multicast groups (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 will briefly tell you what time exists in Linux and how to set it. In Linux, as in other OS, there are 2 times. First - hardware , sometimes called Real Time Clock, abbreviated ( RTC) (they are also BIOS clocks) they are usually associated with an oscillating quartz crystal, which has an accuracy of up to several seconds per day. The accuracy depends on various fluctuations, such as ambient temperature. Second clock - internal software clock , which run continuously, including during breaks in the system. They are subject to fluctuations associated with high system load and interrupt latency. However, the system usually reads the hardware clock at boot and then uses the system clock.

Operating system date and time set at boot based on the value hardware clock, as well as time zone settings. The 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(analogue of GMT), or the current territorial time. The general recommendation on what time to set (?) is as follows: if the computer has several operating systems and one of them is Windows, then you must use the current time (because Windows takes the time from the BIOS / CMOS and considers it local). If only operating UNIX systems families, it is desirable to store the time in the BIOS in UTC format.

After the operating system boots, the operating system clock and the BIOS 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. Which clock keeps the correct time? Neither one nor the other until we set up time synchronization.

Note:

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

Because the number of seconds since January 1, 1970 UTC is stored as a signed 32-bit integer (this is true for Linux/Intel systems), your clock will stop working around 2038. Linux doesn't have a Y2K problem, but it does have a Y2038 problem. Fortunately, by that time all linux's will be running on 64-bit systems. A 64-bit integer will contain our clock up to approximately 292271-millionth year.

NTP Server Linux

Introduction

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

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 "accept" 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. Synchronize all computers on the local network with the specified servers that receive time from the Internet.

Installing ntpd

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

Before configuring the daemon to synchronize with the outside world, I would suggest setting the current system date to a value that is 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 not required to be specified.

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 options, which can be found in man date.

Also, you need 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

In the first example, configuration file, which defines the use of UTC for RH, the second - for Deb distributions.

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

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

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

Now that we have everything prepared and installed, let's proceed to at the construction site.

Managing the ntpd daemon

Control ntpd daemon is 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 startup options:

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

Setting up the ntpd server

First of all, I advise you to change the daemon startup 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 setting will allow the clock to be synchronized 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 syntax of the file is standard, as in many other configs: empty lines and lines starting with the "#" character are ignored. Here is 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 per line. If the server is given with an 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 other servers' responses, 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 timekeeping equipment.

Parameter driftfile specifies the file that is used to store the system clock offset. As far as I understand, this file constantly 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 specifying this file in the configuration - the file must be created.

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

restrict default ignore

If you want to allow sync your clock with your server only machines on your network, but ban them configure the server or be equal participants in time synchronization, then instead of the specified one, 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 multiple restrict directives.

For the daemon to work correctly and more accurately, it is advisable to choose a level server - from stratum 2 (you can, of course, stratum1, but you have to kill time looking for such a server) and from the selected stratum 2 those to which the minimum "distance". Usually such servers can 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 a list of open servers of the second level from here: http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers.

Select 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 this list, we select the servers that meet our requirements by analyzing the output of the command ntpdate. When the command is executed, the following syntax is applied:

ntpdate parameters servers_space separated

In order for our query not to make changes to the system, we must use the -q parameter, which indicates the use of the query without making changes. It is also possible to use the -d switch, which indicates that the command will be executed in debug mode, displaying additional information, without making real changes (with this switch, a bunch of other garbage is displayed :), which we don’t need at the moment). See man 8 ntpdate for other options. From the specified link, I selected all the 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 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.003147, 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.138, 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 O Greater accuracy is obtained when using servers that have a low latency packet transmission over the network. To find out, you can use . Accordingly, by first choosing those with a shorter response time, and of them, those with fewer hops. I, in order not to waste time, will use all the specified servers and enter them into the configuration file. Total, knowing all of the above, I will describe my resulting file /etc/ntp.conf:

Ntp-server:~# cat /etc/ntp.conf # LAN servers (commented out, not used - only one server on the network) #server 192.168.0.2 #server 192.168.0.5 # Internet server 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: # ignore everything by default restrict default ignore # localhost without parameters - everything is allowed. Parameters go only to bans. restrict 127.0.0.1 # the following describes the servers with which we synchronize in 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 LAN 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 level of trust for 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 options that I did not mention:

  • enable/disable auth/monitor/pll/pps/stats - switch on switch off working mode:
    • auth- communicate with unmentioned neighbors only in authentication mode;
    • monitor- allow request monitoring;
    • pll- allow setting local clock frequency via NTP;
    • stats- allow the collection of statistics;
  • statisticsloopstats- on each modification of the local clock, writes a line to the file loopstats;
  • statisticspeerstats- each communication with a neighbor is recorded in a log stored in a file peerstats;
  • statisticsclockstats- each message from the local clock driver is written to a log stored in a file clockstats;
  • statsdir(catalogue_name_with_statistics)- sets the name of the directory where files with server statistics will be located;
  • filegen - defines the algorithm for generating filenames, 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 forbidden, can be changed with the file key;
    • suffix- is generated depending on typename;
  • restrictnumeric-address- sets the access restriction: packets are sorted and masked, the source address is taken and compared sequentially, the 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 do not synchronize with it;
  • clientlimitlimit- for the flag limited determines the maximum number of clients served (by default 3);

In total, we got ntpd-server, which is synchronized with the outside world, allows you to get the 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). We just need to set up the clients and learn how to monitor our server.

Monitoring the ntpd server and synchronization

When you are all set. 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 outputs to standard output a list of time sources with their characteristics (other command options 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 the time from. It can be a hostname or something like .GPS. indicating the origin of the Global Positioning System.

Stratum (level) is a number from 1 to 16, indicating the accuracy of the server. One means maximum precision, 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. After 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 representing the results of the last eight attempts to connect to the server. The bit is set if the remote server has responded.

The amount of time (in seconds) it takes to get a response to a "what time is it?" query.

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

Dispersion (Jitter) is a measure of statistical deviations from the offset value (offset field) over several successful request-response pairs. A smaller 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 the 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 much level, cycle or obvious error;

ntpd service"smart" and itself weeds out sources of time that are too out of the bounds of reason. Some time after starting, ntpd will choose the most reliable data sources and will synchronize with them. The list of reference NTP servers provided by us 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 output of the command, it can be seen that our server has already become a stratum 2 level. It takes some time to reach this level. Perhaps in the first 10-15 minutes the server level will be higher.

The correct operation of the ntp server can also be judged by 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

Configuring netfilter (iptables) for NTP server

Having configured the server, it would be nice to protect it. We know that the server is running on port 123/udp, while requests are also sent from port 123/udp. After reading the article, and having read the practical ones, you can create network traffic filtering rules:

Ntp ~ # iptables-save # generic 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 LAN access to 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 the client machines have a couple of extra megabytes of RAM, then you can start 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, you must correctly specify in which format to store the time and select the correct time zone, .

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

C:\>nettime /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 started successfully. C:\>net time /querysntp The current SNTP value is: The command completed successfully.

Conclusion

Well, like everything! The volume of the article turned out to be enormous ... I didn’t even expect it myself. Let me summarize a little. In this article, I hope it became clear to us what is and how the NTP server works. Learned how to set up a server and clients on UNIX and Windows machines. In a few words, the structure of time synchronization in the local network is as follows: There are 1.2 or more exact time servers in the local network, they synchronize their time with external sources in the global network. Server and client settings are based on /etc/ntp.conf (main ntpd daemon configuration file), /etc/localtime (current timezone file), /etc/sysconfig/ntp (for RH) and /etc/default /ntp (for Deb) - daemon startup parameter files. For local ntp server in the configuration file, external servers are specified to receive the time and access is allowed for these servers with the restrict parameter, as well as for computers on the local network, for clients the time source is specified - local servers on the local network, and access is also denied for everyone except the time source in 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 Stratum1 level exact time server.
  • describes how to configure authorization on the ntp server.

There are many services in operating systems whose normal functioning depends on the accuracy of the system clock. If the exact time is not set on the server, this can cause various problems.

For example, on a local network, it is required that the clocks of machines sharing files be synchronized - otherwise it will not be possible to correctly set the modification time of files. This, in turn, can cause version conflicts or important data to be overwritten.

If the server does not have an exact time set, there will be problems with Cron jobs - it is not clear when they will run. It will be very difficult to analyze the system event logs to diagnose the causes of failures and malfunctions ...

You can go on for a long time...

To avoid all the described problems, you need to set up synchronization of the system clock. Linux uses NTP (Network Time Protocol) for this. In this article, we will talk in detail about how to install and configure NTP on the server. Let's start with a little theoretical introduction.

How does the NTP protocol work?

The NTP protocol is based on a hierarchical structure of exact time servers, in which different levels (English strata) are distinguished. Level 0 refers to the reference clock (atomic clock or GPS clock). At level zero, NTP servers don't work.

Tier 1 NTP servers, which are sources for Tier 2 servers, synchronize with the reference clock. Tier 2 servers synchronize with Tier 1 servers, but can also synchronize with each other. Tier 3 and below servers work the same way. In total, up to 256 levels are supported.

The hierarchical structure of the NTP protocol is characterized by fault tolerance and redundancy. In the event of connection failures with the upstream servers, the backup servers take over the synchronization process. Redundancy ensures that NTP servers are always available. By synchronizing with multiple servers, NTP uses data from all sources to calculate the most accurate time.

Installing and configuring an NTP server

The best known and most widely used time synchronization tool is the ntpd daemon. Depending on the settings specified in the configuration file (this will be discussed below), it can act both as a server and as a client (i.e. it can both receive time from remote hosts and distribute it to other hosts) . Below we will describe in detail how to install and configure this daemon in OC Ubuntu.

Installation

The NTP program is included in the distributions of most modern Linux systems and is installed using a standard package manager:

$ sudo apt-get install ntp

Setting

After the installation is completed, open in text editor/etc/ntp.conf file. It stores all program settings. Let's consider them in more detail.

Logging options

The first line of the config file looks like this:

Driftfile /var/lib/ntp/ntp.drift

It specifies a file for storing information about the frequency of the time offset. This file stores the value resulting from previous time adjustments. If external NTP servers become unavailable for one reason or another, the value will be taken from it.

Logfile /var/log/ntp.log

List of servers for synchronization

The configuration file specifies the list of NTP servers with which synchronization will be performed. By default it looks like this:

Server 0.ubuntu.pool.ntp.org server 1.ubuntu.pool.ntp.org server 2.ubuntu.pool.ntp.org server 3.ubuntu.pool.ntp.org

Each line means a group of servers that will report the correct time to our server. You can improve synchronization accuracy using the iburst option (it indicates that not one, but several packets should be sent to the server for synchronization):

Server 0.ubuntu.pool.ntp.org iburst server 1.ubuntu.pool.ntp.org iburst server 2.ubuntu.pool.ntp.org iburst server 3.ubuntu.pool.ntp.org iburst

You can also specify your preferred server with the prefer option:

Server 0.ubuntu.pool.ntp.org iburst prefer

NTP servers are scattered around the world (here, for example, is a list of available public NTP servers). To ensure a more accurate setting of the system clock, it is recommended to synchronize only with ntp servers of the region in which our server is geographically located. To do this, in the /etc/ntp.conf configuration file, specify the regional subdomain for pool.ntp.org in the server addresses:

  • Asia - asia.pool.ntp.org;
  • Europe - europe.pool.ntp org;
  • Africa — africa.pool.ntp.org;
  • North America - north-america.pool.ntp.org;
  • South America - south-america.pool.ntp.org;
  • Oceania - oceania.pool.ntp.org.

You can also specify subdomains for individual countries (for more details, see ). There is also a subdomain for Russia - ru.pool.ntp.org

Backup time server

An NTP server that is disconnected from the Internet for any reason may transmit its system clock data for synchronization. To do this, add the following line to the configuration file:

Server 127.127.1.0

Restrictions

Recently, cases of using NTP servers to amplify traffic in DDoS attacks have become more frequent (for more details, see, for example,). To prevent our server from becoming a victim of abuse, it would be useful to set access restrictions for external clients. By default, the following restrictions are set in the /etc/ntp.conf file:

Restrict −4 default kod notrap nomodify nopeer noquery restrict −6 default kod notrap nomodify nopeer noquery

The nomodify, notrap, nopeer, and noquery options prevent third-party clients from modifying anything on the server. The kod parameter (this abbreviation means kiss of death) provides additional protection: a client that sends too many requests will first receive a so-called kod packet (denial of service warning) and then be disconnected from the server.

In order for machines from the local network to synchronize with the NTP server, add the following line to the configuration file:

Restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

For the local host, you can set access to the NTP server without restrictions:

Restrict 127.127.1.0

Synchronization check

After all the necessary changes have been made to the configuration file and saved, restart the NTP server:

$ service restart ntp

Then run the following command:

$ ntpq -pn

Its output will be presented in the form of a table:

Remote refid st t when poll reach delay offset jitter ======================================= ===================================== *62.76.96.4 130.173.91.58 2 u 207 256 37 10.985 -215.79 256.992 +85.21.78.91 89.175.22.41 2 U 193 256 37 32.623 -207.70 259.121 +31.131.249.27 89.175.22.41 2 U 19621 -216.90 257.037 +85.21.11.11.1111111.11.111111111.1111111111.1AND 207.41 259.863 +91.189.94.4 193.79.237.14 2 u 192 256 37 50.573 -206.62 259.542

The table indicates the following parameters:

  • remote — exact time server address (this column displays servers from the list in the configuration file);
  • refid - upstream server (the one from which the server from the previous columns receives synchronization);
  • st — level (stratum) of the server;
  • t — peer type (u- unicast, m- multicast);
  • when is the time of the last synchronization;
  • poll is the time in seconds it takes for the NTP daemon to synchronize with the peer.
  • reach — server availability status; after eight successful synchronization attempts, the value of this parameter becomes equal to 377;
  • delay — response delay time from the server;
  • offset is the time difference between our server and the synchronization server; a positive value of this parameter means that our clock is fast, a negative value means that it is behind;
  • jitter is the time offset on the remote server.

The following characters can be specified to the left of the server address:

  • * server selected for synchronization;
  • + a server suitable for updating (with which you can synchronize);
  • — it is not recommended to synchronize with the server;
  • x server is unavailable.

You can check if a server from the list is suitable for synchronization using the command:

Ntpdate -q server хх.ххх.ххх.ххх, stratum 2, offset −0.127936, delay 0.02600 7 Jul 14:30:23 ntpdate: adjust time server хх.ххх.ххх.ххх offset −0.127936 sec

From the above output, it can be seen that the server is suitable for synchronization, its level is 2, the offset is 0.127936 ms, and the delay is 0.026 ms.

You can also find out how the synchronization went (successfully or with errors) from the logs:

7 Jul 15:17:17 ntpd: synchronized to 91.198.10.4, stratum=2 7 Jul 15:17:17 ntpd: kernel time sync disabled 0041 7 Jul 15:17:21 ntpd: kernel time sync enabled 0001

Setting the local date and time

The ntpdate command can be used to set the local date and time on the server by sending a request to the NTP server.