/[pdpsoft]/nl.nikhef.pdp.fetchcrl/trunk/TrustAnchor.pm
ViewVC logotype

Contents of /nl.nikhef.pdp.fetchcrl/trunk/TrustAnchor.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3107 - (show annotations) (download) (as text)
Fri Sep 9 15:32:11 2016 UTC (5 years, 1 month ago) by davidg
File MIME type: application/x-perl
File size: 27539 byte(s)
Add post-exec capability

1 #
2 # @(#)$Id$
3 #
4 # ###########################################################################
5 #
6 #
7 package TrustAnchor;
8 use strict;
9 use File::Basename;
10 use LWP;
11 require ConfigTiny and import ConfigTiny unless defined &ConfigTiny::new;
12 require CRL and import CRL unless defined &CRL::new;
13 require base64 and import base64 unless defined &base64::b64encode;
14 use vars qw/ $log $cnf /;
15
16 sub new {
17 my $obref = {}; bless $obref;
18 my $self = shift;
19 $self = $obref;
20 my $name = shift;
21
22 $self->{"infodir"} = $cnf->{_}->{infodir};
23 $self->{"suffix"} = "info";
24
25 $self->loadAnchor($name) if defined $name;
26
27 return $self;
28 }
29
30 sub saveLogMode($) {
31 my $self = shift;
32 return 0 unless defined $self;
33 $self->{"preserve_warnings"} = $::log->getwarnings;
34 $self->{"preserve_errors"} = $::log->geterrors;
35 return 1;
36 }
37
38 sub setLogMode($) {
39 my $self = shift;
40 return 0 unless defined $self;
41 $self->{"nowarnings"} and $::log->setwarnings(0);
42 $self->{"noerrors"} and $::log->seterrors(0);
43 return 1;
44 }
45
46 sub restoreLogMode($) {
47 my $self = shift;
48 return 0 unless defined $self;
49 (defined $self->{"preserve_warnings"} and defined $self->{"preserve_errors"})
50 or die "Internal error: restoreLogMode called without previous save\n";
51 $::log->setwarnings($self->{"preserve_warnings"});
52 $::log->seterrors($self->{"preserve_errors"});
53 return 1;
54 }
55
56 sub getInfodir($$) {
57 my $self = shift;
58 my ($path) = shift;
59 return 0 unless defined $self;
60
61 return $self->{"infodir"};
62 }
63
64 sub setInfodir($$) {
65 my $self = shift;
66 my ($path) = shift;
67 return 0 unless defined $path and defined $self;
68
69 -e $path or
70 $::log->err("setInfodir: path $path does not exist") and return 0;
71 -d $path or
72 $::log->err("setInfodir: path $path is not a directory") and return 0;
73
74 $self->{"infodir"} = $path;
75
76 return 1;
77 }
78
79
80 sub loadAnchor($$) {
81 my $self = shift;
82 my ($name) = @_;
83 return 0 unless defined $name;
84
85 $::log->verb(1,"Initializing trust anchor $name");
86
87 my ( $basename, $path, $suffix) = fileparse($name,('.info','.crl_url'));
88
89 $path = "" if $path eq "./" and substr($name,0,length($path)) ne $path ;
90
91 $::log->err("Invalid name of trust anchor $name") and return 0
92 unless $basename;
93
94 $self->{"infodir"} = $path if $path ne "";
95 $path = $self->{"infodir"} || "";
96 $path and $path .= "/" unless $path =~ /\/$/;
97
98 if ( $suffix ) {
99 -e $name or
100 $::log->err("Trust anchor data $name not found") and return 0;
101 } else { # try and guess which suffix should be used
102 ($suffix eq "" and -e $path.$basename.".info" ) and $suffix = ".info";
103 ($suffix eq "" and -e $path.$basename.".crl_url" ) and $suffix = ".crl_url";
104 $suffix or
105 $::log->err("No trust anchor metadata for $basename in '$path'")
106 and return 0;
107 }
108
109 if ( $suffix eq ".crl_url" ) {
110
111 $self->{"alias"} = $basename;
112 @{$self->{"crlurls"}} = ();
113 open CRLURL,"$path$basename$suffix" or
114 $::log->err("Error reading crl_url $path$basename$suffix: $!") and return 0;
115 $self->{"filename"} = "$path$basename$suffix";
116 my $urllist;
117 while (<CRLURL>) {
118 /^\s*([^#\n]+).*$/ and my $url = $1 or next;
119 $url =~ s/\s*$//; # trailing whitespace is ignored
120
121 $url =~ /^\w+:\/\/.*$/ or
122 $::log->err("File $path$basename$suffix contains a non-URL entry")
123 and close CRLURL and return 0;
124
125 $urllist and $urllist .= "\001";
126 $urllist .= $url;
127 }
128 close CRLURL;
129 push @{$self->{"crlurls"}}, $urllist;
130 $self->{"status"} ||= "unknown";
131
132 } else {
133
134 my $info = ConfigTiny->new();
135 $info->read( $path . $basename . $suffix ) or
136 $::log->err("Error reading info $path$basename$suffix", $info->errstr)
137 and return 0;
138 $self->{"filename"} = "$path$basename$suffix";
139
140 $info->{_}->{"crl_url"} and $info->{_}->{"crl_url.0"} and
141 $::log->err("Invalid info for $basename: crl_url and .0 duplicate") and
142 return 0;
143 $info->{_}->{"crl_url"} and
144 $info->{_}->{"crl_url.0"} = $info->{_}->{"crl_url"};
145
146 # only do something when there is actually a CRL to process
147 $info->{_}->{"crl_url.0"} or
148 $::log->verb(1,"Trust anchor $basename does not have a CRL") and return 0;
149
150 $info->{_}->{"alias"} or
151 $::log->err("Invalid info for $basename: no alias") and
152 return 0;
153 $self->{"alias"} = $info->{_}->{"alias"};
154
155 @{$self->{"crlurls"}} = ();
156 for ( my $i=0 ; defined $info->{_}{"crl_url.".$i} ; $i++ ) {
157 $info->{_}{"crl_url.".$i} =~ s/[;\s]+/\001/g;
158 $info->{_}{"crl_url.".$i} =~ s/^\s*([^\s]*)\s*$/$1/;
159
160 $info->{_}{"crl_url.".$i} =~ /^\w+:\/\// or
161 $::log->err("File $path$basename$suffix contains a non-URL entry",
162 $info->{_}{"crl_url.".$i})
163 and close CRLURL and return 0;
164
165 push @{$self->{"crlurls"}} , $info->{_}{"crl_url.".$i};
166 }
167
168 foreach my $field ( qw/email ca_url status/ ) {
169 $self->{$field} = $info->{_}->{$field} if $info->{_}->{$field};
170 }
171
172 # status of CA is only knwon for info-file based CAs
173 $self->{"status"} ||= "local";
174
175 }
176
177 # preserve basename of file for config and diagnostics
178 $self->{"anchorname"} = $basename;
179
180 #
181 # set defaults for common values
182 foreach my $key ( qw /
183 prepend_url postpend_url agingtolerance
184 httptimeout proctimeout
185 nowarnings noerrors nocache http_proxy
186 nametemplate_der nametemplate_pem
187 cadir catemplate statedir
188 / ) {
189 $self->{$key} = $self->{$key} ||
190 $::cnf->{$self->{"alias"}}->{$key} ||
191 $::cnf->{$self->{"anchorname"}}->{$key} ||
192 $::cnf->{_}->{$key} or delete $self->{$key};
193 defined $self->{$key} and do {
194 $self->{$key} =~ s/\@ANCHORNAME\@/$self->{"anchorname"}/g;
195 $self->{$key} =~ s/\@STATUS\@/$self->{"status"}/g;
196 $self->{$key} =~ s/\@ALIAS\@/$self->{"alias"}/g;
197 };
198 }
199 # reversible toggle options
200 foreach my $key ( qw / warnings errors cache / ) {
201 delete $self->{"no$key"} if $::cnf->{$self->{"alias"}}->{$key} or
202 $::cnf->{$self->{"anchorname"}}->{$key} or
203 $::cnf->{_}->{$key};
204 }
205 foreach my $key ( qw / nohttp_proxy noprepend_url nopostpend_url
206 nostatedir / ) {
207 (my $nokey = $key) =~ s/^no//;
208 delete $self->{"$nokey"} if $::cnf->{$self->{"alias"}}->{$key} or
209 $::cnf->{$self->{"anchorname"}}->{$key} or
210 $::cnf->{_}->{$key};
211 }
212
213 # overriding of the URLs (alias takes precedence over anchorname
214 foreach my $section ( qw / anchorname alias / ) {
215 my $i = 0;
216 while ( defined ($::cnf->{$self->{$section}}->{"crl_url.".$i}) ) {
217 my $urls;
218 ($urls=$::cnf->{$self->{$section}}->{"crl_url.".$i} )=~s/[;\s]+/\001/g;
219 ${$self->{"crlurls"}}[$i] = $urls;
220 $i++;
221 }
222 }
223
224 # templates to construct a CA name may still have other separators
225 $self->{"catemplate"} =~ s/[;\s]+/\001/g;
226
227 # select only http/https/ftp/file URLs
228 # also transform the URLs using the base patterns and prepend any
229 # local URL patterns (@ANCHORNAME@, @ALIAS@, and @R@)
230 for ( my $i=0; $i <= $#{$self->{"crlurls"}} ; $i++ ) {
231 my $urlstring = @{$self->{"crlurls"}}[$i];
232 my @urls = split(/\001/,$urlstring);
233 $urlstring="";
234 foreach my $url ( @urls ) {
235 if ( $url =~ /^(http:|https:|ftp:|file:)/ ) {
236 $urlstring.="\001" if $urlstring; $urlstring.=$url;
237 } else {
238 $::log->verb(0,"URL $url in $basename$suffix unsupported, ignored");
239 }
240 }
241 if ( my $purl = $self->{"prepend_url"} ) {
242 $purl =~ s/\@R\@/$i/g;
243 $urlstring = join "\001" , $purl , $urlstring;
244 }
245 if ( my $purl = $self->{"postpend_url"} ) {
246 $purl =~ s/\@R\@/$i/g;
247 $urlstring = join "\001" , $urlstring, $purl;
248 }
249 if ( ! $urlstring ) {
250 $::log->err("No usable CRL URLs for",$self->getAnchorName);
251 $self->{"crlurls"}[$i] = "";
252 } else {
253 $self->{"crlurls"}[$i] = $urlstring;
254 }
255 }
256
257 return 1;
258 }
259
260 sub getAnchorName($) {
261 my $self = shift;
262 return ($self->{"anchorname"} || undef);
263 }
264
265 sub printAnchorName($) {
266 my $self = shift;
267 print "" . ($self->{"anchorname"} || "undefined") ."\n";
268 }
269
270 sub displayAnchorName($) {
271 my $self = shift;
272 return ($self->{"anchorname"} || "undefined");
273 }
274
275 sub loadCAfiles($) {
276 my $self = shift;
277 my $idx = 0;
278
279 # try to find a CA dir, whatever it takes, almost
280 my $cadir = $self->{"cadir"} || $self->{"infodir"};
281
282 -d $cadir or
283 $::log->err("CA directory",$cadir,"does not exist") and
284 return 0;
285
286 # add @HASH@ support, inducing a file read and fork, only if really needed
287 my $crlhash;
288 if ( $self->{"catemplate"} =~ /\@HASH\@/ ) {
289 $self->{"crl"}[0]{"data"} ne "" or
290 $::log->err("CA name template contains HASH, but no CRL ".
291 "could be loaded in time for ".$self->displayAnchorName) and
292 return 0;
293 my $probecrl = CRL->new(undef,$self->{"crl"}[0]{"data"});
294 $crlhash = $probecrl->getAttribute("hash");
295 $::log->verb(3,"Inferred CA template HASH ".($crlhash?$crlhash:"failed").
296 " for ".$self->displayAnchorName);
297 }
298
299 @{$self->{"cafile"}} = ();
300 do {
301 my $cafile;
302
303 foreach my $catpl ( split /\001/, $self->{"catemplate"} ) {
304 $catpl =~ s/\@R\@/$idx/g;
305 $catpl =~ s/\@HASH\@/$crlhash/g;
306 -e $cadir.'/'.$catpl and
307 $cafile = $cadir.'/'.$catpl and last;
308 }
309 defined $cafile or do {
310 $idx or do $::log->err("Cannot find any CA for",
311 $self->{"alias"},"in",$cadir);
312 return $idx?1:0;
313 };
314 # is the new one any different from the previous (i.e. is the CA indexed?)
315 $#{$self->{"cafile"}} >= 0 and
316 $cafile eq $self->{"cafile"}[$#{$self->{"cafile"}}] and return 1;
317 push @{$self->{"cafile"}}, $cafile;
318 $::log->verb(3,"Added CA file $idx: $cafile");
319 } while(++$idx);
320 return 0; # you never should come here
321 }
322
323
324 sub loadState($$) {
325 my $self = shift;
326 my $fallbackmode = shift;
327
328 $self->{"crlurls"} or
329 $::log->err("loading state for uninitialised list of CRLs") and return 0;
330 $self->{"alias"} or
331 $::log->err("loading state for uninitialised trust anchor") and return 0;
332
333 for ( my $i = 0; $i <= $#{$self->{"crlurls"}} ; $i++ ) { # all indices
334 if ( $self->{"statedir"} and
335 -e $self->{"statedir"}.'/'.$self->{"alias"}.'.'.$i.'.state'
336 ) {
337 my $state = ConfigTiny->new();
338 $state->read($self->{"statedir"}.'/'.$self->{"alias"}.'.'.$i.'.state')
339 or $::log->err("Cannot read existing state file",
340 $self->{"statedir"}.'/'.$self->{"alias"}.'.$i.state',
341 " - ",$state->errstr) and return 0;
342 foreach my $key ( keys %{$state->{$self->{"alias"}}} ) {
343 $self->{"crl"}[$i]{"state"}{$key} = $state->{$self->{"alias"}}->{$key};
344 }
345 }
346
347 # fine, but we should find at least an mtime if at all possible
348 # make sure it is there:
349 # try to retrieve state from installed files in @output_
350 # where the first look-alike CRL will win. NSS databases
351 # are NOT supported for this heuristic
352 if ( ! defined $self->{"crl"}[$i]{"state"}{"mtime"} ) {
353 my $mtime;
354 STATEHUNT: foreach my $output ( ( $::cnf->{_}->{"output"},
355 $::cnf->{_}->{"output_der"}, $::cnf->{_}->{"output_pem"},
356 $::cnf->{_}->{"output_nss"}, $::cnf->{_}->{"output_openssl"}) ) {
357 defined $output and $output or next;
358 foreach my $ref (
359 $self->{"nametemplate_der"},
360 $self->{"nametemplate_pem"},
361 $self->{"alias"}.".r\@R\@",
362 $self->{"anchorname"}.".r\@R\@",
363 ) {
364 next unless $ref;
365 my $file = $ref; # copy, not to change original
366 $file =~ s/\@R\@/$i/g;
367 $file = join "/", $output, $file;
368 next if ! -e $file;
369 $mtime = (stat(_))[9];
370 last STATEHUNT;
371 }
372 }
373 $::log->verb(3,"Inferred mtime for",$self->{"alias"},"is",$mtime) if $mtime;
374 $self->{"crl"}[$i]{"state"}{"mtime"} = $mtime if $mtime;
375 }
376
377 # as a last resort, set mtime to curren time
378 $self->{"crl"}[$i]{"state"}{"mtime"} ||= time;
379
380 }
381 return 1;
382 }
383
384 sub saveState($$) {
385 my $self = shift;
386 my $fallbackmode = shift;
387
388 $self->{"statedir"} and -d $self->{"statedir"} and -w $self->{"statedir"} or
389 return 0;
390
391 $self->{"crlurls"} or
392 $::log->err("loading state for uninitialised list of CRLs") and return 0;
393 $self->{"alias"} or
394 $::log->err("loading state for uninitialised trust anchor") and return 0;
395
396 # of state, mtime is set based on CRL write in $output and filled there
397 for ( my $i = 0; $i <= $#{$self->{"crlurls"}} ; $i++ ) { # all indices
398 if ( defined $self->{"statedir"} and
399 -d $self->{"statedir"}
400 ) {
401 my $state = ConfigTiny->new;
402 foreach my $key ( keys %{$self->{"crl"}[$i]{"state"}} ) {
403 $state->{$self->{"alias"}}->{$key} = $self->{"crl"}[$i]{"state"}{$key};
404 }
405 $state->write(
406 $self->{"statedir"}.'/'.$self->{"alias"}.'.'.$i.'.state' );
407 $::log->verb(5,"State saved in",
408 $self->{"statedir"}.'/'.$self->{"alias"}.'.'.$i.'.state');
409 }
410
411 }
412 return 1;
413 }
414
415 sub retrieveHTTP($$) {
416 my $self = shift;
417 my $idx = shift;
418 my $url = shift;
419 my %metadata;
420 my $data;
421
422 $url =~ /^(http:|https:|ftp:)/ or die "retrieveHTTP: non-http URL $url\n";
423
424 $::log->verb(3,"Downloading data from $url");
425 my $ua = LWP::UserAgent->new;
426 $ua->agent('fetch-crl/'.$::cnf->{_}->{version} . ' ('.
427 $ua->agent . '; '.$::cnf->{_}->{packager} . ')'
428 );
429 $ua->timeout($self->{"httptimeout"});
430 $ua->use_eval(0);
431 if ( $self->{"http_proxy"} ) {
432 if ( $self->{"http_proxy"} =~ /^ENV/i ) {
433 $ua->env_proxy();
434 } else {
435 $ua->proxy("http", $self->{"http_proxy"});
436 }
437 }
438 # set request cache control if specified as valid in config
439 if ( defined $::cnf->{_}->{cache_control_request} ) {
440 $::log->verb(5,"Setting request cache-control to ".
441 $::cnf->{_}->{cache_control_request});
442 if ( $::cnf->{_}->{cache_control_request} =~ /^\d+$/ ) {
443 $ua->default_header('Cache-control' =>
444 "max-age=".$::cnf->{_}->{cache_control_request} );
445 } else {
446 die "Request cache control is invalid (not a number)\n";
447 }
448 }
449
450 # see with a HEAD request if we can get by with old data
451 # but to assess that we need Last-Modified from the previous request
452 # (so if the CA did not send that: too bad)
453 if ( $self->{"crl"}[$idx]{"state"}{"lastmod"} and
454 $self->{"crl"}[$idx]{"state"}{"b64data"}
455 ) {
456 $::log->verb(4,"Lastmod set to",$self->{"crl"}[$idx]{"state"}{"lastmod"});
457 $::log->verb(4,"Attemping HEAD retrieval of $url");
458
459 my $response;
460 eval {
461 local $SIG{ALRM}=sub{die "timed out after ".$self->{"httptimeout"}."s\n";};
462 alarm $self->{"httptimeout"};
463 $response = $ua->head($url);
464 alarm 0;
465 };
466 alarm 0; # make sure the alarm stops ticking, regardless of the eval
467
468 if ( $@ ) { # died, alarm hit: server bad, so try next URL
469 $::log->verb(2,"HEAD error $url:", $@);
470 return undef;
471 }
472
473 # try using cached data if it is fresh
474 if ( ( ! $@ ) and
475 $response->is_success and
476 $response->header("Last-Modified") ) {
477
478 my $lastmod = HTTP::Date::str2time($response->header("Last-Modified"));
479 if ( $lastmod == $self->{"crl"}[$idx]{"state"}{"lastmod"}) {
480 $::log->verb(4,"HEAD lastmod unchanged, using cache");
481 $data = base64::b64decode($self->{"crl"}[$idx]{"state"}{"b64data"});
482 %metadata = (
483 "freshuntil" => $response->fresh_until(heuristic_expiry=>0)||time,
484 "lastmod" => $self->{"crl"}[$idx]{"state"}{"lastmod"} || time,
485 "sourceurl" => $self->{"crl"}[$idx]{"state"}{"sourceurl"} || $url
486 );
487 return ($data,%metadata) if wantarray;
488 return $data;
489
490 } elsif ( $lastmod < $self->{"crl"}[$idx]{"state"}{"lastmod"} ) {
491 # retrieve again, but print warning abount this wierd behaviour
492 $::log->warn("Retrieved HEAD Last-Modified is older than cache: ".
493 "cache invalidated, GET issued");
494 }
495 }
496 }
497
498 # try get if head fails, there was no cache, cache disabled or invalidated
499
500 my $response;
501 eval {
502 local $SIG{ALRM}=sub{die "timed out after ".$self->{"httptimeout"}."s\n";};
503 alarm $self->{"httptimeout"};
504 $ua->parse_head(0);
505 $response = $ua->get($url);
506 alarm 0;
507 };
508 alarm 0; # make sure the alarm stops ticking, regardless of the eval
509
510 if ( $@ ) {
511 chomp($@);
512 $::log->verb(0,"Download error $url:", $@);
513 return undef;
514 }
515
516 if ( ! $response->is_success ) {
517 $::log->verb(0,"Download error $url:",$response->status_line);
518 return undef;
519 }
520
521 $data = $response->content;
522
523 $metadata{"freshuntil"}=$response->fresh_until(heuristic_expiry=>0)||time;
524 if ( my $lastmod = $response->header("Last-Modified") ) {
525 $metadata{"lastmod"} = HTTP::Date::str2time($lastmod);
526 }
527 $metadata{"sourceurl"} = $url;
528
529 return ($data,%metadata) if wantarray;
530 return $data;
531 }
532
533 sub retrieveFile($$) {
534 my $self = shift;
535 my $idx = shift;
536 my $url = shift;
537 $url =~ /^file:\/*(\/.*)$/ or die "retrieveFile: non-file URL $url\n";
538 $::log->verb(4,"Retrieving data from $url");
539
540 # for files the previous state does not matter, we retrieve it
541 # anyway
542
543 my $data;
544 {
545 open CRLFILE,$1 or do {
546 $! = "Cannot open $1: $!";
547 return undef;
548 };
549 binmode CRLFILE;
550 local $/;
551 $data = <CRLFILE>;
552 close CRLFILE;
553 }
554
555 my %metadata;
556 $metadata{"lastmod"} = (stat($1))[9];
557 $metadata{"freshuntil"} = time;
558 $metadata{"sourceurl"} = $url;
559
560 return ($data,%metadata) if wantarray;
561 return $data;
562 }
563
564 sub retrieve($) {
565 my $self = shift;
566
567 $self->{"crlurls"} or
568 $::log->err("Retrieving uninitialised list of CRL URLs") and return 0;
569
570 $::log->verb(2,"Retrieving CRLs for",$self->{"alias"});
571
572 for ( my $i = 0; $i <= $#{$self->{"crlurls"}} ; $i++ ) { # all indices
573 my ($result,%response);
574
575 $::log->verb(3,"Retrieving CRL for",$self->{"alias"},"index $i");
576
577 # within the list of CRL URLs for a specific index, all entries
578 # are considered equivalent. I.e., if we get one, the metadata will
579 # be used for all (like Last-Modified, and cache control data)
580
581 # if we have a cached piece of fresh data, return that one
582 # and make sure the nextupdate in the CRL itself outlives claimed freshness
583 if ( !$self->{"nocache"} and
584 ($self->{"crl"}[$i]{"state"}{"freshuntil"} || 0) > time and
585 ($self->{"crl"}[$i]{"state"}{"nextupdate"} || time) >= time and
586 ($self->{"crl"}[$i]{"state"}{"nextupdate"} || 0) >=
587 ($self->{"crl"}[$i]{"state"}{"freshuntil"} || 0) and
588 $self->{"crl"}[$i]{"state"}{"b64data"} ) {
589 $::log->verb(3,"Using cached content for",$self->{"alias"},"index",$i);
590 $::log->verb(4,"Content dated",
591 scalar gmtime($self->{"crl"}[$i]{"state"}{"lastmod"}),
592 "valid until",
593 scalar gmtime($self->{"crl"}[$i]{"state"}{"freshuntil"}),
594 "UTC");
595 $result = base64::b64decode($self->{"crl"}[$i]{"state"}{"b64data"});
596 %response = (
597 "freshuntil" => $self->{"crl"}[$i]{"state"}{"freshuntil"} || time,
598 "lastmod" => $self->{"crl"}[$i]{"state"}{"lastmod"} || time,
599 "sourceurl" => $self->{"crl"}[$i]{"state"}{"sourceurl"} || "null:"
600 );
601 } else {
602 foreach my $url ( split(/\001/,$self->{"crlurls"}[$i]) ) {
603 # of these, the first one wins
604 $url =~ /^(http:|https:|ftp:)/ and
605 ($result,%response) = $self->retrieveHTTP($i,$url);
606 $url =~ /^(file:)/ and
607 ($result,%response) = $self->retrieveFile($i,$url);
608 last if $result;
609 }
610 }
611
612 # check if result is there, otherwise invoke agingtolerance clause
613 # before actually raising this as an error
614 # note that agingtolerance stats counting only AFTER the freshness
615 # of the cache control directives has passed ...
616
617 if ( ! $result ) {
618
619 $::log->verb(1,"CRL retrieval for",
620 $self->{"alias"},($i?"[$i] ":"")."failed from all URLs");
621
622 if ( $self->{"agingtolerance"} && $self->{"crl"}[$i]{"state"}{"mtime"} ) {
623 if ( ( time - $self->{"crl"}[$i]{"state"}{"mtime"} ) <
624 3600*$self->{"agingtolerance"}) {
625 $::log->warn("CRL retrieval for",
626 $self->{"alias"},($i?"[$i] ":"")."failed,",
627 int((3600*$self->{"agingtolerance"}+
628 $self->{"crl"}[$i]{"state"}{"mtime"}-
629 time )/3600).
630 " left of ".$self->{"agingtolerance"}."h, retry later.");
631 } else {
632 $::log->retr_err("CRL retrieval for",
633 $self->{"alias"},($i?"[$i] ":"")."failed.",
634 $self->{"agingtolerance"}."h grace expired.",
635 "CRL not updated");
636 }
637 } else { # direct errors, no tolerance anymore
638 $::log->retr_err("CRL retrieval for",
639 $self->{"alias"},($i?"[$i] ":"")."failed,",
640 "CRL not updated");
641 }
642 next; # next subindex CRL for same CA, no further action on this one
643 }
644
645 # now data for $i is loaded in $result;
646 # for freshness checks, take a sum (SysV style)
647 my $sum = unpack("%32C*",$result) % 65535;
648
649 $::log->verb(4,"Got",length($result),"bytes of data (sum=$sum)");
650
651 $self->{"crl"}[$i]{"data"} = $result;
652 $self->{"crl"}[$i]{"state"}{"alias"} = $self->{"alias"};
653 $self->{"crl"}[$i]{"state"}{"index"} = $i;
654 $self->{"crl"}[$i]{"state"}{"sum"} = $sum;
655 ($self->{"crl"}[$i]{"state"}{"b64data"} =
656 base64::b64encode($result)) =~ s/\s+//gm;
657
658 $self->{"crl"}[$i]{"state"}{"retrievaltime"} = time;
659 $self->{"crl"}[$i]{"state"}{"sourceurl"} = $response{"sourceurl"}||"null:";
660 $self->{"crl"}[$i]{"state"}{"freshuntil"} = $response{"freshuntil"}||time;
661 $self->{"crl"}[$i]{"state"}{"lastmod"} = $response{"lastmod"}||time;
662
663 }
664 return 1;
665 }
666
667 sub verifyAndConvertCRLs($) {
668 my $self = shift;
669 $self->{"crlurls"} or
670 $::log->err("Verifying uninitialised list of CRLs impossible") and return 0;
671
672 # all CRLs must be valid in order to proceed
673 # or we would end up shifting the relative ordering around and
674 # possibly creatiing holes (or overwriting good local copies of
675 # CRLs that have gone bad on the remote end
676
677 for ( my $i = 0; $i <= $#{$self->{"crlurls"}} ; $i++ ) { # all indices
678 $self->{"crlurls"}[$i] or
679 $::log->verb(3,"CRL",$self->getAnchorName."/".$i,"ignored (no valid URL)")
680 and next;
681 $self->{"crl"}[$i]{"data"} or
682 $::log->verb(3,"CRL",$self->getAnchorName."/".$i,"ignored (no new data)")
683 and next;
684 $::log->verb(4,"Verifying CRL $i for",$self->getAnchorName);
685
686 my $crl = CRL->new($self->getAnchorName."/$i",$self->{"crl"}[$i]{"data"});
687 my @verifyMessages= $crl->verify(@{$self->{"cafile"}});
688
689 # do additional checks on correlation between download and current
690 # lastUpdate of current file? have to guess the current file
691 # unless we are stateful!
692 my $oldlastupdate = $self->{"crl"}[$i]{"state"}{"lastupdate"} || undef;
693 $oldlastupdate or do {
694 $::log->verb(6,"Attempting to extract lastUpdate of previous D/L");
695 CRLSTATEHUNT: foreach my $output ( @{$::cnf->{_}->{"output_"}} ,
696 $self->{"infodir"}
697 ) {
698 foreach my $file (
699 $self->{"nametemplate_der"},
700 $self->{"nametemplate_pem"},
701 $self->{"alias"}.".r\@R\@",
702 $self->{"anchorname"}.".r\@R\@",
703 ) {
704 next unless $file;
705 (my $thisfile = $file ) =~ s/\@R\@/$i/g;
706 $thisfile = join "/", $output, $thisfile;
707 $::log->verb(6,"Trying guess $file for old CRL");
708 next if ! -e $thisfile;
709 my $oldcrldata; {
710 open OCF,$thisfile and do {
711 binmode OCF;
712 local $/;
713 $oldcrldata = <OCF>;
714 close OCF;
715 }
716 }
717 my $oldcrl = CRL->new($thisfile,$oldcrldata);
718 $oldlastupdate = $oldcrl->getLastUpdate;
719 last CRLSTATEHUNT;
720 }
721 }
722 $::log->verb(3,"Inferred lastupdate for",$self->{"alias"},"is",
723 $oldlastupdate) if $oldlastupdate;
724 };
725
726 if ( ! $crl->getLastUpdate ) {
727 push @verifyMessages,"downloaded CRL lastUpdate could not be derived";
728 } elsif ( $oldlastupdate and ($crl->getLastUpdate < $oldlastupdate) and
729 ($self->{"crl"}[$i]{"state"}{"mtime"} <= time)
730 ) {
731 push @verifyMessages,"downloaded CRL lastUpdate predates installed CRL,",
732 "and current version has sane timestamp";
733 } elsif ( defined $oldlastupdate and $oldlastupdate > time ) {
734 $::log->warn($self->{"anchorname"}."/$i:","replaced with downloaded CRL",
735 "since current one has lastUpdate in the future");
736 }
737
738 $#verifyMessages >= 0 and do {
739 $::log->retr_err("CRL verification failed for",$self->{"anchorname"}."/$i",
740 "(".$self->{"alias"}.")");
741 foreach my $m ( @verifyMessages ) {
742 $::log->verb(0,$self->{"anchorname"}."/$i:",$m);
743 }
744 return 0;
745 };
746
747 $self->{"crl"}[$i]{"pemdata"} = $crl->getPEMdata();
748 foreach my $key ( qw/ lastupdate nextupdate sha1fp issuer / ) {
749 $self->{"crl"}[$i]{"state"}{$key} = $crl->getAttribute($key) || "";
750 }
751
752
753 # issue a low-level warning in case the cache control headers from
754 # the CA (or its CDN) are bugus, i.e. the CRL wille expire before the
755 # cache does. Don't log at warning, since the site cannot fix this
756 if ( defined ($self->{"crl"}[$i]{"state"}{"freshuntil"}) and
757 ( $self->{"crl"}[$i]{"state"}{"freshuntil"} >
758 ( $self->{"crl"}[$i]{"state"}{"nextupdate"} +
759 $::cnf->{_}->{expirestolerance} )
760 )
761 ) {
762 $::log->verb(1,"Cache control headers for CA ".$self->{"alias"}." at ".
763 "URL ".$self->{"crl"}[$i]{"state"}{"sourceurl"}." have apparent ".
764 "freshness ".sprintf("%.1f",($self->{"crl"}[$i]{"state"}{"freshuntil"}-
765 $self->{"crl"}[$i]{"state"}{"nextupdate"})/3600).
766 "hrs beyond CRL expiration nextUpdate. Reset freshness from ".
767 gmtime($self->{"crl"}[$i]{"state"}{"freshuntil"})." UTC to ".
768 $::cnf->{_}->{expirestolerance}." second before nextUpdate at ".
769 gmtime($self->{"crl"}[$i]{"state"}{"nextupdate"})." UTC.");
770 $self->{"crl"}[$i]{"state"}{"freshuntil"} =
771 $self->{"crl"}[$i]{"state"}{"nextupdate"} -
772 $::cnf->{_}->{expirestolerance};
773 }
774
775 # limit maximum freshness period to compensate for CAs that overdo it
776 if ( defined ($self->{"crl"}[$i]{"state"}{"freshuntil"}) and
777 $self->{"crl"}[$i]{"state"}{"freshuntil"} >
778 (time + $::cnf->{_}->{maxcachetime}) ) {
779 $self->{"crl"}[$i]{"state"}{"freshuntil"} =
780 time+$::cnf->{_}->{maxcachetime};
781 $::log->verb(1,"Cache state freshness expiry for CA ".$self->{"alias"}.
782 " reset to at most ".
783 sprintf("%.1f",$::cnf->{_}->{maxcachetime}/3600.).
784 "hrs beyond current time (".
785 gmtime($self->{"crl"}[$i]{"state"}{"freshuntil"})." UTC)");
786 }
787
788 }
789 return 1;
790 }
791
792
793 1;
794

Properties

Name Value
svn:keywords Id

grid.support@nikhef.nl
ViewVC Help
Powered by ViewVC 1.1.28