Monday, April 4, 2011

How to chroot ntp in Debian

Here are few simple steps to chroot ntp in debian. Add the following to file /usr/local/sbin/chroot-ntp and execute (alternatively you can download script from bitbucket site here):
#!/bin/bash

/etc/init.d/ntp stop

rootfs=/var/chroot/ntp
mkdir -p $rootfs/{etc,var/lib/ntp,var/log}

mv /etc/ntp.conf $rootfs/etc
ln -s $rootfs/etc/ntp.conf /etc/ntp.conf

if [ -e /var/lib/ntp/ntp.drift ]; then
    mv /var/lib/ntp/ntp.drift $rootfs/var/lib/ntp
fi
ln -s $rootfs/var/lib/ntp/ntp.drift \
    /var/lib/ntp/ntp.drift
chown -R ntp:ntp $rootfs/var/lib/ntp

mv /var/log/ntpstats $rootfs/var/log
ln -s $rootfs/var/log/ntpstats /var/log/ntpstats
chown -R ntp:ntp $rootfs/var/log/ntpstats

sed -e "s,'-g','-4 -i /var/chroot/ntp -g'," \
    /etc/default/ntp > /tmp/x && \
    mv /tmp/x /etc/default/ntp

sed -e "s,restrict -6,#restrict -6," \
    -e "s,restrict ::1,#restrict ::1," \
    /etc/ntp.conf > /tmp/x && \
    mv /tmp/x /etc/ntp.conf

/etc/init.d/ntp start
Verify that ntp uses the chroot (file /etc/default/ntp):
NTPD_OPTS='-4 -i /var/chroot/ntp -g'

5 comments:

  1. Thanks for the nice How To.

    Can it be that the /var/chroot/ntp/var/run directory is not used, since the PID is still prepared in /var/run/ntpd.pid (ouside of the chroot). I wonder if I can remove it again?

    When using the drift file, you should also create a directory under /var/chroot/ntp/var/lib/ntp. Owner must be ntp.

    Have you made ​​any modifications to the /etc/init.d/ntp script?

    I'm using Debian Squeeze.

    Thanks.
    Marc

    ReplyDelete
  2. Thank you for your questions. I am using Debian Testing and at the moment it is not far away from Squeeze.

    1. Yes, /var/chroot/ntp/var/run is not used since ntp pid file is controlled during ntp daemon start.

    2. I have modified the script a bit to take drift file into account.

    3. There are no any modifications necessary in /etc/init.d/ntp script.

    ReplyDelete
  3. Quick question for you,

    Prior to running this script I was able to use ntpq -p to check the status of NTP. After running this script I get:

    localhost: timed out, nothing received
    ***Request timed out

    My clients all still appear to be sync'd and when I run ntptrace I get a result back. Is this expected behaviour?

    ReplyDelete
    Replies
    1. When no host is specified to `ntpq -p` command it tries communicate to localhost. There are certain restrictions in /etc/ntp.conf file. Take a look at line related to 127.0.0.1 interface... if you have that line commented out than you get exactly the behavior you experienced.

      Delete
    2. ntp.conf has restrict 127.0.0.1 in it and not commented out. As I mentioned, prior to applying your script it worked fine. When I specify eth0 as a host, you are correct, it connects fine so this appears to be something to do with accessing the loopback interface afer the chroot. Thanks for your help and a great blog.

      Delete