Gentoo Wiki ArchivesGentoo Wiki

HOWTO_NTP

Warning: The procedure here descripted makes use of deprecated ntpdate command. Use ntpd with -s option instead.

Contents

What is NTP?

NTP (Network Time Protocol) is used to synchronize your system's time with an online server. This is a very useful application, and should be installed on every machine. It runs as a service, and can easily (and should) be set up to run as a non-root user, defaulting to user "ntp".

NTP can also be used to serve time for a network. For example a LAN consisting of Windows and Linux machines can all synchronize to a single NTP server, saving bandwidth.

There are alternative programs to perform time synchronization via NTP, such as OpenNTPD and Chrony.

To install ntp, set its caps USE flag in package.use:

echo "net-misc/ntp caps" >> /etc/portage/package.use
emerge --ask --verbose ntp

Firewall Configuration

NTP uses UDP port 123. TCP is not used. To synchronize with external time servers, the following standard iptables rule is sufficient:

-A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

Find a Time Server

NTP needs to synchronize with one or more time servers. The default gentoo configuration includes an index to the pool of time servers and a random timeserver is choosen from the pool on each run.

Alternatively, some choose to use three open access stratum 2 time servers in their own country. You can run e.g. /usr/sbin/tracepath ntp.demon.co.uk or netselect -s 3 pool.ntp.org (available after "emerge netselect") to find the best ones with the lowest communication delay. There are also localized pools available.

(Preferred) List of time servers (based on ntp.org pools)

Multiple preferred servers can be specified by placing a number in front of the domain, e.g.:

server 0.north-america.pool.ntp.org
server 1.north-america.pool.ntp.org
server 2.north-america.pool.ntp.org
AreaHost Name
Worldwidepool.ntp.org
Asiaasia.pool.ntp.org
Europeeurope.pool.ntp.org
North Americanorth-america.pool.ntp.org
Oceaniaoceania.pool.ntp.org
South Americasouth-america.pool.ntp.org

Deeper sub-zones can also be used, e.g.:

server 0.uk.pool.ntp.org
server 1.uk.pool.ntp.org
server 2.uk.pool.ntp.org

Use ntpdate to set time now and on startup

The following instructions will set up your clock once (when you run it manually, but most importantly every time your computer starts). To keep the machine's time in sync over hours and days, you have to run ntpd, which is explained later.

In /etc/conf.d/ntp-client, edit the line:

File: /etc/conf.d/ntp-client
NTPCLIENT_OPTS="-b -u firstserver secondserver thirdserver"

Uncomment it and add your server list (separated by spaces). Your client is now set up to sync with the server(s). If the "-s" option is set (in addition to -b and -u as above) you can leave it be; -s controls logging output of ntpdate and does not affect the time servers (see ntpdate man page for more details about options you can pass here).

Update your clock now, and run rc-update for the default runlevel so it's run on each startup.

/etc/init.d/ntp-client start
rc-update add ntp-client default

If everything fails (like "Failed to set clock" or "Unable to locate the client command") In /etc/conf.d/ntp-client, uncomment and edit the line:

File: /etc/conf.d/ntp-client
NTPCLIENT_CMD="ntpdate"

Service Dependency

ntp-client obviously has to run after the Internet connection is ready. If, for example, the Internet connection is provided by /etc/init.d/net.eth0, then the depend() function of /etc/init.d/ntp-client should be edited to add net.eth0 to the after line. So, the function would look like:

File: /etc/init.d/ntp-client
depend() {
       before cron portmap
       need net
       after net.eth0
       use dns logger
}

It is even possible that the Internet interface setup script finishes before the Internet connection is strictly ready, causing the ntp-client service to fail, in which case a small delay should be added to the Internet provider script, e.g.:

File: /etc/conf.d/net
 postup() {
    if [[ "${IFACE}" == "eth0" ]] ; then
        # Wait for connection to be ready to communicate
        sleep 5
    fi

    return 0
 }

Use ntpd to keep your clock in sync

While ntpdate is useful for immediate (potentially large) changes in time, ntpd maintains the time continually, handling e.g. clock drift.

Configure ntp

Now edit /etc/ntp.conf as per the official docs, ntp wiki and the time servers you chose above.

File: Example /etc/ntp.conf
 # Correct "restrict" settings are essential for ntp to work
 # See http://ntp.isc.org/bin/view/Support/AccessRestrictions
 restrict 127.0.0.1 nomodify
 # Allow ntp to automatically correct predictable clock drift
 driftfile /var/lib/ntp/ntp.drift
 # logfile defaults to /var/log/messages
 logfile /var/log/ntp.log

 # Un-comment the next line, to act as a time server to the local network
 #restrict 192.168.0.0 mask 255.255.255.0 nomodify nopeer notrap

Generic server list:
 server 0.pool.ntp.org
 server 1.pool.ntp.org
 server 2.pool.ntp.org

Good server list for machines based in the UK:
 # This is the fastest, therefore preferred server
 server ntp.demon.co.uk prefer
 # The next two servers are DNS-chosen at random from the country-localized pool
 server 0.uk.pool.ntp.org
 server 1.uk.pool.ntp.org

As mentioned in the ntp wiki, be careful about defining a restrict default line. When using pool servers, these IP addresses will be handled by the default restriction, and could be blocked with a strict default policy, such as restrict default ignore.

Root Permissions

To allow ntpd to set the clock whilst dropping root privileges:

If you are using a 2.6 series kernel, make sure it has been compiled with the following options:

Linux Kernel Configuration: make menuconfig
 Security options  --->
  [*] Enable different security models
  <*>   Default Linux Capabilities - ''CONFIG_SECURITY_CAPABILITIES''

Then make sure you have compiled ntp with the caps USE flag

Finally, make sure there is the following line in /etc/conf.d/ntpd:

File: /etc/conf.d/ntpd
NTPD_OPTS="-u ntp:ntp"

Otherwise, leave this option blank or comment the line out.

Serve time to other NTP Clients

Before any (S)NTP client will synchronize to your server, it must synchronize itself to gain a lower stratum result (e.g. stratum 1). This will be acknowledged by /var/log/ntp.log in the following form. The synchronization can take a few minutes.

File: /var/log/ntp.log
3 May 19:46:05 ntpd[24616]: synchronized to LOCAL(1), stratum=10
3 May 19:46:06 ntpd[24616]: synchronized to 1.2.3.4, stratum=1
3 May 19:51:31 ntpd[24616]: synchronized to 2.3.4.5, stratum=1
3 May 20:21:44 ntpd[24616]: synchronized to 3.4.5.6, stratum=1

Almost all Unix-like operating systems ship with a pre-installed ntp client software, mostly the reference implementation of NTP from www.ntp.org. This applies to every Linux distribution which offers NTP synchronization. A free port of this implementation for Windows can be downloaded from Meinberg and allows you to let your Windows clients synchronize to your Gentoo machine.

samba can also act as the time server for a Windows network, by adding time server = yes to /etc/samba/smb.conf

Clock Accuracy at Reboot

The following option sets the hardware clock during shutdown, so that the clock is accurate even before ntp-client runs during startup:

File: /etc/conf.d/clock
CLOCK_SYSTOHC="yes"
Note: The filename of /etc/conf.d/clock has changed in baselayout 2.

DHCP info

If you are using dhcp to get an ip address, dhcpcd will overwrite /etc/ntp.conf by default. If your dhcp server hands out a valid ntp server this is not a problem. If it does not hand out a valid ntp server, you will want to make sure dhcpcd will not overwrite this file. You can do this by editing /etc/conf.d/net as such:

File: /etc/conf.d/net
dhcpcd_eth0="-N"

Where eth0 is the interface using dhcpcd.

If you are using dhclient instead of dhcpcd to retrieve an IP-address it will also overwrite /etc/ntp.conf. By editing /etc/conf.d/net you can avoid this. Edit the file to read something like this:

File: /etc/conf.d/net
modules=( "dhclient" )
config_eth0=( "dhcp" )
dhcp_eth0=( "nontp" )

Additionally, if DHCP provides a valid ntp server you might want to alter /etc/conf.d/ntp-client to obtain the servers to sync against from /etc/ntp.conf instead of using a fixed list. This can be done using a bit of awk magic:

File: /etc/conf.d/ntp-client
NTPCLIENT_OPTS=" -b -u $(awk '/^[[:space:]]*server[[:space:]]/ { print $2 }' < /etc/ntp.conf)"

More information on DHCP and its settings can be found in the Gentoo Handbook.

Finalizing

All that's left to do is start ntpd and add it to the default runlevel.

/etc/init.d/ntpd start
rc-update add ntpd default

Checking ntp

It may take up to 4 hours of semi-continuous reachability to calibrate the clock before you achieve stratum 3 status. If the stratum status hasn't changed in a few hours, your synchronization is definitely failing. It should settle at 3, from synchronization with stratum 2 servers.

ntpq -c readvar | grep stratum   # Using full name of option
ntpq -c rv | grep stratum        # Using abbreviation

You can check what peers you are connected to (and in turn what they are connected to):

ntpq -c pe

For some more information:

ntpq -c rv

PPP connections

If your WAN connection is a ppp discontinuous connection (e.g. a dial-up connection or a GPRS/UMTS/HSDPA connection) and if you start/stop the ntpd service in the typical runlevel related mode, the ntpd daemon will fill your logs with a garbage of annoying error messages when the Internet connection is down.

To avoid this, you can keep the start/stop scripts off from your runlevels and add two simple scripts in the /etc/ppp/ip-up.d/ and /etc/ppp/ip-down.d/ directories.

File: /etc/ppp/ip-up.d/90-ntpd.sh
#!/bin/sh

# Wait 20 seconds for the slow connection and start the ntpd service
sleep 20
if [ -x /etc/init.d/ntpd ]; then
        if ! /etc/init.d/ntpd --quiet status ; then
                /etc/init.d/ntpd --quiet start
        fi
fi

(Don't forget to perform some test to establish the best sleeping time.)

File: /etc/ppp/ip-down.d/90-ntpd.sh
#!/bin/sh

# Stop the ntpd service after the disconnection
if [ -x /etc/init.d/ntpd ]; then
        if /etc/init.d/ntpd --quiet status ; then
                /etc/init.d/ntpd --quiet stop
        fi
fi

Obviously, in this way you cannot act as a good ntpd server for a LAN.

In addiction, you don't have any hope to take the time during the bootstrap via the ntp-client startup script. But you can set the clock at the connection time adding one more short script.

File: /etc/ppp/ip-up.d/89-ntpdate.sh
#!/bin/sh

# Wait 10 seconds for the slow connection and set the system clock once
sleep 10
if [ -x /usr/bin/ntpdate ]; then
        ntpdate -s -b -u ntp2.inrim.it 3.it.pool.ntp.org 0.europe.pool.ntp.org
fi

Here you have to set your preferred server instead of mine.

Remember that the ntpd daemon writes a lock blocking the ntpdate command, so you must to be sure that the 89-ntpdate.sh script will run before the 90-ntpd.sh script.

Troubleshooting

If ntp does not run as a non-root user, then check the notrust configuration option, and the caps and capability guidelines above.

Ensure that ntp-client and ntpd are in the default runlevel, not the boot runlevel:

rc-update show | grep ntp
rc-update del ntp-client boot
rc-update del ntpd boot
rc-update add ntp-client default
rc-update add ntpd default

Time is wrong by several hours

If date shows the wrong hour, then check /etc/conf.d/clock and /etc/localtime in the localization guide and handbook.

Run /etc/init.d/ntp-client (rather than ntpd) to instantly set the time correctly.

Clock drifts

If the clock moves faster or slower than normal, then try adding noapic to the kernel line in /boot/grub/menu.lst

No server suitable for synchronization found

Client machines will refuse to synchronize from a stratum 16 time server, with the error message, no server suitable for synchronization found.

If you use the Gentoo Home Router Guide it blocks incoming requests to privileged ports. To avoid this, comment out the two lines

# Drop TCP / UDP packets to privileged ports
iptables -A INPUT -p TCP -i ! ${LAN} -d 0/0 --dport 0:1023 -j DROP
iptables -A INPUT -p UDP -i ! ${LAN} -d 0/0 --dport 0:1023 -j DROP

Or add the following above the drop lines:

# Allow NTP client traffic
iptables -t filter -A INPUT -p udp -m udp --sport 123 --dport 123 -j ACCEPT

Bad file descriptor

If you are seeing Bad file descriptor errors in /var/log/messages, then make sure that only one instance of ntpd is running:

/etc/init.d/ntpd stop
killall ntpd
/etc/init.d/ntpd zap
/etc/init.d/ntpd start

Error : Servname not supported for ai_socktype

If you are seeing the error message Error : Servname not supported for ai_socktype, then run:

echo "ntp 123/udp" >> /etc/services
/etc/init.d/ntpd restart

If you have previously tried to set up NTP through Gnome's time & date settings, and are seeing Failed to set clock or NTP socket is in use errors, then uncheck Gnome's "Synchronize clock with Internet servers" box.

Access Restrictions

If ntpd won't connect with the servers, the access restrictions could be too strict. For example

restrict default ignore

Here the ntpd does ignore all packets, even those answers from the time servers. Output from the command 'ntpq -c pe' looks like this:

     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 tack.Informatik .INIT.          16 u    - 1024    0    0.000    0.000 4000.00

Solution: If you have a firewall which filters access to port 123, you can leave the restrictions a bit lesser like this

restrict default kod nomodify notrap nopeer noquery

Without a firewall you can write a strong default restriction and add lesser restrictions for each time server:

restrict default ignore
restrict ntp.theremailer.net nomodify notrap nopeer noquery
restrict tick.fh-augsburg.de nomodify notrap nopeer noquery

But you have to manage the restrictions for each time server, which could be too much work to do. Better use a firewall. Note that this example is also inaccurate, as you can't specify hostnames in restrict lines, only IP addresses (which further complicates things.)

Also don't forget that if you use the nopeer keyword, then ntpd won't synchronise against any servers covered by that restrict line! (So in the above example, ntpd will never sync against anything, because the two timeservers are listed as nopeer and everything else is covered by the ignore line.)

Failed to drop root privileges

If ntpd does not start and /var/log/ntp.log contains the error message, cap_set_proc() failed to drop root privileges: Operation not permitted, then check that the kernel "capability" module is loaded, as referred to above.

Other Problems

Read the NTP troubleshooting guide, which includes some online tools for remotely querying your server, to make sure your firewall or your ISP's firewall isn't blocking TCP/UDP port 123.

Retrieved from "http://www.gentoo-wiki.info/NTP"

Last modified: Wed, 01 Oct 2008 03:53:00 +1000 Hits: 215,010

Created by NickStallman.net, Luxury Homes Australia
Real estate agents should list their apartments, townhouses and units in Australia.