This file is indexed.

/usr/share/checkbox/scripts/network_ntp_test is in checkbox 0.13.7.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/python
'''
Program to test that ntpdate will sync the clock with an internet time server.

Copyright (C) 2010 Canonical Ltd.

Author:
    Jeff Lane <jeffrey.lane@canonical.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2,
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

The purpose of this script is to test to see whether the test system can
connect to an internet time server and sync the local clock.

It will also check to see if ntpd is running locally, and if so, stop it for
the duration of the test and restart it after the test is finished.

By default, we're hitting ntp.ubuntu.com, however you can use any valid NTP
server by passing the URL to the program via --server

'''
import sys
import os
import logging
import signal
import time
from datetime import datetime, timedelta
from subprocess import Popen, PIPE, STDOUT
from optparse import OptionParser 

def SilentCall(*popenargs):
    '''
    Modified version of subprocess.call() to supress output from the command
    that is executed. Wait for command to complete, then return the returncode
    attribute.
    '''
    null_fh = open('/dev/null','w',0)
    try:
        return Popen(*popenargs,shell=True,stdout=null_fh,stderr=null_fh).wait()
    finally:
        null_fh.close()


def CheckNTPD():
    '''
    This checks to see if nptd is running or not, if so it returns a tuple
    (status,pid,command) where status is either on or off.
    '''
    ps_list = Popen('ps axo pid,comm',shell=True,stdout=PIPE).communicate()[0].splitlines()
    for item in ps_list:
        fields = item.split()
        if fields[1] == 'ntpd':
            logging.debug('Found %s with PID %s' % (fields[1],fields[0]))
            break
    if fields[1] == 'ntpd':
        return ('on',fields[0],fields[1])
    else:
        return ('off','0','0')


def StartStopNTPD(state,pid=0):
    '''
    This is used to either start or stop ntpd if its running.
    '''
    if state == 'off':
        logging.info('Stopping ntpd process PID: %s' % pid)
        os.kill(int(pid),signal.SIGHUP)
    elif state == 'on':
        logging.debug('Starting ntp process')
        status = SilentCall('/etc/init.d/ntp start')
        ntpd_status = CheckNTPD()

        if status == 0:
            logging.info('ntpd restarted with PID: %s' % ntpd_status[1])
        else:
            logging.error('ntpd restart failed for some reason') 
    else:
        logging.error('Unknown status')


def SyncTime(server):
    '''
    This is used to sync time to the specified ntp server.  We use -b here as
    that syncs time faster than the slewed method that ntpdate uses by default,
    meaning we'll see something meaningful faster.
    '''
    cmd='ntpdate -b ' + server
    logging.debug('using %s' % server)
    sync = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE)
    result = sync.communicate()
    
    if sync.returncode == 0:
        logging.info('Successful NTP update from %s' % server)
        logging.info('%s' % result[0].strip())
        return True
    else:
        logging.error('Failed to sync with %s' % server)
        logging.error('%s' % result[1])
        return False

def TimeCheck():
    '''
    Returns current time in a time.localtime() struct
    '''
    return time.localtime()

def SkewTime():
    '''
    Optional function. We can skew time by 1 hour if we'd like to see real sync
    changes being enforced
    '''
    TIME_SKEW=1
    logging.info('Time Skewing has been selected. Setting clock ahead 1 hour')
    # Let's get our current time
    skewed = datetime.now() + timedelta(hours=TIME_SKEW)
    logging.info('Current time is: %s' % time.asctime())
    # Now create new time string in the form MMDDhhmmYYYY for the date program    
    date_time_string = skewed.strftime('%m%d%H%M%Y')
    logging.debug('New date string is: %s' % date_time_string)
    logging.debug('Setting new system time/date')
    status = SilentCall('/bin/date %s' % date_time_string)
    logging.info('Pre-sync time is: %s' % time.asctime())

def main():
    usage = 'Usage: %prog [OPTIONS]'
    parser = OptionParser(usage)
    parser.add_option('--server',
                        action='store',
                        type='string',
                        default='ntp.ubuntu.com',
                        help='The NTP server to sync from. The default server \
                        is %default') 
    parser.add_option('--skew-time',
                        action='store_true',
                        default=False,
                        help='Setting this will change system time ahead by 1 \
                        hour to make the results of ntp syncing more dramatic \
                        and noticeable.')
    parser.add_option('-d','--debug',
                        action='store_true',
                        default=False,
                        help='Verbose output for debugging purposes')
    (options, args) = parser.parse_args()

    # Set up logging
    format = '%(asctime)s %(levelname)-8s %(message)s'
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter(format))
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    if options.debug:
        logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)

    # Make sure NTP is installed
    if not os.access('/usr/sbin/ntpdate',os.F_OK):
        logging.debug('NTP is not installed!')
        return 1
    
    # Check for and stop the ntp daemon
    ntpd_status = CheckNTPD()
    logging.debug('Pre-sync ntpd status: %s %s %s' % (ntpd_status[0],
                                                      ntpd_status[1],
                                                      ntpd_status[2]))
    if ntpd_status[0] == 'on':
        logging.debug('Since ntpd is currently running, stopping it now')
        StartStopNTPD('off',ntpd_status[1])
    
    if options.skew_time:
        logging.debug('Setting system time ahead one hour')
        SkewTime()
    else:
        logging.info('Pre-sync time is: %s' % time.asctime(TimeCheck()))
    
    sync = SyncTime(options.server)

    logging.info('Current system time is: %s' % time.asctime(TimeCheck()))

    # Restart ntp daemon
    if ntpd_status[0] == 'on':
        logging.debug('Since ntpd was previously running, starting it again')
        StartStopNTPD('on')

    if sync is True:
        return 0
    else:
        return 1

if __name__ == '__main__':
    sys.exit(main())