/[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 3178 - (show annotations) (download) (as text)
Tue Apr 11 07:16:27 2017 UTC (4 years, 6 months ago) by davidg
File MIME type: application/x-perl
File size: 28334 byte(s)
Qualify socket error messages at verb=4 and print only first error (bugzilla #29)

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 chomp($@);
470 my $shorterror = $@; $shorterror =~ s/\n.*$//gs;
471 $::log->verb(2,"HEAD error $url:", $shorterror);
472 # underlying socket library may be verybose - filter and qualify messages
473 if ( $shorterror ne $@ ) {
474 foreach my $errorline ( split(/\n/,$@) ) {
475 chomp($errorline); $errorline eq $shorterror and next; # nodups
476 $errorline and $::log->verb(4,"HEAD error detail:", $errorline);
477 }
478 }
479 return undef;
480 }
481
482 # try using cached data if it is fresh
483 if ( ( ! $@ ) and
484 $response->is_success and
485 $response->header("Last-Modified") ) {
486
487 my $lastmod = HTTP::Date::str2time($response->header("Last-Modified"));
488 if ( $lastmod == $self->{"crl"}[$idx]{"state"}{"lastmod"}) {
489 $::log->verb(4,"HEAD lastmod unchanged, using cache");
490 $data = base64::b64decode($self->{"crl"}[$idx]{"state"}{"b64data"});
491 %metadata = (
492 "freshuntil" => $response->fresh_until(heuristic_expiry=>0)||time,
493 "lastmod" => $self->{"crl"}[$idx]{"state"}{"lastmod"} || time,
494 "sourceurl" => $self->{"crl"}[$idx]{"state"}{"sourceurl"} || $url
495 );
496 return ($data,%metadata) if wantarray;
497 return $data;
498
499 } elsif ( $lastmod < $self->{"crl"}[$idx]{"state"}{"lastmod"} ) {
500 # retrieve again, but print warning abount this wierd behaviour
501 $::log->warn("Retrieved HEAD Last-Modified is older than cache: ".
502 "cache invalidated, GET issued");
503 }
504 }
505 }
506
507 # try get if head fails, there was no cache, cache disabled or invalidated
508
509 my $response;
510 eval {
511 local $SIG{ALRM}=sub{die "timed out after ".$self->{"httptimeout"}."s\n";};
512 alarm $self->{"httptimeout"};
513 $ua->parse_head(0);
514 $response = $ua->get($url);
515 alarm 0;
516 };
517 alarm 0; # make sure the alarm stops ticking, regardless of the eval
518
519 if ( $@ ) {
520 chomp($@);
521 my $shorterror = $@; $shorterror =~ s/\n.*$//gs;
522 $::log->verb(0,"Download error $url:", $shorterror);
523 # underlying socket library may be verybose - filter and qualify messages
524 if ( $shorterror ne $@ ) {
525 foreach my $errorline ( split(/\n/,$@) ) {
526 chomp($errorline); $errorline eq $shorterror and next; # nodups
527 $errorline and $::log->verb(4,"Download error detail:", $errorline);
528 }
529 }
530 return undef;
531 }
532
533 if ( ! $response->is_success ) {
534 $::log->verb(0,"Download error $url:",$response->status_line);
535 return undef;
536 }
537
538 $data = $response->content;
539
540 $metadata{"freshuntil"}=$response->fresh_until(heuristic_expiry=>0)||time;
541 if ( my $lastmod = $response->header("Last-Modified") ) {
542 $metadata{"lastmod"} = HTTP::Date::str2time($lastmod);
543 }
544 $metadata{"sourceurl"} = $url;
545
546 return ($data,%metadata) if wantarray;
547 return $data;
548 }
549
550 sub retrieveFile($$) {
551 my $self = shift;
552 my $idx = shift;
553 my $url = shift;
554 $url =~ /^file:\/*(\/.*)$/ or die "retrieveFile: non-file URL $url\n";
555 $::log->verb(4,"Retrieving data from $url");
556
557 # for files the previous state does not matter, we retrieve it
558 # anyway
559
560 my $data;
561 {
562 open CRLFILE,$1 or do {
563 $! = "Cannot open $1: $!";
564 return undef;
565 };
566 binmode CRLFILE;
567 local $/;
568 $data = <CRLFILE>;
569 close CRLFILE;
570 }
571
572 my %metadata;
573 $metadata{"lastmod"} = (stat($1))[9];
574 $metadata{"freshuntil"} = time;
575 $metadata{"sourceurl"} = $url;
576
577 return ($data,%metadata) if wantarray;
578 return $data;
579 }
580
581 sub retrieve($) {
582 my $self = shift;
583
584 $self->{"crlurls"} or
585 $::log->err("Retrieving uninitialised list of CRL URLs") and return 0;
586
587 $::log->verb(2,"Retrieving CRLs for",$self->{"alias"});
588
589 for ( my $i = 0; $i <= $#{$self->{"crlurls"}} ; $i++ ) { # all indices
590 my ($result,%response);
591
592 $::log->verb(3,"Retrieving CRL for",$self->{"alias"},"index $i");
593
594 # within the list of CRL URLs for a specific index, all entries
595 # are considered equivalent. I.e., if we get one, the metadata will
596 # be used for all (like Last-Modified, and cache control data)
597
598 # if we have a cached piece of fresh data, return that one
599 # and make sure the nextupdate in the CRL itself outlives claimed freshness
600 if ( !$self->{"nocache"} and
601 ($self->{"crl"}[$i]{"state"}{"freshuntil"} || 0) > time and
602 ($self->{"crl"}[$i]{"state"}{"nextupdate"} || time) >= time and
603 ($self->{"crl"}[$i]{"state"}{"nextupdate"} || 0) >=
604 ($self->{"crl"}[$i]{"state"}{"freshuntil"} || 0) and
605 $self->{"crl"}[$i]{"state"}{"b64data"} ) {
606 $::log->verb(3,"Using cached content for",$self->{"alias"},"index",$i);
607 $::log->verb(4,"Content dated",
608 scalar gmtime($self->{"crl"}[$i]{"state"}{"lastmod"}),
609 "valid until",
610 scalar gmtime($self->{"crl"}[$i]{"state"}{"freshuntil"}),
611 "UTC");
612 $result = base64::b64decode($self->{"crl"}[$i]{"state"}{"b64data"});
613 %response = (
614 "freshuntil" => $self->{"crl"}[$i]{"state"}{"freshuntil"} || time,
615 "lastmod" => $self->{"crl"}[$i]{"state"}{"lastmod"} || time,
616 "sourceurl" => $self->{"crl"}[$i]{"state"}{"sourceurl"} || "null:"
617 );
618 } else {
619 foreach my $url ( split(/\001/,$self->{"crlurls"}[$i]) ) {
620 # of these, the first one wins
621 $url =~ /^(http:|https:|ftp:)/ and
622 ($result,%response) = $self->retrieveHTTP($i,$url);
623 $url =~ /^(file:)/ and
624 ($result,%response) = $self->retrieveFile($i,$url);
625 last if $result;
626 }
627 }
628
629 # check if result is there, otherwise invoke agingtolerance clause
630 # before actually raising this as an error
631 # note that agingtolerance stats counting only AFTER the freshness
632 # of the cache control directives has passed ...
633
634 if ( ! $result ) {
635
636 $::log->verb(1,"CRL retrieval for",
637 $self->{"alias"},($i?"[$i] ":"")."failed from all URLs");
638
639 if ( $self->{"agingtolerance"} && $self->{"crl"}[$i]{"state"}{"mtime"} ) {
640 if ( ( time - $self->{"crl"}[$i]{"state"}{"mtime"} ) <
641 3600*$self->{"agingtolerance"}) {
642 $::log->warn("CRL retrieval for",
643 $self->{"alias"},($i?"[$i] ":"")."failed,",
644 int((3600*$self->{"agingtolerance"}+
645 $self->{"crl"}[$i]{"state"}{"mtime"}-
646 time )/3600).
647 " left of ".$self->{"agingtolerance"}."h, retry later.");
648 } else {
649 $::log->retr_err("CRL retrieval for",
650 $self->{"alias"},($i?"[$i] ":"")."failed.",
651 $self->{"agingtolerance"}."h grace expired.",
652 "CRL not updated");
653 }
654 } else { # direct errors, no tolerance anymore
655 $::log->retr_err("CRL retrieval for",
656 $self->{"alias"},($i?"[$i] ":"")."failed,",
657 "CRL not updated");
658 }
659 next; # next subindex CRL for same CA, no further action on this one
660 }
661
662 # now data for $i is loaded in $result;
663 # for freshness checks, take a sum (SysV style)
664 my $sum = unpack("%32C*",$result) % 65535;
665
666 $::log->verb(4,"Got",length($result),"bytes of data (sum=$sum)");
667
668 $self->{"crl"}[$i]{"data"} = $result;
669 $self->{"crl"}[$i]{"state"}{"alias"} = $self->{"alias"};
670 $self->{"crl"}[$i]{"state"}{"index"} = $i;
671 $self->{"crl"}[$i]{"state"}{"sum"} = $sum;
672 ($self->{"crl"}[$i]{"state"}{"b64data"} =
673 base64::b64encode($result)) =~ s/\s+//gm;
674
675 $self->{"crl"}[$i]{"state"}{"retrievaltime"} = time;
676 $self->{"crl"}[$i]{"state"}{"sourceurl"} = $response{"sourceurl"}||"null:";
677 $self->{"crl"}[$i]{"state"}{"freshuntil"} = $response{"freshuntil"}||time;
678 $self->{"crl"}[$i]{"state"}{"lastmod"} = $response{"lastmod"}||time;
679
680 }
681 return 1;
682 }
683
684 sub verifyAndConvertCRLs($) {
685 my $self = shift;
686 $self->{"crlurls"} or
687 $::log->err("Verifying uninitialised list of CRLs impossible") and return 0;
688
689 # all CRLs must be valid in order to proceed
690 # or we would end up shifting the relative ordering around and
691 # possibly creatiing holes (or overwriting good local copies of
692 # CRLs that have gone bad on the remote end
693
694 for ( my $i = 0; $i <= $#{$self->{"crlurls"}} ; $i++ ) { # all indices
695 $self->{"crlurls"}[$i] or
696 $::log->verb(3,"CRL",$self->getAnchorName."/".$i,"ignored (no valid URL)")
697 and next;
698 $self->{"crl"}[$i]{"data"} or
699 $::log->verb(3,"CRL",$self->getAnchorName."/".$i,"ignored (no new data)")
700 and next;
701 $::log->verb(4,"Verifying CRL $i for",$self->getAnchorName);
702
703 my $crl = CRL->new($self->getAnchorName."/$i",$self->{"crl"}[$i]{"data"});
704 my @verifyMessages= $crl->verify(@{$self->{"cafile"}});
705
706 # do additional checks on correlation between download and current
707 # lastUpdate of current file? have to guess the current file
708 # unless we are stateful!
709 my $oldlastupdate = $self->{"crl"}[$i]{"state"}{"lastupdate"} || undef;
710 $oldlastupdate or do {
711 $::log->verb(6,"Attempting to extract lastUpdate of previous D/L");
712 CRLSTATEHUNT: foreach my $output ( @{$::cnf->{_}->{"output_"}} ,
713 $self->{"infodir"}
714 ) {
715 foreach my $file (
716 $self->{"nametemplate_der"},
717 $self->{"nametemplate_pem"},
718 $self->{"alias"}.".r\@R\@",
719 $self->{"anchorname"}.".r\@R\@",
720 ) {
721 next unless $file;
722 (my $thisfile = $file ) =~ s/\@R\@/$i/g;
723 $thisfile = join "/", $output, $thisfile;
724 $::log->verb(6,"Trying guess $file for old CRL");
725 next if ! -e $thisfile;
726 my $oldcrldata; {
727 open OCF,$thisfile and do {
728 binmode OCF;
729 local $/;
730 $oldcrldata = <OCF>;
731 close OCF;
732 }
733 }
734 my $oldcrl = CRL->new($thisfile,$oldcrldata);
735 $oldlastupdate = $oldcrl->getLastUpdate;
736 last CRLSTATEHUNT;
737 }
738 }
739 $::log->verb(3,"Inferred lastupdate for",$self->{"alias"},"is",
740 $oldlastupdate) if $oldlastupdate;
741 };
742
743 if ( ! $crl->getLastUpdate ) {
744 push @verifyMessages,"downloaded CRL lastUpdate could not be derived";
745 } elsif ( $oldlastupdate and ($crl->getLastUpdate < $oldlastupdate) and
746 ($self->{"crl"}[$i]{"state"}{"mtime"} <= time)
747 ) {
748 push @verifyMessages,"downloaded CRL lastUpdate predates installed CRL,",
749 "and current version has sane timestamp";
750 } elsif ( defined $oldlastupdate and $oldlastupdate > time ) {
751 $::log->warn($self->{"anchorname"}."/$i:","replaced with downloaded CRL",
752 "since current one has lastUpdate in the future");
753 }
754
755 $#verifyMessages >= 0 and do {
756 $::log->retr_err("CRL verification failed for",$self->{"anchorname"}."/$i",
757 "(".$self->{"alias"}.")");
758 foreach my $m ( @verifyMessages ) {
759 $::log->verb(0,$self->{"anchorname"}."/$i:",$m);
760 }
761 return 0;
762 };
763
764 $self->{"crl"}[$i]{"pemdata"} = $crl->getPEMdata();
765 foreach my $key ( qw/ lastupdate nextupdate sha1fp issuer / ) {
766 $self->{"crl"}[$i]{"state"}{$key} = $crl->getAttribute($key) || "";
767 }
768
769
770 # issue a low-level warning in case the cache control headers from
771 # the CA (or its CDN) are bugus, i.e. the CRL wille expire before the
772 # cache does. Don't log at warning, since the site cannot fix this
773 if ( defined ($self->{"crl"}[$i]{"state"}{"freshuntil"}) and
774 ( $self->{"crl"}[$i]{"state"}{"freshuntil"} >
775 ( $self->{"crl"}[$i]{"state"}{"nextupdate"} +
776 $::cnf->{_}->{expirestolerance} )
777 )
778 ) {
779 $::log->verb(1,"Cache control headers for CA ".$self->{"alias"}." at ".
780 "URL ".$self->{"crl"}[$i]{"state"}{"sourceurl"}." have apparent ".
781 "freshness ".sprintf("%.1f",($self->{"crl"}[$i]{"state"}{"freshuntil"}-
782 $self->{"crl"}[$i]{"state"}{"nextupdate"})/3600).
783 "hrs beyond CRL expiration nextUpdate. Reset freshness from ".
784 gmtime($self->{"crl"}[$i]{"state"}{"freshuntil"})." UTC to ".
785 $::cnf->{_}->{expirestolerance}." second before nextUpdate at ".
786 gmtime($self->{"crl"}[$i]{"state"}{"nextupdate"})." UTC.");
787 $self->{"crl"}[$i]{"state"}{"freshuntil"} =
788 $self->{"crl"}[$i]{"state"}{"nextupdate"} -
789 $::cnf->{_}->{expirestolerance};
790 }
791
792 # limit maximum freshness period to compensate for CAs that overdo it
793 if ( defined ($self->{"crl"}[$i]{"state"}{"freshuntil"}) and
794 $self->{"crl"}[$i]{"state"}{"freshuntil"} >
795 (time + $::cnf->{_}->{maxcachetime}) ) {
796 $self->{"crl"}[$i]{"state"}{"freshuntil"} =
797 time+$::cnf->{_}->{maxcachetime};
798 $::log->verb(1,"Cache state freshness expiry for CA ".$self->{"alias"}.
799 " reset to at most ".
800 sprintf("%.1f",$::cnf->{_}->{maxcachetime}/3600.).
801 "hrs beyond current time (".
802 gmtime($self->{"crl"}[$i]{"state"}{"freshuntil"})." UTC)");
803 }
804
805 }
806 return 1;
807 }
808
809
810 1;
811

Properties

Name Value
svn:keywords Id

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