/[pdpsoft]/nl.nikhef.pdp.fetchcrl/tags/fetch-crl-3.0.17-2/TrustAnchor.pm
ViewVC logotype

Annotation of /nl.nikhef.pdp.fetchcrl/tags/fetch-crl-3.0.17-2/TrustAnchor.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2805 - (hide annotations) (download) (as text)
Tue Nov 10 16:07:33 2015 UTC (6 years ago) by davidg
Original Path: nl.nikhef.pdp.fetchcrl/trunk/TrustAnchor.pm
File MIME type: application/x-perl
File size: 27437 byte(s)
rescoe cnf, oops

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

Properties

Name Value
svn:keywords Id

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