]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/ntp/scripts/update-leap/update-leap.in
Fix multiple vulnerabilities of ntp.
[FreeBSD/releng/10.2.git] / contrib / ntp / scripts / update-leap / update-leap.in
1 #! @PATH_PERL@ -w
2
3 # Copyright (C) 2015 Network Time Foundation
4 # Author: Harlan Stenn
5
6 # Original shell version:
7 # Copyright (C) 2014 Timothe Litt litt at acm dot org
8
9 # This script may be freely copied, used and modified providing that
10 # this notice and the copyright statement are included in all copies
11 # and derivative works.  No warranty is offered, and use is entirely at
12 # your own risk.  Bugfixes and improvements would be appreciated by the
13 # author.
14
15 use strict;
16
17 use Digest::SHA qw(sha1_hex);
18 use File::Copy qw(move);
19 use File::Fetch;
20 use Getopt::Long qw(:config auto_help no_ignore_case bundling);
21 use Sys::Syslog;
22
23 my $VERSION="1.003";
24
25 # leap-seconds file manager/updater
26
27 # ########## Default configuration ##########
28 #
29
30 my $CRONJOB = $ENV{'CRONJOB'};
31 $CRONJOB = "" unless defined($CRONJOB);
32 my $LOGGER;
33 my $QUIET = "";
34 my $VERBOSE = "";
35
36 # Where to get the file
37 # Choices:
38 #       https://www.ietf.org/timezones/data/leap-seconds.list
39 #       ftp://time.nist.gov/pub/leap-seconds.list
40 my $LEAPSRC="https://www.ietf.org/timezones/data/leap-seconds.list";
41 my $LEAPFILE;
42
43 # How many times to try to download new file
44 my $MAXTRIES=6;
45 my $INTERVAL=10;
46
47 # Where to find ntp config file
48 my $NTPCONF="/etc/ntp.conf";
49
50 # How long (in days) before expiration to get updated file
51 my $PREFETCH="60";
52
53 # How to restart NTP - older NTP: service ntpd? try-restart | condrestart
54 # Recent NTP checks for new file daily, so there's nothing to do
55 my $RESTART="";
56
57 my $EXPIRES;
58 my $FORCE = "";
59
60 # Where to put temporary copy before it's validated
61 my $TMPFILE="/tmp/leap-seconds.$$.tmp";
62
63 # Syslog facility
64 my $LOGFAC="daemon";
65
66 # ###########################################
67
68 =item update-leap
69
70 Usage: $0 [options] [leapfile]
71
72 Verifies and if necessary, updates leap-second definition file
73
74 All arguments are optional:  Default (or current value) shown:
75     -s    Specify the URL of the master copy to download
76           $LEAPSRC
77     -d    Specify the filename on the local system
78           $LEAPFILE
79     -e    Specify how long (in days) before expiration the file is to be
80           refreshed.  Note that larger values imply more frequent refreshes.
81           "$PREFETCH"
82     -f    Specify location of ntp.conf (used to make sure leapfile directive is
83           present and to default  leapfile)
84           $NTPCONF
85     -F    Force update even if current file is OK and not close to expiring.
86     -r    Specify number of times to retry on get failure
87           $MAXTRIES
88     -i    Specify number of minutes between retries
89           $INTERVAL
90     -l    Use syslog for output (Implied if CRONJOB is set)
91     -L    Don't use syslog for output
92     -P    Specify the syslog facility for logging
93           $LOGFAC
94     -t    Name of temporary file used in validation
95           $TMPFILE
96     -q    Only report errors to stdout
97     -v    Verbose output
98
99 The following options are not (yet) implemented in the perl version:
100     -4    Use only IPv4
101     -6    Use only IPv6
102     -c    Command to restart NTP after installing a new file
103           <none> - ntpd checks file daily
104     -p 4|6
105           Prefer IPv4 or IPv6 (as specified) addresses, but use either
106     -z    Specify path for utilities
107           $PATHLIST
108     -Z    Only use system path
109
110 $0 will validate the file currently on the local system
111
112 Ordinarily, the file is found using the "leapfile" directive in $NTPCONF.
113 However, an alternate location can be specified on the command line.
114
115 If the file does not exist, is not valid, has expired, or is expiring soon,
116 a new copy will be downloaded.  If the new copy validates, it is installed and
117 NTP is (optionally) restarted.
118
119 If the current file is acceptable, no download or restart occurs.
120
121 -c can also be used to invoke another script to perform administrative
122 functions, e.g. to copy the file to other local systems.
123
124 This can be run as a cron job.  As the file is rarely updated, and leap
125 seconds are announced at least one month in advance (usually longer), it
126 need not be run more frequently than about once every three weeks.
127
128 For cron-friendly behavior, define CRONJOB=1 in the crontab.
129
130 Version $VERSION
131 =cut
132
133 # Default: Use syslog for logging if running under cron
134
135 my $SYSLOG = $CRONJOB;
136
137 # Parse options
138
139 our(%opt);
140
141 GetOptions(\%opt,
142         'c=s',
143         'e:60',
144         'F',
145         'f=s',
146         'i:10',
147         'L',
148         'l',
149         'P=s',
150         'q',
151         'r:6',
152         's=s',
153         't=s',
154         'v'
155         );
156
157 $LOGFAC=$opt{P} if (defined($opt{P}));
158 $LEAPSRC=$opt{s} if (defined($opt{s}));
159 $PREFETCH=$opt{e} if (defined($opt{e}));
160 $NTPCONF=$opt{f} if (defined($opt{f}));
161 $FORCE="Y" if (defined($opt{F}));
162 $RESTART=$opt{c} if (defined($opt{c}));
163 $MAXTRIES=$opt{r} if (defined($opt{r}));
164 $INTERVAL=$opt{i} if (defined($opt{i}));
165 $TMPFILE=$opt{t} if (defined($opt{t}));
166 $SYSLOG="Y" if (defined($opt{l}));
167 $SYSLOG="" if (defined($opt{L}));
168 $QUIET="Y" if (defined($opt{q}));
169 $VERBOSE="Y" if (defined($opt{v}));
170
171 # export PATH="$PATHLIST$PATH"
172
173 # Handle logging
174
175 openlog($0, 'pid', $LOGFAC);
176
177 sub logger {
178     my ($priority, $message) = @_;
179
180     # "priority" "message"
181     #
182     # Stdout unless syslog specified or logger isn't available
183     #
184     if ($SYSLOG eq "" or $LOGGER eq "") {
185         if ($QUIET ne "" and ( $priority eq "info" or $priority eq "notice" or $priority eq "debug" ) ) {
186             return 0
187         }
188         printf "%s: $message\n", uc $priority;
189         return 0;
190     }
191
192     # Also log to stdout if cron job && notice or higher
193     if (($CRONJOB ne "" and ($priority ne "info" ) and ($priority ne "debug" )) || ($VERBOSE ne "")) {
194         # Log to stderr as well
195         print STDERR "$0: $priority: $message\n";
196     }
197     syslog($priority, $message);
198 }
199
200 # Verify interval
201 # INTERVAL=$(( $INTERVAL *1 ))
202
203 # Validate a leap-seconds file checksum
204 #
205 # File format: (full description in files)
206 # # marks comments, except:
207 # #$ number : the NTP date of the last update
208 # #@ number : the NTP date that the file expires
209 # Date (seconds since 1900) leaps : leaps is the # of seconds to add for times >= Date
210 # Date lines have comments.
211 # #h hex hex hex hex hex is the SHA-1 checksum of the data & dates, excluding whitespace w/o leading zeroes
212 #
213 # Returns:
214 #   0   File is valid
215 #   1   Invalid Checksum
216 #   2   Expired
217
218 sub verifySHA {
219     my ($file, $verbose) = @_;
220
221     my $raw = "";
222     my $data = "";
223     my $FSHA;
224
225     # Remove comments, except those that are markers for last update,
226     # expires and hash
227
228     unless (open(LF, $file)) {
229         warn "Can't open <$file>: $!\n";
230         print "Will try and create that file.\n";
231         return 1;
232     };
233     while (<LF>) {
234         if (/^#\$/) {
235                 $raw .= $_;
236                 s/^..//;
237                 $data .= $_;
238         }
239         elsif (/^#\@/) {
240                 $raw .= $_;
241                 s/^..//;
242                 $data .= $_;
243                 s/\s+//g;
244                 $EXPIRES = $_ - 2208988800;
245         }
246         elsif (/^#h\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)/) {
247                 chomp;
248                 $raw .= $_;
249                 $FSHA = sprintf("%08s%08s%08s%08s%08s", $1, $2, $3, $4, $5);
250         }
251         elsif (/^#/) {
252                 # ignore it
253         }
254         elsif (/^\d/) {
255                 s/#.*$//;
256                 $raw .= $_;
257                 $data .= $_;
258         } else {
259                 chomp;
260                 print "Unexpected line: <$_>\n";
261         }
262     }
263     close LF;
264
265     # Remove all white space
266     $data =~ s/\s//g;
267
268     # Compute the SHA hash of the data, removing the marker and filename
269     # Computed in binary mode, which shouldn't matter since whitespace has been removed
270
271     my $DSHA = sha1_hex($data);
272
273     # Extract the file's hash. Restore any leading zeroes in hash segments.
274
275     if ( ( "$FSHA" ne "" ) && ( $FSHA eq $DSHA ) ) {
276         if ( $verbose ne "" ) {
277             logger("info", "Checksum of $file validated");
278         }
279     } else {
280         logger("error", "Checksum of $file is invalid:");
281         $FSHA="(no checksum record found in file)"
282             if ( $FSHA eq "");
283         logger("error", "EXPECTED: $FSHA");
284         logger("error", "COMPUTED: $DSHA");
285         return 1;
286     }
287
288     # Check the expiration date, converting NTP epoch to Unix epoch used by date
289
290     if ( $EXPIRES < time() ) {
291         logger("notice", "File expired on " . gmtime($EXPIRES));
292         return 2;
293     }
294     return 0;
295 }
296
297 # Verify ntp.conf
298
299 -r $NTPCONF || die "Missing ntp configuration: $NTPCONF\n";
300
301 # Parse ntp.conf for leapfile directive
302
303 open(LF, $NTPCONF) || die "Can't open <$NTPCONF>: $!\n";
304 while (<LF>) {
305     chomp;
306     if (/^ *leapfile\s+"(\S+)"/) {
307         $LEAPFILE = $1;
308     }
309 }
310 close LF;
311
312 -s $LEAPFILE || warn "$NTPCONF specifies $LEAPFILE as a leapfile, which is empty.\n";
313
314 # Allow placing the file someplace else - testing
315
316 if ( defined $ARGV[0] ) {
317     if ( $ARGV[0] ne $LEAPFILE ) {
318         logger("notice", "Requested install to $ARGV[0], but $NTPCONF specifies $LEAPFILE");
319     }
320     $LEAPFILE = $ARGV[0];
321 }
322
323 # Verify the current file
324 # If it is missing, doesn't validate or expired
325 # Or is expiring soon
326 #  Download a new one
327
328 if ( $FORCE ne "" || verifySHA($LEAPFILE, $VERBOSE) || ( $EXPIRES lt ( $PREFETCH * 86400 + time() ) )) {
329     my $TRY = 0;
330     my $ff = File::Fetch->new(uri => $LEAPSRC) || die "Fetch failed.\n";
331     while (1) {
332         ++$TRY;
333         logger("info", "Attempting download from $LEAPSRC, try $TRY..")
334             if ($VERBOSE ne "");
335         my $where = $ff->fetch( to => '/tmp' );
336
337         if ($where) {
338             logger("info", "Download of $LEAPSRC succeeded");
339
340             if ( verifySHA($where, $VERBOSE )) {
341                 # There is no point in retrying, as the file on the
342                 # server is almost certainly corrupt.
343
344                 logger("warning", "Downloaded file $where rejected -- saved for diagnosis");
345                 exit 1;
346             }
347
348             # While the shell script version will set correct permissions
349             # on temporary file, for the perl version that's harder, so
350             # for now at least one should run this script as the
351             # appropriate user.
352
353             # REFFILE="$LEAPFILE"
354             # if [ ! -f $LEAPFILE ]; then
355             #   logger "notice" "$LEAPFILE was missing, creating new copy - check permissions"
356             #   touch $LEAPFILE
357             #   # Can't copy permissions from old file, copy from NTPCONF instead
358             #   REFFILE="$NTPCONF"
359             # fi
360             # chmod --reference $REFFILE $TMPFILE
361             # chown --reference $REFFILE $TMPFILE
362             # ( which selinuxenabled && selinuxenabled && which chcon ) >/dev/null 2>&1
363             # if  [ $? == 0 ] ; then
364             #     chcon --reference $REFFILE $TMPFILE
365             # fi
366
367             # Replace current file with validated new one
368
369             if ( move $where, $LEAPFILE ) {
370                 logger("notice", "Installed new $LEAPFILE from $LEAPSRC");
371             } else {
372                 logger("error", "Install $where => $LEAPFILE failed -- saved for diagnosis: $!");
373                 exit 1;
374             }
375
376             # Restart NTP (or whatever else is specified)
377
378             if ( $RESTART ne "" ) {
379                 if ( $VERBOSE ne "" ) {
380                     logger("info", "Attempting restart action: $RESTART");
381                 }
382
383 # XXX
384                 #R="$( 2>&1 $RESTART )"
385                 #if [ $? -eq 0 ]; then
386                 #    logger "notice" "Restart action succeeded"
387                 #    if [ -n "$VERBOSE" -a -n "$R" ]; then
388                 #       logger "info" "$R"
389                 #    fi
390                 #else
391                 #    logger "error" "Restart action failed"
392                 #    if [ -n "$R" ]; then
393                 #       logger "error" "$R"
394                 #    fi
395                 #    exit 2
396                 #fi
397             }
398             exit 0;
399         }
400
401         # Failed to download.  See about trying again
402
403         # rm -f $TMPFILE
404         if ( $TRY ge $MAXTRIES ) {
405             last;
406         }
407         if ( $VERBOSE ne "" ) {
408             logger("info", "Waiting $INTERVAL minutes before retrying...");
409         }
410         sleep $INTERVAL * 60 ;
411     }
412
413     # Failed and out of retries
414
415     logger("warning", "Download from $LEAPSRC failed after $TRY attempts");
416     exit 1;
417 }
418
419 print "FORCE is <$FORCE>\n";
420 print "verifySHA is " . verifySHA($LEAPFILE, "") . "\n";
421 print "EXPIRES <$EXPIRES>  vs ". ( $PREFETCH * 86400 + time() ) . "\n";
422
423 logger("info", "Not time to replace $LEAPFILE");
424
425 exit 0;
426
427 # EOF