File: CachingCertificateValidator.java

package info (click to toggle)
voms-api-java 3.3.5-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,164 kB
  • sloc: java: 7,524; xml: 358; sh: 61; makefile: 2
file content (391 lines) | stat: -rw-r--r-- 10,753 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// SPDX-FileCopyrightText: 2006 Istituto Nazionale di Fisica Nucleare
//
// SPDX-License-Identifier: Apache-2.0

package org.italiangrid.voms.util;

import java.security.cert.CertPath;
import java.security.cert.X509Certificate;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.italiangrid.voms.VOMSError;

import eu.emi.security.authn.x509.ProxySupport;
import eu.emi.security.authn.x509.RevocationParameters;
import eu.emi.security.authn.x509.StoreUpdateListener;
import eu.emi.security.authn.x509.ValidationErrorListener;
import eu.emi.security.authn.x509.ValidationResult;
import eu.emi.security.authn.x509.X509CertChainValidatorExt;
import eu.emi.security.authn.x509.impl.CertificateUtils;
import eu.emi.security.authn.x509.impl.FormatMode;

/**
 * A Certificate validator that caches validation results for a configurable
 * period of time. The cache is keyed by the fingerprint of the certificate at
 * the top of the chain (likely the EEC).
 *
 *
 * @author andreaceccanti
 *
 */
public class CachingCertificateValidator implements X509CertChainValidatorExt {

  /**
   * Simple concurrent cache for validation results
   */
  protected final ConcurrentMap<String, CachedValidationResult> validationResultsCache;

  /**
   * The wrapped CANL certificate validator
   */
  protected final X509CertChainValidatorExt validator;

  /**
   * The cache entry lifetime for this validator
   */
  protected final long cacheEntryLifetimeMsec;

  /**
   * Builds a caching validator wrapping the validator passed as argument.
   *
   * @param val
   *          The CANL validator to be wrapped.
   * @param maxCacheEntryLifetime
   *          the maximum cache entry lifetime (in msecs)
   */
  public CachingCertificateValidator(X509CertChainValidatorExt val,
    long maxCacheEntryLifetime) {

    cacheEntryLifetimeMsec = maxCacheEntryLifetime;
    validator = val;
    validationResultsCache = new ConcurrentHashMap<String, CachedValidationResult>();
  }

  /**
   * Checks whether the {@link CachedValidationResult} passed as argument has
   * expired with respect to the {@link #cacheEntryLifetimeMsec} defined for
   * this validator and the reference time passed as argument.
   *
   * @param cvr
   *          a {@link CachedValidationResult} object
   * @param referenceTime
   *          the reference time (msecs since the epoch)
   * @return <code>true</code> when expired, <code>false</code> otherwise
   */
  public boolean cachedValidationResultHasExpired(CachedValidationResult cvr,
    long referenceTime) {

    return (referenceTime - cvr.getTimestamp() > cacheEntryLifetimeMsec);
  }

  /**
   * Gets a validation result from the memory cache
   *
   * @param certFingerprint
   *          the certificate fingerprint for the certificate at the top of the
   *          chain
   * @return the validation result, if found. <code>null</code> otherwise.
   */
  protected ValidationResult getCachedResult(String certFingerprint) {

    CachedValidationResult cvr = validationResultsCache.get(certFingerprint);

    if (cvr == null)
      return null;

    if (!cachedValidationResultHasExpired(cvr, System.currentTimeMillis())) {
      return cvr.getResult();
    }

    validationResultsCache.remove(certFingerprint, cvr);
    return null;
  }

  /**
   * Obvious sanity checks on input certificate chain
   *
   * @param certChain
   *          the chain to be checked
   */
  private void certChainSanityChecks(X509Certificate[] certChain) {

    if (certChain == null)
      throw new IllegalArgumentException("Cannot validate a null cert chain.");

    if (certChain.length == 0)
      throw new IllegalArgumentException(
        "Cannot validate a cert chain of length 0.");
  }

  /**
   * Validates a certificate chain using the wrapped validator, caching the
   * result for future validation calls.
   *
   * @param certChain
   *          the certificate chain that will be validated
   * @return a possibly cached {@link ValidationResult}
   * @see eu.emi.security.authn.x509.X509CertChainValidator#validate(java.security.cert.X509Certificate[])
   */
  public ValidationResult validate(X509Certificate[] certChain) {

    certChainSanityChecks(certChain);

    String certFingerprint = null;

    try {
      certFingerprint = FingerprintHelper
        .getFingerprint(certChain[certChain.length - 1]);

    } catch (Throwable t) {

      String errorMsg = String.format("Error computing fingerprint for "
        + "certificate: %s. Cause: %s",
        CertificateUtils.format(certChain[0], FormatMode.COMPACT_ONE_LINE),
        t.getMessage());

      throw new VOMSError(errorMsg, t);

    }

    ValidationResult res = getCachedResult(certFingerprint);

    if (res == null) {
      res = validator.validate(certChain);
      validationResultsCache.putIfAbsent(certFingerprint,
        new CachedValidationResult(certFingerprint, res));
    }

    return res;

  }

  /**
   * @see eu.emi.security.authn.x509.X509CertChainValidatorExt#dispose()
   */
  public void dispose() {

    validator.dispose();
  }

  /**
   * @return the proxy support information
   * @see eu.emi.security.authn.x509.X509CertChainValidatorExt#getProxySupport()
   */
  public ProxySupport getProxySupport() {

    return validator.getProxySupport();
  }

  /**
   * @param certPath
   *          the certificate path that will be validated
   * @return the {@link ValidationResult}
   * @see eu.emi.security.authn.x509.X509CertChainValidator#validate(java.security.cert.CertPath)
   */
  public ValidationResult validate(CertPath certPath) {

    return validator.validate(certPath);
  }

  /**
   * @return revocation parameters for the wrapped validator
   * @see eu.emi.security.authn.x509.X509CertChainValidatorExt#getRevocationCheckingMode()
   */
  public RevocationParameters getRevocationCheckingMode() {

    return validator.getRevocationCheckingMode();
  }

  /**
   * @return trusted issuers from the wrapped validator
   * @see eu.emi.security.authn.x509.X509CertChainValidator#getTrustedIssuers()
   */
  public X509Certificate[] getTrustedIssuers() {

    return validator.getTrustedIssuers();
  }

  /**
   * @param listener
   *          the {@link ValidationErrorListener} to be added to this validator
   *          
   * @see eu.emi.security.authn.x509.X509CertChainValidator#addValidationListener(eu.emi.security.authn.x509.ValidationErrorListener)
   */
  public void addValidationListener(ValidationErrorListener listener) {

    validator.addValidationListener(listener);
  }

  /**
   * @param listener
   *        the {@link ValidationErrorListener} that must be removed from 
   *        this validator
   * @see eu.emi.security.authn.x509.X509CertChainValidator#removeValidationListener(eu.emi.security.authn.x509.ValidationErrorListener)
   */
  public void removeValidationListener(ValidationErrorListener listener) {

    validator.removeValidationListener(listener);
  }

  /**
   * @param listener
   *          the {@link StoreUpdateListener} that must be added to this 
   *          validator
   *        
   * @see eu.emi.security.authn.x509.X509CertChainValidator#addUpdateListener(eu.emi.security.authn.x509.StoreUpdateListener)
   */
  public void addUpdateListener(StoreUpdateListener listener) {

    validator.addUpdateListener(listener);
  }

  /**
   * @param listener
   *          the {@link StoreUpdateListener} that must be removed from this 
   *          validator
   *          
   * @see eu.emi.security.authn.x509.X509CertChainValidator#removeUpdateListener(eu.emi.security.authn.x509.StoreUpdateListener)
   */
  public void removeUpdateListener(StoreUpdateListener listener) {

    validator.removeUpdateListener(listener);
  }

}

/**
 * A validation result cache entry.
 *
 * @author cecco
 *
 */
class CachedValidationResult {

  /**
   * Default constructor.
   *
   * @param certificateFingerprint
   *          the certificate fingerprint for this entry
   * @param res
   *          the validation result
   */
  public CachedValidationResult(String certificateFingerprint,
    ValidationResult res) {

    certFingerprint = certificateFingerprint;
    result = res;
    timestamp = System.currentTimeMillis();
  }

  /** The certificate fingerprint for this cache entry **/
  private String certFingerprint;

  /** The validation result for this cache entry **/
  private ValidationResult result;

  /** The cache entry creation timestamp **/
  private long timestamp;

  /**
   * Returns the validation result for this entry.
   *
   * @return a {@link ValidationResult}
   */
  public ValidationResult getResult() {

    return result;
  }

  /**
   * Sets the validation result for this entry
   *
   * @param result
   *          a {@link ValidationResult}
   */
  public void setResult(ValidationResult result) {

    this.result = result;
  }

  /**
   * Returns this entry creation timestamp.
   *
   * @return the timestamp expressed as milliseconds since epoch
   */
  public long getTimestamp() {

    return timestamp;
  }

  /**
   * Sets this entry creation timestamp (in milliseconds since the epoch).
   *
   * @param timestamp
   *          the timestamp
   */
  public void setTimestamp(long timestamp) {

    this.timestamp = timestamp;
  }

  /**
   * Returns the certificate fingerprint for this entry.
   *
   * The certificate fingerprint is the SHA1 hash of the DER encoding of the
   * certificate.
   *
   *
   *
   * @return the fingerprint for this entry
   * @see FingerprintHelper
   */
  public String getCertFingerprint() {

    return certFingerprint;
  }

  /**
   *
   * Sets the certificate finger for this entry. The certificate fingerprint is
   * the SHA1 hash of the DER encoding of the certificate.
   *
   * It can be computed with the
   * {@link FingerprintHelper#getFingerprint(X509Certificate)} method.
   *
   * @param certFingerprint
   *          a certificate fingerprint describing a certificate
   */
  public void setCertFingerprint(String certFingerprint) {

    this.certFingerprint = certFingerprint;
  }

  @Override
  public int hashCode() {

    final int prime = 31;
    int result = 1;
    result = prime * result
      + ((certFingerprint == null) ? 0 : certFingerprint.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {

    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    CachedValidationResult other = (CachedValidationResult) obj;
    if (certFingerprint == null) {
      if (other.certFingerprint != null)
        return false;
    } else if (!certFingerprint.equals(other.certFingerprint))
      return false;
    return true;
  }
}