Linux之时间服务器NTP

1 NTP授时的过程

1. 首先,主机当然需要启动 daemon 
2. Client 会向 NTP Server 发送出调校时间的 message ,
3. 然后 NTP Server 会送出目前的标准时间给 Client ,
4. Client 接收了来自 Server 的时间后,会据以调整自己的时间,就达成了网络校时咯!

2 NTP 服务器的阶层概念

2.1 阶层概念

(下面的文字摘自《鸟哥的Linux私房菜》) 你有没有想到一件事啊,那就是如果 Client 到 Server 的讯息传送时间过长怎么办?举例来说,我在台湾以 ADSL 的 PC 主机,联机到美国的 NTP Server 主机进行时间同步化要求,而美国 NTP Server 收到我的要求之后,就发送当时的正确时间给我,不过, 由美国将数据传送回我的 PC 时,时间可能已经延迟了 10 秒钟去了!这样一来,我的 PC 校正的时间是 10 秒钟前的标准时间喔!此外,如果美国那么 NTP 主机有太多的人喜欢上去进行网络校时了,所以 loading (负荷) 太重啦!导致讯息的回传又延迟的更为严重!那怎么办?

为了这些延迟的问题,有一些 program 已经开发了自动计算时间传送过程的误差,以更准确的校准自己的时间!当然啦,在 daemon 的部分,也同时以 server/client 及 master/slave 的架构来提供用户进行网络校时的动作!所谓的 master/slave 就有点类似 DNS 的系统咯!举例来说,台湾的标准时间主机去国际标准时间的主机校时, 然后各大专院校再到台湾的标准时间校时,然后我们再到各大专院校的标准时间校时!这样一来,那几部国际标准时间主机 (Time server) 的 loading 就不至于太大,而我们也可以很快速的达到正确的网络校时的目的呢!

tick.stdtime.gov.tw
tock.stdtime.gov.tw
time.stdtime.gov.tw
clock.stdtime.gov.tw
watch.stdtime.gov.tw

至于 ntp 这个 daemon 是以 port 123 为连结的埠口 (使用 UDP 封包),所以我们要利用 Time server 来进行时间的同步更新时,就得要使用 NTP 软件提供的 ntpdate 来进行 port 123 的联机喔!关于网络校时更多的说明,可以到 NTP 的官方网站 (注4) 上察看喔! 如前所述,由于 NTP 时间服务器采用类似阶层架构 (stratum) 来处理时间的同步化, 所以他使用的是类似一般 server/client 的主从架构。网络社会上面有提供一些主要与次要的时间服务器, 这些均属于第一阶及第二阶的时间服务器 (stratum-1, stratum-2) ,如下所示:

主要时间服务器: http://support.ntp.org/bin/view/Servers/StratumOneTimeServers
次要时间服务器: http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers

由于这些时间服务器大多在国外,所以我们是否要使用这些服务器来同步化自己的时间呢? 其实如果台湾地区已经有标准时间服务器的话,用那部即可,不需要联机到国外啦!浪费带宽与时间啊! 而如前面提到的,台湾地区已经有标准的时间服务器了,所以当然我们可以直接选择台湾地区的 NTP 主机即可。

如果你评估一下,确定有架设 NTP 的需求时,我们可以直接选择台湾地区的上层 NTP 来同步化时间即可。 举例来说 tock.stdtime.gov.tw 这个国家单位的主机应该是比较适合的。一般来说,我们在进行 NTP 主机的设定时,都会先选择多部上层的 Time Server 来做为我们这一部 NTP Server 的校正之用,选择多部的原因是因为可以避免因为某部时间服务器突然挂点时, 其他主机仍然可以提供我们的 NTP 主机来自我更新啊!然后我们的 NTP Server 才提供给自己的 Client 端更新时间。如此一来,国家单位的 tock.stdtime.gov.tw 负载才不会太大,而我们的 Client 也可以很快速的达到校时的动作!

Tips:
其实 NTP 的阶层概念与 DNS 很类似啦,当你架设一部 NTP 主机,这部 NTP 所向上要求同步化的那部主要主机为 stratum-1 时,那么你的 NTP 就是 stratum-2 啰!举例来说,如果我们的 NTP 是向台湾的 tock.stdtime.gov.tw 这部 stratum-2 的主机要求时间同步化,那我们的主机即为 stratum-3 ,如果还有其他的 NTP 主机向我们要求时间同步, 那么该部主机则会是 stratum-4 啦!就这样啊~ 那最多可以有几个阶层?最多可达 15 个阶层喔!

3 ntp.conf文件及参数详解

3.1 ntp.conf文件详解

[root@www ~]# vim /etc/ntp.conf
# 1. 先处理权限方面的问题,包括放行上层服务器以及开放区网用户来源:
restrict default kod nomodify notrap nopeer noquery     <==拒绝 IPv4 的用户
restrict -6 default kod nomodify notrap nopeer noquery  <==拒绝 IPv6 的用户
restrict 220.130.158.71   <==放行 tock.stdtime.gov.tw 进入本 NTP 服务器
restrict 59.124.196.83    <==放行 tick.stdtime.gov.tw 进入本 NTP 服务器
restrict 59.124.196.84    <==放行 time.stdtime.gov.tw 进入本 NTP 服务器
restrict 127.0.0.1        <==底下两个是默认值,放行本机来源
restrict -6 ::1
restrict 192.168.100.0 mask 255.255.255.0 nomodify <==放行区网来源

# 2. 设定主机来源,请先将原本的 [0|1|2].centos.pool.ntp.org 的设定批注掉:
server 220.130.158.71 prefer  <==以这部主机为最优先
server 59.124.196.83
server 59.124.196.84

# 3. 预设时间差异分析档案与暂不用到的 keys 等,不需要更动它:
driftfile /var/lib/ntp/drift
keys      /etc/ntp/keys

3.2 ntp.conf参数详解

3.2.1 restrict管理权限控制

restrict [客户端IP] mask [IP掩码] [parameter]

“客户端IP” 和 “IP掩码” 指定了对网络中哪些范围的计算机进行控制,如果使用default关键字,则表示对所有的计算机进行控制,参数指定了具体的限制内容,常见的参数如下: 其中 parameter 的参数主要有底下这些:

ignore: 拒绝所有类型的 NTP 联机;
nomodify: 客户端不能使用 ntpc 与 ntpq 这两支程序来修改服务器的时间参数, 但客户端仍可透过这部主机来进行网络校时的;
noquery: 客户端不能够使用 ntpq, ntpc 等指令来查询时间服务器,等于不提供 NTP 的网络校时啰;
notrap: 不提供 trap 这个远程事件登录 (remote event logging) 的功能。
notrust: 拒绝没有认证的客户端。
nopeer: 提供时间服务,但不作为对等体
kod: 向不安全的访问者发送Kiss-Of-Death报文

那如果你没有在 parameter 的地方加上任何参数的话,这表示『该 IP 或网段不受任何限制』的意思喔!一般来说,我们可以先关闭 NTP 的权限,然后再一个一个的启用允许登入的网段。

3.2.2 server 设定上层 NTP 服务器

上层 NTP 服务器的设定方式为:

server host [ key n ] [ version n ] [ prefer ] [ mode n ] [ minpoll n ] [ maxpoll n ] [ iburst ] 其中host是上层NTP服务器的IP地址或域名,随后所跟的参数解释如下所示:

key: 表示所有发往服务器的报文包含有秘钥加密的认证信息,n是32位的整数,表示秘钥号。
version:表示发往上层服务器的报文使用的版本号,n默认是3,可以是1或者2。
prefer: 如果有多个server选项,具有该参数的服务器优先使用。
mode: 指定数据报文mode字段的值。
minpoll: 指定与查询该服务器的最小时间间隔为2的n次方秒,n默认为6,范围为4-14。
maxpoll: 指定与查询该服务器的最大时间间隔为2的n次方秒,n默认为10,范围为4-14。
iburst: 当初始同步请求时,采用突发方式接连发送8个报文,时间间隔为2秒。
3.2.3 driftfile 记录时间差异

设定的方式如下:

driftfile [可以被 ntpd 写入的目录与档案]

因为预设的 NTP Server 本身的时间计算是依据 BIOS 的芯片震荡周期频率来计算的,但是这个数值与上层 Time Server 不见得会一致啊!所以 NTP 这个 daemon (ntpd) 会自动的去计算我们自己主机的频率与上层 Time server 的频率,并且将两个频率的误差记录下来,记录下来的档案就是在 driftfile 后面接的完整档名当中了!关于档名你必须要知道:

driftfile 后面接的档案需要使用完整路径文件名;
该档案不能是连结档;
该档案需要设定成 ntpd 这个 daemon 可以写入的权限。
该档案所记录的数值单位为:百万分之一秒 (ppm)。

driftfile 后面接的档案会被 ntpd 自动更新,所以他的权限一定要能够让 ntpd 写入才行.

3.2.4 [key_file]

除了以 restrict 来限制客户端的联机之外,我们也可以透过密钥系统来给客户端认证, 如此一来可以让主机端更放心了。

3.2.5 stratum层次

stratum根据上层server的层次而设定(+1)。对于提供network time service provider的主机来说,stratum的设定要尽可能准确。而作为局域网的time service provider,通常将stratum设置为10

0层的服务器采用的是原子钟、GPS钟等物理设备,stratum 1与stratum 0 是直接相连的,往后的stratum与上一层stratum通过网络相连,同一层的server也可以交互。ntpd对下层client来说是service server,对于上层server来说它是client。ntpd根据配置文件的参数决定是要为其他服务器提供时钟服务或者是从其他服务器同步时钟。所有的配置都在/etc/ntp.conf文件中。

4 Centos-NTP服务器配置实例

有两种情况列举如下:

  1. 本机与公网时间同步,即本机为client
  2. 本机作为授时服务器,为在同一网段中的其他PC机进行授时,即本机为server

下面详细描述两种情况,并且分别进行配置

4.1 作为client

  1. 安装NTP

     yum install -y ntp
    
  2. 验证是否安装已安装ntp

     [root@ERICSSON ~]#  rpm -q ntp
     ntp-4.2.6p5-28.el7.centos.x86_64
    
  3. 配置NTP.conf文件

     # For more information about this file, see the man pages
     # ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).
     
     driftfile /var/lib/ntp/drift
     
     # Permit time synchronization with our time source, but do not
     # permit the source to query or modify the service on this system.
     restrict default nomodify notrap nopeer noquery
     
     # Permit all access over the loopback interface.  This could
     # be tightened as well, but to do so would effect some of
     # the administrative functions.
     restrict 10.0.0.51 nomodify notrap nopeer noquery # 当前节点IP地址
     restrict 127.0.0.1
     restrict ::1
     
     # Hosts on local network are less restricted.
     restrict 10.0.0.2 mask 255.255.255.0 nomodify notrap  #集群所在网段的网关(Gateway),子网掩码(Genmask)
     #restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
     
     # Use public servers from the pool.ntp.org project.
     # Please consider joining the pool (http://www.pool.ntp.org/join.html).
     #server 0.centos.pool.ntp.org iburst
     #server 1.centos.pool.ntp.org iburst
     #server 2.centos.pool.ntp.org iburst
     #server 3.centos.pool.ntp.org iburst
     server 127.127.1.0
     Fudge 127.127.1.0 stratum 10
     #broadcast 192.168.1.255 autokey        # broadcast server
     #broadcastclient                        # broadcast client
     #broadcast 224.0.1.1 autokey            # multicast server
     #multicastclient 224.0.1.1              # multicast client
     #manycastserver 239.255.254.254         # manycast server
     #manycastclient 239.255.254.254 autokey # manycast client
     
     # Enable public key cryptography.
     #crypto
     
     includefile /etc/ntp/crypto/pw
     
     # Key file containing the keys and key identifiers used when operating
     # with symmetric key cryptography.
     keys /etc/ntp/keys
     
     # Specify the key identifiers which are trusted.
     #trustedkey 4 8 42
     
     # Specify the key identifier to use with the ntpdc utility.
     #requestkey 8
     
     # Specify the key identifier to use with the ntpq utility.
     #controlkey 8
     
     # Enable writing of statistics records.
     #statistics clockstats cryptostats loopstats peerstats
     
     # Disable the monitoring facility to prevent amplification attacks using ntpdc
     # monlist command when default restrict does not include the noquery flag. See
     # CVE-2013-5211 for more details.
     # Note: Monitoring will not be disabled with the limited restriction flag.
     disable monitor
    
  4. 启动NTP服务

     ● systemctl start ntpd.service
    
  5. 设置为开机自启动NTP

     ● systemctl enable ntpd.service
    

	[root@ERICSSON ~]# systemctl enable ntpd.service
	Created symlink from /etc/systemd/system/multi-user.target.wants/ntpd.service to /usr/lib/systemd/system/ntpd.service.
  1. 查看NTP服务状态

     ● systemctl status ntpd.service
    

	[root@ERICSSON ~]# systemctl status ntpd.service
	● ntpd.service - Network Time Service
	   Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled; vendor preset: disabled)
	   Active: active (running) since Thu 2019-04-11 01:22:15 JST; 3min 5s ago
	 Main PID: 87560 (ntpd)
	   CGroup: /system.slice/ntpd.service
	           └─87560 /usr/sbin/ntpd -u ntp:ntp -g
  1. 查看NTP进程的状态

     ● watch "ntpq -p"
    

	您可以看到when下面的数字不停的跳动,跳动的周期为‘Every 2.0s’
	Every 2.0s: ntpq -p                                                                                                                                                           Thu Apr 11 01:43:42 2019
	
	     remote           refid      st t when poll reach   delay   offset  jitter
	==============================================================================
	*LOCAL(0)        .LOCL.           5 l   36   64  377    0.000    0.000   0.000	

	第一列中的字符指示源的质量。星号 ( * ) 表示该源是当前引用。
	remote:列出源的 IP 地址或主机名。
	when:指出从轮询源开始已过去的时间(秒)。
	poll:指出轮询间隔时间。该值会根据本地时钟的精度相应增加。
	reach:是一个八进制数字,指出源的可存取性。值 377 表示源已应答了前八个连续轮询。
	offset:是源时钟与本地时钟的时间差(毫秒)。
  1. 查看udp123端口是否处于监听状态

由于NTP的端口号为123,所以我们也可以通过观察NTP的端口号是否处于监听状态来判断其服务是否处于正常状态。

	● ss -unlp|grep "ntpd"

	[root@ERICSSON sysconfig]#  ss -unlp|grep "ntpd"
	UNCONN     0      0      10.0.0.51:123                      *:*                   users:(("ntpd",pid=91993,fd=19))
	UNCONN     0      0      127.0.0.1:123                      *:*                   users:(("ntpd",pid=91993,fd=18))
	UNCONN     0      0            *:123                      *:*                   users:(("ntpd",pid=91993,fd=16))
	UNCONN     0      0      fe80::4de5:88d5:dc2b:d9c9%ens32:123                     :::*                   users:(("ntpd",pid=91993,fd=21))
	UNCONN     0      0          ::1:123                     :::*                   users:(("ntpd",pid=91993,fd=20))
	UNCONN     0      0           :::123                     :::*                   users:(("ntpd",pid=91993,fd=17))
  1. 查看ntp服务器有无和上层ntp连通

     ● ntpstat 
    

	[root@ERICSSON sysconfig]# ntpstat
	synchronised to local net at stratum 6
	   time correct to within 11 ms
	   polling server every 64 s

4.2 作为授时server

4.2.1 HOST主机 ntp.conf

与作为client获取互联网时间的配置相同可以参考上文中的操作进行

4.2.2 client机器 ntp.conf的配置####
		# For more information about this file, see the man pages
		# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).
		
		driftfile /var/lib/ntp/drift
		
		# Permit time synchronization with our time source, but do not
		# permit the source to query or modify the service on this system.
		restrict default nomodify notrap nopeer noquery
		
		# Permit all access over the loopback interface.  This could
		# be tightened as well, but to do so would effect some of
		# the administrative functions.
		restrict 10.0.0.51 nomodify notrap nopeer noquery # 当前节点IP地址
		restrict 127.0.0.1
		restrict ::1
		
		# Hosts on local network are less restricted.
		restrict 10.0.0.2 mask 255.255.255.0 nomodify notrap  #集群所在网段的网关(Gateway),子网掩码(Genmask)
		#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
		
		# Use public servers from the pool.ntp.org project.
		# Please consider joining the pool (http://www.pool.ntp.org/join.html).
		#server 0.centos.pool.ntp.org iburst
		#server 1.centos.pool.ntp.org iburst
		#server 2.centos.pool.ntp.org iburst
		#server 3.centos.pool.ntp.org iburst  ** #server的服务器一定要进行屏蔽**
		server 10.0.0.51                      ** #修改为授时服务器的IP**
		Fudge  10.0.0.51 stratum 10
		#broadcast 192.168.1.255 autokey        # broadcast server
		#broadcastclient                        # broadcast client
		#broadcast 224.0.1.1 autokey            # multicast server
		#multicastclient 224.0.1.1              # multicast client
		#manycastserver 239.255.254.254         # manycast server
		#manycastclient 239.255.254.254 autokey # manycast client
		
		# Enable public key cryptography.
		#crypto
		
		includefile /etc/ntp/crypto/pw
		
		# Key file containing the keys and key identifiers used when operating
		# with symmetric key cryptography.
		keys /etc/ntp/keys
		
		# Specify the key identifiers which are trusted.
		#trustedkey 4 8 42
		
		# Specify the key identifier to use with the ntpdc utility.
		#requestkey 8
		
		# Specify the key identifier to use with the ntpq utility.
		#controlkey 8
		
		# Enable writing of statistics records.
		#statistics clockstats cryptostats loopstats peerstats
		
		# Disable the monitoring facility to prevent amplification attacks using ntpdc
		# monlist command when default restrict does not include the noquery flag. See
		# CVE-2013-5211 for more details.
		# Note: Monitoring will not be disabled with the limited restriction flag.
		disable monitor
4.2.2 client机器 NTP时间的配置

参看作为主机作为Client获取互联网时间的步骤进行 启动服务->开机自启动->检测NTP状态即可。

5 ntpd、ntpdate的区别

使用之前得弄清楚一个问题,ntpd与ntpdate在更新时间时有什么区别。ntpd不仅仅是时间同步服务器,它还可以做客户端与标准时间服务器进行同步时间,而且是平滑同步,并非ntpdate立即同步,在生产环境中慎用ntpdate,也正如此两者不可同时运行。时钟的跃变,对于某些程序会导致很严重的问题。

许多应用程序依赖连续的时钟——毕竟,这是一项常见的假定,即,取得的时间是线性的,一些操作,例如数据库事务,通常会地依赖这样的事实:时间不会往回跳跃。

不幸的是,ntpdate调整时间的方式就是我们所说的”跃变“:在获得一个时间之后,ntpdate使用settimeofday(2)设置系统时间,

这有几个非常明显的问题:

  1. 不安全。

ntpdate的设置依赖于ntp服务器的安全性,***者可以利用一些软件设计上的缺陷,拿下ntp服务器并令与其同步的服务器执行某些消耗性的任务。由于ntpdate采用的方式是跳变,跟随它的服务器无法知道是否发生了异常(时间不一样的时候,唯一的办法是以服务器为准)。

  1. 不精确。

一旦ntp服务器宕机,跟随它的服务器也就会无法同步时间。 与此不同,ntpd不仅能够校准计算机的时间,而且能够校准计算机的时钟。

  1. 不够优雅。

由于是跳变,而不是使时间变快或变慢,依赖时序的程序会出错(例如,如果ntpdate发现你的时间快了,则可能会经历两个相同的时刻,对某些应用而言,这是致命的)。因而,唯一一个可以令时间发生跳变的点,是计算机刚刚启动,但还没有启动很多服务的那个时候。 其余的时候,理想的做法是使用ntpd来校准时钟,而不是调整计算机时钟上的时间。NTPD在和时间服务器的同步过程中,会把BIOS计时器的振荡频率偏差——或者说Local Clock的自然漂移(drift)——记录下来。这样即使网络有问题,本机仍然能维持一个相当精确的走时。

结束语

更多详细的资料请参考《鸟哥的Linux私房菜》 http://cn.linux.vbird.org/linux_server/0440ntp.php#theory_NTP