5 Ağustos 2019 Pazartesi

Network Time Protocol - NTP

Network Time Protocol (NTP) Neden Vardır?
Bilgisayarların işlemci tick'leri periyodik değildir. Şu cümle tam anlamıyla periyodik bir saat yapmanın zor olduğunu belirtir.
- Zeroth law: There's a nasty little game the universe plays on you.
- First law: You can't win.
- Second law: But you just might break even, on a very cold day.
- Third law: It never gets that cold.
İdeal saat yoktur ancak birbiri ile uyumlu çalışan saatler vardır. Açıklaması şöyle.
Time (specifically proper time) is the thing measured by clocks. We can be sure that equal time intervals measured by clocks are equal because we have defined time to be the thing that clocks measure. If a clock measured twice as much of something and if the thing that clocks measure is defined to be time then what it measured was by definition twice as much time.

Now, there is no such thing as an ideal clock, but there are some clocks that agree with each other better than other clocks. These clocks that agree with each other well over a long time are used as the standard clocks, and groups of them (at least 3) are used together to detect when one starts to fail electronically or mechanically. Other clocks that are less stable are compared to the standard clocks and adjusted as needed. Clocks that don’t agree with the standard clocks are fixed or removed.
Bilgisayarların saatini ayarlamak için "Network Time Protocol" (NTP) kullanılır.

Clock Kavramları
NTP ile doğrudan bağlantısı olmasa bile aşağıdaki kavramları bilmek bence faydalı.
Clock Skew : Zaman kaynağındaki offset değerin zamana yayılmış hali.
Clock Offset : Zaman kaynağına göreli kayma. NTP'de offset genellikle <= 10 milisaniye civarında olur.
Açıklaması şöyle
To consider NTP, it is necessary to consider the topic of timekeeping itself. It is useful to introduce some timekeeping terms at this juncture:

Stability  How well a clock can maintain a constant frequency
Accuracy How well the frequency and absolute value of the clock compares with a standard reference time
Precision How well the accuracy of a clock can be maintained within a particular timekeeping system
Offset The time difference in the absolute time of two clocks
Skew The variation of offset over time (first-order derivative of offset over time)
Drift         The variation of skew over time (second-order derivative of offset over time)
Port Numarası
Açıklaması şöyle. NTP protokolü UDP Port 123 ile çalışır.
"The Network Time Protocol is a protocol for synchronizing time across your network, this is especially important when utilizing Directory Services. There exists a number of time servers throughout the world that can be used to keep systems synced to each other. NTP utilizes UDP port 123. Through NTP enumeration you can gather information such as lists of hosts connected to NTP server, IP addresses, system names, and OSs running on the client system in a network. All this information can be enumerated by querying NTP server." 

NTP Hangi Zamandan Başlar
NTP, Unix Epoch'undan farklı olarak 1 Ocak 1900'den beri geçen saniyeyi hesaplar.

Unix Epoch ile NTP Epoch arasında  2208988800U saniye fark vardır. Eğer kendi NTP client kodumuzu yazıyor olsaydık, NTP sunucusunun gönderdiği zamandan bu kadar saniyeyi çıkartmak gerekirdi.

Poll Algoritması
Açıklaması şöyle
A NTP client will send a message at regular intervals to a NTP server. This regular interval is commonly set to be 16 seconds. If the server is unreachable, NTP will back off from this polling rate, doubling the back-off time at each unsuccessful poll attempt to a minimum poll rate of 1 poll attempt every 36 hours. When NTP is attempting to resynchronize with a server, it will increase its polling frequency and send a burst of eight packets spaced at 2-second intervals.

When the client clock is operating within a sufficient small offset from the server clock, NTP lengthens the polling interval and sends the eight-packet burst every 4 to 8 minutes (or 256 to 512 seconds).
NTP Response
Response mesajının başında bazı alanlar var. Bunların açıklaması şöyle
LI
Leap Indicator (2 bits)
This field indicates whether the last minute of the current day is to have a leap second applied. The field values follow:
0: No leap second adjustment
1: Last minute of the day has 61 seconds
2: Last minute of the day has 59 seconds
3: Clock is unsynchronized
 
VN
NTP Version Number (3 bits) (current version is 4).
 
Mode
NTP packet mode (3 bits)
The values of the Mode field follow:
0: Reserved
1: Symmetric active
2: Symmetric passive
3: Client
4: Server
5: Broadcast
6: NTP control message
7: Reserved for private use
 
Stratum
Stratum level of the time source (8 bits) The values of the Stratum field follow:

Poll
Poll interval (8-bit signed integer) value of the maximum interval between successive NTP messages, in seconds.
 
Precision
Clock precision (8-bit signed integer)
The precision of the system clock, in log2 seconds.

Root Delay
The total round-trip delay from the server to the primary reference sourced. The value is a 32-bit signed fixed-point number in units of seconds, with the fraction point between bits 15 and 16. This field is significant only in server messages.
 
Root Dispersion
The maximum error due to clock frequency tolerance. The value is a 32-bit signed fixed-point number in units of seconds, with the fraction point between bits 15 and 16. This field is significant only in server messages.
 
Reference Identifier
For stratum 1 servers this value is a four-character ASCII code that describes the external reference source
For secondary servers this value is the 32-bit IPv4 address of the synchronization source, or the first 32 bits of the Message Digest Algorithm 5 (MD5) hash of the IPv6 address of the synchronization source.
Daha sonra timestamp alanları geliyor. Açıklaması şöyle
Reference Timestamp
Time when the system clock was last set or corrected, in NTP timestamp format
Originate timestamp (T1)
Time at the client when the request departed for the server, in NTP timestamp format.
Receive timestamp (T2)
Time at the server when the request arrived from the client, in NTP timestamp format.
Transmit timestamp (T3)
Time at the server when the response left for the client, in NTP timestamp format.
Destination timestamp (T4)
Time at the client when the reply arrived from the server, in NTP timestamp format.
Ayrıca her timestamp alanı yanında bir sistem saatini gösteren alan da bulunur. Açıklaması şöyle
Each of the timestamps fields has an associated time field which is the timestamp as system time which is time in seconds since the Epoch.
Timestamp 64  bit ve yapısı şöyle
NTP timestamp format (64 bits) :
Seconds (32) Fraction (32)
Seconds and Fractions since 01.01.1900
Key ve Message Digest Alanlar
Açıklaması şöyle
The optional Key and Message Digest fields allow a client and a server to share a secret 128-bit key, and use this shared secret to generate a 128-bit MD5 hash of the key and the NTP message fields. This construct allows a client to detect attempts to inject false responses from a man-in the-middle attack.

NTP Response paketinden 3 tane şey hesaplanabilir.

1. Offset Hesaplaması
Açıklaması şöyle
The offset is the difference between your local clock and the clock of the NTP server which is the amount to correct the local clock by in seconds to match the clock of the server.

offset = ((recv_timestamp - orig_timestamp) + (tx_timestamp - dest_timestamp))/2

offset = ((T2 - T1) + (T3 - T4))/2
2. Delay Hesaplaması
Açıklaması şöyle
The "Delay", the time that was needed to transfer the packet in the network
Delay =(t4 - t1) - (t3 - t2)
Here you can see that NTP averages the Delay because it assumes that the trip of the packet is the same in both directions, that means differences influence the Offset as an error.

In local networks the round-trip delay is only a small part of the offset and therefor the offset calculation is already precise.

In bigger networks the offsets and delays are filtered more often, to compensate the delay variations. The offset is calculated from the packet with the smallest delay out of the last eight packets.
Şöyle yaparız
delay = (t4 - t1) - (t3 - t2)
clock offset = (t2 - t1 + t3 - t4)/2
3. Dispersion Hesaplaması
Açıklaması şöyle
Additionally another value is calculated from the same packets:
The "Dispersion" value, an averaged value of the offset deviation from the eight last data packets to the actual offset. The offsets with a smaller delay are weighted more.
Switch ve Router'larda NTP
Bir çok switch ve router NTP sunucusu içeriyor. Tüm router ve switch'lerin saatini NTP ile aynı yapmak log'ları okumayı kolaylaştırır.

Cisco'larda eğer 1.3.6.1.4.1.9.9.168.1.1.11 OID ile SNMP kullanarak NTP sorgulanabilir.

Linux NTP Servisi
Servisi başlatma ve bir daha ki açılışta otomatik başlaması için şöyle yaparız.

service ntpd start
chkconfig ntpd on

Windows NTP Servisi
Windows üzerinde NTP servisi w32time Servisi kullanılır

Linux NTP Servisi
Linux'ta etc/ntpd.conf dosyasında ayarlar bulunur. ntp sunucusu için server 127.0.0.1 satırı mevcuttur. Bu satır servise saati sistemden almasını belirtir.
# Specify one or more NTP servers.

# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board
# on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for
# more information.
#server 0.ubuntu.pool.ntp.org
#server 1.ubuntu.pool.ntp.org
#server 2.ubuntu.pool.ntp.org
#server 3.ubuntu.pool.ntp.org
server 192.168.128.118
# Use system clock as a fallback.
server 127.0.0.1
İstemci dosyasında ise sunucunun IP adresi bulunur. Örneğin server 10.0.0.1 gibi
# if you need to allow access from a remote host, you can add lines like this: 
restrict 10.0.0.1 mask 255.255.0.0 
ntpdate
ntpdate komutu yazısına taşıdım.

NtpDatestamp
Açıklaması şöyle
To convert system time in any format to NTP date and timestamp formats requires that the number of seconds s from the prime epoch to the system time be determined. To determine the integer era and timestamp given s,
era = s / 2^(32) and timestamp = s - era * 2^(32),
which works for positive and negative dates. To determine s given the era and timestamp,
s = era * 2^(32) + timestamp.
Yapısı şöyledir.
struct NtpDatestamp {
  std::int32_t era_number;
  std::uint32_t seconds_since_era_epoch;
  std::uint64_t fraction_of_second;
};
Önce Unix Epoch'tan beri geçen saniyeyi bulmak için şöyle yaparız.
static std::time_t to_time(const boost::posix_time::ptime& time) {
  static const boost::posix_time::ptime epoch_time{
      boost::gregorian::date{1970, 1, 1}};
  const boost::posix_time::time_duration diff{time - epoch_time};

  return (diff.ticks() / diff.ticks_per_second());
}
Daha sonra 1899 yılında itibaren hesaplamak için şöyle yaparız.
auto system_time = boost::posix_time::time_from_string("1899-12-31 00:00:00.123");
boost::posix_time::ptime prime_epoch{boost::gregorian::date{1900, 1, 1}};
// Calculate the number of seconds from the prime epoch to the system time.
std::time_t s{to_time(system_time) - to_time(prime_epoch)};

std::int32_t era{static_cast<std::int32_t>(std::floor(s / std::pow(2, 32)))};
std::uint32_t timestamp{
static_cast<std::uint32_t>(s - era * std::pow(2, 32))};
std::uint64_t fraction{static_cast<std::uint64_t>(
      system_time.time_of_day().fractional_seconds())};

std::cout << "s = " << std::dec << s << '\n';
std::cout << "Era (expected: -1) = " << std::dec << era << '\n';
std::cout << "Timestamp (expected: 4294880896) = " << std::dec << timestamp
            << '\n';
std::cout << "Fraction (expected: 123000) = " << std::dec << fraction << '\n';
adjtime metodu
Açıklaması şöyle
When NTP is configured on a client, it attempts to keep the client clock synchronized against the reference time standard. To do this task NTP conventionally adjusts the local time by small offsets (larger offsets may cause side effects on running applications, as has been found when processing leap seconds). This small adjustment is undertaken by an adjtime() system call, which slews the clock by altering the frequency of the software clock until the time correction is achieved. Slewing the clock is a slow process for large time offsets; a typical slew rate is 0.5 ms per second.

ntp_adjtime metodu - NTP sunucusu ile senkronize olup olmadığımızı döndürür
ntp_adjtime metodu yazısına taşıdım

ntp_gettime metodu
ntp_gettime metodu yazısına taşıdım

GPSD
Windows'ta gpsd yok. Bunun yerine özel bir ntp yazılım kullanılabilir.

GSP cihazı ile ntpd servisini bağlamak için kullanılır. ntpd.conf dosyasına şuna benzer bir satır eklenir.
server 127.127.46.0 
fudge 127.127.46.0 time1 0.0 time2 0.0 refid GPS
Bu örnek ntpd'nin 46 numaralı sürücüsünü kullanıyor. Sürücü listesi şöyle. En çok kullanılan sürücülerden birisi ise 28 numaralı shared memory sürücüsü.
server 127.127.28.0 
fudge 127.127.28.0 time1 0.0 time2 0.0 refid GPS

gpsmm
gpsmm Kütüphanesi yazısına taşıdım.

Hiç yorum yok:

Yorum Gönder