1 /* 2 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package sun.security.x509; 27 28 import java.io.InputStream; 29 import java.io.OutputStream; 30 import java.io.IOException; 31 import java.math.BigInteger; 32 import java.security.Principal; 33 import java.security.PublicKey; 34 import java.security.PrivateKey; 35 import java.security.Provider; 36 import java.security.Signature; 37 import java.security.NoSuchAlgorithmException; 38 import java.security.InvalidKeyException; 39 import java.security.NoSuchProviderException; 40 import java.security.SignatureException; 41 import java.security.cert.Certificate; 42 import java.security.cert.X509CRL; 43 import java.security.cert.X509Certificate; 44 import java.security.cert.X509CRLEntry; 45 import java.security.cert.CRLException; 46 import java.util.*; 47 48 import javax.security.auth.x500.X500Principal; 49 50 import sun.security.provider.X509Factory; 51 import sun.security.util.*; 52 import sun.security.util.HexDumpEncoder; 53 54 /** 55 * <p> 56 * An implementation for X509 CRL (Certificate Revocation List). 57 * <p> 58 * The X.509 v2 CRL format is described below in ASN.1: 59 * <pre> 60 * CertificateList ::= SEQUENCE { 61 * tbsCertList TBSCertList, 62 * signatureAlgorithm AlgorithmIdentifier, 63 * signature BIT STRING } 64 * </pre> 65 * More information can be found in 66 * <a href="http://tools.ietf.org/html/rfc5280">RFC 5280: Internet X.509 67 * Public Key Infrastructure Certificate and CRL Profile</a>. 68 * <p> 69 * The ASN.1 definition of <code>tbsCertList</code> is: 70 * <pre> 71 * TBSCertList ::= SEQUENCE { 72 * version Version OPTIONAL, 73 * -- if present, must be v2 74 * signature AlgorithmIdentifier, 75 * issuer Name, 76 * thisUpdate ChoiceOfTime, 77 * nextUpdate ChoiceOfTime OPTIONAL, 78 * revokedCertificates SEQUENCE OF SEQUENCE { 79 * userCertificate CertificateSerialNumber, 80 * revocationDate ChoiceOfTime, 81 * crlEntryExtensions Extensions OPTIONAL 82 * -- if present, must be v2 83 * } OPTIONAL, 84 * crlExtensions [0] EXPLICIT Extensions OPTIONAL 85 * -- if present, must be v2 86 * } 87 * </pre> 88 * 89 * @author Hemma Prafullchandra 90 * @see X509CRL 91 */ 92 public class X509CRLImpl extends X509CRL implements DerEncoder { 93 94 // CRL data, and its envelope 95 private byte[] signedCRL = null; // DER encoded crl 96 private byte[] signature = null; // raw signature bits 97 private byte[] tbsCertList = null; // DER encoded "to-be-signed" CRL 98 private AlgorithmId sigAlgId = null; // sig alg in CRL 99 100 // crl information 101 private int version; 102 private AlgorithmId infoSigAlgId; // sig alg in "to-be-signed" crl 103 private X500Name issuer = null; 104 private X500Principal issuerPrincipal = null; 105 private Date thisUpdate = null; 106 private Date nextUpdate = null; 107 private Map<X509IssuerSerial,X509CRLEntry> revokedMap = new TreeMap<>(); 108 private List<X509CRLEntry> revokedList = new LinkedList<>(); 109 private CRLExtensions extensions = null; 110 private static final boolean isExplicit = true; 111 private static final long YR_2050 = 2524636800000L; 112 113 private boolean readOnly = false; 114 115 /** 116 * PublicKey that has previously been used to successfully verify 117 * the signature of this CRL. Null if the CRL has not 118 * yet been verified (successfully). 119 */ 120 private PublicKey verifiedPublicKey; 121 /** 122 * If verifiedPublicKey is not null, name of the provider used to 123 * successfully verify the signature of this CRL, or the 124 * empty String if no provider was explicitly specified. 125 */ 126 private String verifiedProvider; 127 128 /** 129 * Not to be used. As it would lead to cases of uninitialized 130 * CRL objects. 131 */ 132 private X509CRLImpl() { } 133 134 /** 135 * Unmarshals an X.509 CRL from its encoded form, parsing the encoded 136 * bytes. This form of constructor is used by agents which 137 * need to examine and use CRL contents. Note that the buffer 138 * must include only one CRL, and no "garbage" may be left at 139 * the end. 140 * 141 * @param crlData the encoded bytes, with no trailing padding. 142 * @exception CRLException on parsing errors. 143 */ 144 public X509CRLImpl(byte[] crlData) throws CRLException { 145 try { 146 parse(new DerValue(crlData)); 147 } catch (IOException e) { 148 signedCRL = null; 149 throw new CRLException("Parsing error: " + e.getMessage()); 150 } 151 } 152 153 /** 154 * Unmarshals an X.509 CRL from an DER value. 155 * 156 * @param val a DER value holding at least one CRL 157 * @exception CRLException on parsing errors. 158 */ 159 public X509CRLImpl(DerValue val) throws CRLException { 160 try { 161 parse(val); 162 } catch (IOException e) { 163 signedCRL = null; 164 throw new CRLException("Parsing error: " + e.getMessage()); 165 } 166 } 167 168 /** 169 * Unmarshals an X.509 CRL from an input stream. Only one CRL 170 * is expected at the end of the input stream. 171 * 172 * @param inStrm an input stream holding at least one CRL 173 * @exception CRLException on parsing errors. 174 */ 175 public X509CRLImpl(InputStream inStrm) throws CRLException { 176 try { 177 parse(new DerValue(inStrm)); 178 } catch (IOException e) { 179 signedCRL = null; 180 throw new CRLException("Parsing error: " + e.getMessage()); 181 } 182 } 183 184 /** 185 * Initial CRL constructor, no revoked certs, and no extensions. 186 * 187 * @param issuer the name of the CA issuing this CRL. 188 * @param thisDate the Date of this issue. 189 * @param nextDate the Date of the next CRL. 190 */ 191 public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate) { 192 this.issuer = issuer; 193 this.thisUpdate = thisDate; 194 this.nextUpdate = nextDate; 195 } 196 197 /** 198 * CRL constructor, revoked certs, no extensions. 199 * 200 * @param issuer the name of the CA issuing this CRL. 201 * @param thisDate the Date of this issue. 202 * @param nextDate the Date of the next CRL. 203 * @param badCerts the array of CRL entries. 204 * 205 * @exception CRLException on parsing/construction errors. 206 */ 207 public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate, 208 X509CRLEntry[] badCerts) 209 throws CRLException 210 { 211 this.issuer = issuer; 212 this.thisUpdate = thisDate; 213 this.nextUpdate = nextDate; 214 if (badCerts != null) { 215 X500Principal crlIssuer = getIssuerX500Principal(); 216 X500Principal badCertIssuer = crlIssuer; 217 for (int i = 0; i < badCerts.length; i++) { 218 X509CRLEntryImpl badCert = (X509CRLEntryImpl)badCerts[i]; 219 try { 220 badCertIssuer = getCertIssuer(badCert, badCertIssuer); 221 } catch (IOException ioe) { 222 throw new CRLException(ioe); 223 } 224 badCert.setCertificateIssuer(crlIssuer, badCertIssuer); 225 X509IssuerSerial issuerSerial = new X509IssuerSerial 226 (badCertIssuer, badCert.getSerialNumber()); 227 this.revokedMap.put(issuerSerial, badCert); 228 this.revokedList.add(badCert); 229 if (badCert.hasExtensions()) { 230 this.version = 1; 231 } 232 } 233 } 234 } 235 236 /** 237 * CRL constructor, revoked certs and extensions. 238 * 239 * @param issuer the name of the CA issuing this CRL. 240 * @param thisDate the Date of this issue. 241 * @param nextDate the Date of the next CRL. 242 * @param badCerts the array of CRL entries. 243 * @param crlExts the CRL extensions. 244 * 245 * @exception CRLException on parsing/construction errors. 246 */ 247 public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate, 248 X509CRLEntry[] badCerts, CRLExtensions crlExts) 249 throws CRLException 250 { 251 this(issuer, thisDate, nextDate, badCerts); 252 if (crlExts != null) { 253 this.extensions = crlExts; 254 this.version = 1; 255 } 256 } 257 258 /** 259 * Returned the encoding as an uncloned byte array. Callers must 260 * guarantee that they neither modify it nor expose it to untrusted 261 * code. 262 */ 263 public byte[] getEncodedInternal() throws CRLException { 264 if (signedCRL == null) { 265 throw new CRLException("Null CRL to encode"); 266 } 267 return signedCRL; 268 } 269 270 /** 271 * Returns the ASN.1 DER encoded form of this CRL. 272 * 273 * @exception CRLException if an encoding error occurs. 274 */ 275 public byte[] getEncoded() throws CRLException { 276 return getEncodedInternal().clone(); 277 } 278 279 /** 280 * Encodes the "to-be-signed" CRL to the OutputStream. 281 * 282 * @param out the OutputStream to write to. 283 * @exception CRLException on encoding errors. 284 */ 285 public void encodeInfo(OutputStream out) throws CRLException { 286 try { 287 DerOutputStream tmp = new DerOutputStream(); 288 DerOutputStream rCerts = new DerOutputStream(); 289 DerOutputStream seq = new DerOutputStream(); 290 291 if (version != 0) // v2 crl encode version 292 tmp.putInteger(version); 293 infoSigAlgId.encode(tmp); 294 if ((version == 0) && (issuer.toString() == null)) 295 throw new CRLException("Null Issuer DN not allowed in v1 CRL"); 296 issuer.encode(tmp); 297 298 if (thisUpdate.getTime() < YR_2050) 299 tmp.putUTCTime(thisUpdate); 300 else 301 tmp.putGeneralizedTime(thisUpdate); 302 303 if (nextUpdate != null) { 304 if (nextUpdate.getTime() < YR_2050) 305 tmp.putUTCTime(nextUpdate); 306 else 307 tmp.putGeneralizedTime(nextUpdate); 308 } 309 310 if (!revokedList.isEmpty()) { 311 for (X509CRLEntry entry : revokedList) { 312 ((X509CRLEntryImpl)entry).encode(rCerts); 313 } 314 tmp.write(DerValue.tag_Sequence, rCerts); 315 } 316 317 if (extensions != null) 318 extensions.encode(tmp, isExplicit); 319 320 seq.write(DerValue.tag_Sequence, tmp); 321 322 tbsCertList = seq.toByteArray(); 323 out.write(tbsCertList); 324 } catch (IOException e) { 325 throw new CRLException("Encoding error: " + e.getMessage()); 326 } 327 } 328 329 /** 330 * Verifies that this CRL was signed using the 331 * private key that corresponds to the given public key. 332 * 333 * @param key the PublicKey used to carry out the verification. 334 * 335 * @exception NoSuchAlgorithmException on unsupported signature 336 * algorithms. 337 * @exception InvalidKeyException on incorrect key. 338 * @exception NoSuchProviderException if there's no default provider. 339 * @exception SignatureException on signature errors. 340 * @exception CRLException on encoding errors. 341 */ 342 public void verify(PublicKey key) 343 throws CRLException, NoSuchAlgorithmException, InvalidKeyException, 344 NoSuchProviderException, SignatureException { 345 verify(key, ""); 346 } 347 348 /** 349 * Verifies that this CRL was signed using the 350 * private key that corresponds to the given public key, 351 * and that the signature verification was computed by 352 * the given provider. 353 * 354 * @param key the PublicKey used to carry out the verification. 355 * @param sigProvider the name of the signature provider. 356 * 357 * @exception NoSuchAlgorithmException on unsupported signature 358 * algorithms. 359 * @exception InvalidKeyException on incorrect key. 360 * @exception NoSuchProviderException on incorrect provider. 361 * @exception SignatureException on signature errors. 362 * @exception CRLException on encoding errors. 363 */ 364 public synchronized void verify(PublicKey key, String sigProvider) 365 throws CRLException, NoSuchAlgorithmException, InvalidKeyException, 366 NoSuchProviderException, SignatureException { 367 368 if (sigProvider == null) { 369 sigProvider = ""; 370 } 371 if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) { 372 // this CRL has already been successfully verified using 373 // this public key. Make sure providers match, too. 374 if (sigProvider.equals(verifiedProvider)) { 375 return; 376 } 377 } 378 if (signedCRL == null) { 379 throw new CRLException("Uninitialized CRL"); 380 } 381 Signature sigVerf = null; 382 if (sigProvider.length() == 0) { 383 sigVerf = Signature.getInstance(sigAlgId.getName()); 384 } else { 385 sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider); 386 } 387 sigVerf.initVerify(key); 388 389 if (tbsCertList == null) { 390 throw new CRLException("Uninitialized CRL"); 391 } 392 393 sigVerf.update(tbsCertList, 0, tbsCertList.length); 394 395 if (!sigVerf.verify(signature)) { 396 throw new SignatureException("Signature does not match."); 397 } 398 verifiedPublicKey = key; 399 verifiedProvider = sigProvider; 400 } 401 402 /** 403 * Verifies that this CRL was signed using the 404 * private key that corresponds to the given public key, 405 * and that the signature verification was computed by 406 * the given provider. Note that the specified Provider object 407 * does not have to be registered in the provider list. 408 * 409 * @param key the PublicKey used to carry out the verification. 410 * @param sigProvider the signature provider. 411 * 412 * @exception NoSuchAlgorithmException on unsupported signature 413 * algorithms. 414 * @exception InvalidKeyException on incorrect key. 415 * @exception SignatureException on signature errors. 416 * @exception CRLException on encoding errors. 417 */ 418 public synchronized void verify(PublicKey key, Provider sigProvider) 419 throws CRLException, NoSuchAlgorithmException, InvalidKeyException, 420 SignatureException { 421 422 if (signedCRL == null) { 423 throw new CRLException("Uninitialized CRL"); 424 } 425 Signature sigVerf = null; 426 if (sigProvider == null) { 427 sigVerf = Signature.getInstance(sigAlgId.getName()); 428 } else { 429 sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider); 430 } 431 sigVerf.initVerify(key); 432 433 if (tbsCertList == null) { 434 throw new CRLException("Uninitialized CRL"); 435 } 436 437 sigVerf.update(tbsCertList, 0, tbsCertList.length); 438 439 if (!sigVerf.verify(signature)) { 440 throw new SignatureException("Signature does not match."); 441 } 442 verifiedPublicKey = key; 443 } 444 445 /** 446 * Encodes an X.509 CRL, and signs it using the given key. 447 * 448 * @param key the private key used for signing. 449 * @param algorithm the name of the signature algorithm used. 450 * 451 * @exception NoSuchAlgorithmException on unsupported signature 452 * algorithms. 453 * @exception InvalidKeyException on incorrect key. 454 * @exception NoSuchProviderException on incorrect provider. 455 * @exception SignatureException on signature errors. 456 * @exception CRLException if any mandatory data was omitted. 457 */ 458 public void sign(PrivateKey key, String algorithm) 459 throws CRLException, NoSuchAlgorithmException, InvalidKeyException, 460 NoSuchProviderException, SignatureException { 461 sign(key, algorithm, null); 462 } 463 464 /** 465 * Encodes an X.509 CRL, and signs it using the given key. 466 * 467 * @param key the private key used for signing. 468 * @param algorithm the name of the signature algorithm used. 469 * @param provider the name of the provider. 470 * 471 * @exception NoSuchAlgorithmException on unsupported signature 472 * algorithms. 473 * @exception InvalidKeyException on incorrect key. 474 * @exception NoSuchProviderException on incorrect provider. 475 * @exception SignatureException on signature errors. 476 * @exception CRLException if any mandatory data was omitted. 477 */ 478 public void sign(PrivateKey key, String algorithm, String provider) 479 throws CRLException, NoSuchAlgorithmException, InvalidKeyException, 480 NoSuchProviderException, SignatureException { 481 try { 482 if (readOnly) 483 throw new CRLException("cannot over-write existing CRL"); 484 Signature sigEngine = null; 485 if ((provider == null) || (provider.length() == 0)) 486 sigEngine = Signature.getInstance(algorithm); 487 else 488 sigEngine = Signature.getInstance(algorithm, provider); 489 490 sigEngine.initSign(key); 491 492 // in case the name is reset 493 sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm()); 494 infoSigAlgId = sigAlgId; 495 496 DerOutputStream out = new DerOutputStream(); 497 DerOutputStream tmp = new DerOutputStream(); 498 499 // encode crl info 500 encodeInfo(tmp); 501 502 // encode algorithm identifier 503 sigAlgId.encode(tmp); 504 505 // Create and encode the signature itself. 506 sigEngine.update(tbsCertList, 0, tbsCertList.length); 507 signature = sigEngine.sign(); 508 tmp.putBitString(signature); 509 510 // Wrap the signed data in a SEQUENCE { data, algorithm, sig } 511 out.write(DerValue.tag_Sequence, tmp); 512 signedCRL = out.toByteArray(); 513 readOnly = true; 514 515 } catch (IOException e) { 516 throw new CRLException("Error while encoding data: " + 517 e.getMessage()); 518 } 519 } 520 521 /** 522 * Returns a printable string of this CRL. 523 * 524 * @return value of this CRL in a printable form. 525 */ 526 public String toString() { 527 return toStringWithAlgName("" + sigAlgId); 528 } 529 530 // Specifically created for keytool to append a (weak) label to sigAlg 531 public String toStringWithAlgName(String name) { 532 StringBuilder sb = new StringBuilder(); 533 sb.append("X.509 CRL v") 534 .append(version+1) 535 .append('\n'); 536 if (sigAlgId != null) 537 sb.append("Signature Algorithm: ") 538 .append(name) 539 .append(", OID=") 540 .append(sigAlgId.getOID()) 541 .append('\n'); 542 if (issuer != null) 543 sb.append("Issuer: ") 544 .append(issuer) 545 .append('\n'); 546 if (thisUpdate != null) 547 sb.append("\nThis Update: ") 548 .append(thisUpdate) 549 .append('\n'); 550 if (nextUpdate != null) 551 sb.append("Next Update: ") 552 .append(nextUpdate) 553 .append('\n'); 554 if (revokedList.isEmpty()) 555 sb.append("\nNO certificates have been revoked\n"); 556 else { 557 sb.append("\nRevoked Certificates: ") 558 .append(revokedList.size()); 559 int i = 1; 560 for (X509CRLEntry entry: revokedList) { 561 sb.append("\n[") 562 .append(i++) 563 .append("] ") 564 .append(entry); 565 } 566 } 567 if (extensions != null) { 568 Collection<Extension> allExts = extensions.getAllExtensions(); 569 Object[] objs = allExts.toArray(); 570 sb.append("\nCRL Extensions: ") 571 .append(objs.length); 572 for (int i = 0; i < objs.length; i++) { 573 sb.append("\n[").append(i+1).append("]: "); 574 Extension ext = (Extension)objs[i]; 575 try { 576 if (OIDMap.getClass(ext.getExtensionId()) == null) { 577 sb.append(ext); 578 byte[] extValue = ext.getExtensionValue(); 579 if (extValue != null) { 580 DerOutputStream out = new DerOutputStream(); 581 out.putOctetString(extValue); 582 extValue = out.toByteArray(); 583 HexDumpEncoder enc = new HexDumpEncoder(); 584 sb.append("Extension unknown: ") 585 .append("DER encoded OCTET string =\n") 586 .append(enc.encodeBuffer(extValue)) 587 .append('\n'); 588 } 589 } else { 590 sb.append(ext); // sub-class exists 591 } 592 } catch (Exception e) { 593 sb.append(", Error parsing this extension"); 594 } 595 } 596 } 597 if (signature != null) { 598 HexDumpEncoder encoder = new HexDumpEncoder(); 599 sb.append("\nSignature:\n") 600 .append(encoder.encodeBuffer(signature)) 601 .append('\n'); 602 } else { 603 sb.append("NOT signed yet\n"); 604 } 605 return sb.toString(); 606 } 607 608 /** 609 * Checks whether the given certificate is on this CRL. 610 * 611 * @param cert the certificate to check for. 612 * @return true if the given certificate is on this CRL, 613 * false otherwise. 614 */ 615 public boolean isRevoked(Certificate cert) { 616 if (revokedMap.isEmpty() || (!(cert instanceof X509Certificate))) { 617 return false; 618 } 619 X509Certificate xcert = (X509Certificate) cert; 620 X509IssuerSerial issuerSerial = new X509IssuerSerial(xcert); 621 return revokedMap.containsKey(issuerSerial); 622 } 623 624 /** 625 * Gets the version number from this CRL. 626 * The ASN.1 definition for this is: 627 * <pre> 628 * Version ::= INTEGER { v1(0), v2(1), v3(2) } 629 * -- v3 does not apply to CRLs but appears for consistency 630 * -- with definition of Version for certs 631 * </pre> 632 * @return the version number, i.e. 1 or 2. 633 */ 634 public int getVersion() { 635 return version+1; 636 } 637 638 /** 639 * Gets the issuer distinguished name from this CRL. 640 * The issuer name identifies the entity who has signed (and 641 * issued the CRL). The issuer name field contains an 642 * X.500 distinguished name (DN). 643 * The ASN.1 definition for this is: 644 * <pre> 645 * issuer Name 646 * 647 * Name ::= CHOICE { RDNSequence } 648 * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName 649 * RelativeDistinguishedName ::= 650 * SET OF AttributeValueAssertion 651 * 652 * AttributeValueAssertion ::= SEQUENCE { 653 * AttributeType, 654 * AttributeValue } 655 * AttributeType ::= OBJECT IDENTIFIER 656 * AttributeValue ::= ANY 657 * </pre> 658 * The Name describes a hierarchical name composed of attributes, 659 * such as country name, and corresponding values, such as US. 660 * The type of the component AttributeValue is determined by the 661 * AttributeType; in general it will be a directoryString. 662 * A directoryString is usually one of PrintableString, 663 * TeletexString or UniversalString. 664 * @return the issuer name. 665 */ 666 public Principal getIssuerDN() { 667 return (Principal)issuer; 668 } 669 670 /** 671 * Return the issuer as X500Principal. Overrides method in X509CRL 672 * to provide a slightly more efficient version. 673 */ 674 public X500Principal getIssuerX500Principal() { 675 if (issuerPrincipal == null) { 676 issuerPrincipal = issuer.asX500Principal(); 677 } 678 return issuerPrincipal; 679 } 680 681 /** 682 * Gets the thisUpdate date from the CRL. 683 * The ASN.1 definition for this is: 684 * 685 * @return the thisUpdate date from the CRL. 686 */ 687 public Date getThisUpdate() { 688 return (new Date(thisUpdate.getTime())); 689 } 690 691 /** 692 * Gets the nextUpdate date from the CRL. 693 * 694 * @return the nextUpdate date from the CRL, or null if 695 * not present. 696 */ 697 public Date getNextUpdate() { 698 if (nextUpdate == null) 699 return null; 700 return (new Date(nextUpdate.getTime())); 701 } 702 703 /** 704 * Gets the CRL entry with the given serial number from this CRL. 705 * 706 * @return the entry with the given serial number, or <code>null</code> if 707 * no such entry exists in the CRL. 708 * @see X509CRLEntry 709 */ 710 public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) { 711 if (revokedMap.isEmpty()) { 712 return null; 713 } 714 // assume this is a direct CRL entry (cert and CRL issuer are the same) 715 X509IssuerSerial issuerSerial = new X509IssuerSerial 716 (getIssuerX500Principal(), serialNumber); 717 return revokedMap.get(issuerSerial); 718 } 719 720 /** 721 * Gets the CRL entry for the given certificate. 722 */ 723 public X509CRLEntry getRevokedCertificate(X509Certificate cert) { 724 if (revokedMap.isEmpty()) { 725 return null; 726 } 727 X509IssuerSerial issuerSerial = new X509IssuerSerial(cert); 728 return revokedMap.get(issuerSerial); 729 } 730 731 /** 732 * Gets all the revoked certificates from the CRL. 733 * A Set of X509CRLEntry. 734 * 735 * @return all the revoked certificates or <code>null</code> if there are 736 * none. 737 * @see X509CRLEntry 738 */ 739 public Set<X509CRLEntry> getRevokedCertificates() { 740 if (revokedList.isEmpty()) { 741 return null; 742 } else { 743 return new TreeSet<X509CRLEntry>(revokedList); 744 } 745 } 746 747 /** 748 * Gets the DER encoded CRL information, the 749 * <code>tbsCertList</code> from this CRL. 750 * This can be used to verify the signature independently. 751 * 752 * @return the DER encoded CRL information. 753 * @exception CRLException on encoding errors. 754 */ 755 public byte[] getTBSCertList() throws CRLException { 756 if (tbsCertList == null) 757 throw new CRLException("Uninitialized CRL"); 758 return tbsCertList.clone(); 759 } 760 761 /** 762 * Gets the raw Signature bits from the CRL. 763 * 764 * @return the signature. 765 */ 766 public byte[] getSignature() { 767 if (signature == null) 768 return null; 769 return signature.clone(); 770 } 771 772 /** 773 * Gets the signature algorithm name for the CRL 774 * signature algorithm. For example, the string "SHA1withDSA". 775 * The ASN.1 definition for this is: 776 * <pre> 777 * AlgorithmIdentifier ::= SEQUENCE { 778 * algorithm OBJECT IDENTIFIER, 779 * parameters ANY DEFINED BY algorithm OPTIONAL } 780 * -- contains a value of the type 781 * -- registered for use with the 782 * -- algorithm object identifier value 783 * </pre> 784 * 785 * @return the signature algorithm name. 786 */ 787 public String getSigAlgName() { 788 if (sigAlgId == null) 789 return null; 790 return sigAlgId.getName(); 791 } 792 793 /** 794 * Gets the signature algorithm OID string from the CRL. 795 * An OID is represented by a set of positive whole number separated 796 * by ".", that means,<br> 797 * <positive whole number>.<positive whole number>.<...> 798 * For example, the string "1.2.840.10040.4.3" identifies the SHA-1 799 * with DSA signature algorithm defined in 800 * <a href="http://www.ietf.org/rfc/rfc3279.txt">RFC 3279: Algorithms and 801 * Identifiers for the Internet X.509 Public Key Infrastructure Certificate 802 * and CRL Profile</a>. 803 * 804 * @return the signature algorithm oid string. 805 */ 806 public String getSigAlgOID() { 807 if (sigAlgId == null) 808 return null; 809 ObjectIdentifier oid = sigAlgId.getOID(); 810 return oid.toString(); 811 } 812 813 /** 814 * Gets the DER encoded signature algorithm parameters from this 815 * CRL's signature algorithm. In most cases, the signature 816 * algorithm parameters are null, the parameters are usually 817 * supplied with the Public Key. 818 * 819 * @return the DER encoded signature algorithm parameters, or 820 * null if no parameters are present. 821 */ 822 public byte[] getSigAlgParams() { 823 if (sigAlgId == null) 824 return null; 825 try { 826 return sigAlgId.getEncodedParams(); 827 } catch (IOException e) { 828 return null; 829 } 830 } 831 832 /** 833 * Gets the signature AlgorithmId from the CRL. 834 * 835 * @return the signature AlgorithmId 836 */ 837 public AlgorithmId getSigAlgId() { 838 return sigAlgId; 839 } 840 841 /** 842 * return the AuthorityKeyIdentifier, if any. 843 * 844 * @return AuthorityKeyIdentifier or null 845 * (if no AuthorityKeyIdentifierExtension) 846 * @throws IOException on error 847 */ 848 public KeyIdentifier getAuthKeyId() throws IOException { 849 AuthorityKeyIdentifierExtension aki = getAuthKeyIdExtension(); 850 if (aki != null) { 851 KeyIdentifier keyId = (KeyIdentifier)aki.get( 852 AuthorityKeyIdentifierExtension.KEY_ID); 853 return keyId; 854 } else { 855 return null; 856 } 857 } 858 859 /** 860 * return the AuthorityKeyIdentifierExtension, if any. 861 * 862 * @return AuthorityKeyIdentifierExtension or null (if no such extension) 863 * @throws IOException on error 864 */ 865 public AuthorityKeyIdentifierExtension getAuthKeyIdExtension() 866 throws IOException { 867 Object obj = getExtension(PKIXExtensions.AuthorityKey_Id); 868 return (AuthorityKeyIdentifierExtension)obj; 869 } 870 871 /** 872 * return the CRLNumberExtension, if any. 873 * 874 * @return CRLNumberExtension or null (if no such extension) 875 * @throws IOException on error 876 */ 877 public CRLNumberExtension getCRLNumberExtension() throws IOException { 878 Object obj = getExtension(PKIXExtensions.CRLNumber_Id); 879 return (CRLNumberExtension)obj; 880 } 881 882 /** 883 * return the CRL number from the CRLNumberExtension, if any. 884 * 885 * @return number or null (if no such extension) 886 * @throws IOException on error 887 */ 888 public BigInteger getCRLNumber() throws IOException { 889 CRLNumberExtension numExt = getCRLNumberExtension(); 890 if (numExt != null) { 891 BigInteger num = numExt.get(CRLNumberExtension.NUMBER); 892 return num; 893 } else { 894 return null; 895 } 896 } 897 898 /** 899 * return the DeltaCRLIndicatorExtension, if any. 900 * 901 * @return DeltaCRLIndicatorExtension or null (if no such extension) 902 * @throws IOException on error 903 */ 904 public DeltaCRLIndicatorExtension getDeltaCRLIndicatorExtension() 905 throws IOException { 906 907 Object obj = getExtension(PKIXExtensions.DeltaCRLIndicator_Id); 908 return (DeltaCRLIndicatorExtension)obj; 909 } 910 911 /** 912 * return the base CRL number from the DeltaCRLIndicatorExtension, if any. 913 * 914 * @return number or null (if no such extension) 915 * @throws IOException on error 916 */ 917 public BigInteger getBaseCRLNumber() throws IOException { 918 DeltaCRLIndicatorExtension dciExt = getDeltaCRLIndicatorExtension(); 919 if (dciExt != null) { 920 BigInteger num = dciExt.get(DeltaCRLIndicatorExtension.NUMBER); 921 return num; 922 } else { 923 return null; 924 } 925 } 926 927 /** 928 * return the IssuerAlternativeNameExtension, if any. 929 * 930 * @return IssuerAlternativeNameExtension or null (if no such extension) 931 * @throws IOException on error 932 */ 933 public IssuerAlternativeNameExtension getIssuerAltNameExtension() 934 throws IOException { 935 Object obj = getExtension(PKIXExtensions.IssuerAlternativeName_Id); 936 return (IssuerAlternativeNameExtension)obj; 937 } 938 939 /** 940 * return the IssuingDistributionPointExtension, if any. 941 * 942 * @return IssuingDistributionPointExtension or null 943 * (if no such extension) 944 * @throws IOException on error 945 */ 946 public IssuingDistributionPointExtension 947 getIssuingDistributionPointExtension() throws IOException { 948 949 Object obj = getExtension(PKIXExtensions.IssuingDistributionPoint_Id); 950 return (IssuingDistributionPointExtension) obj; 951 } 952 953 /** 954 * Return true if a critical extension is found that is 955 * not supported, otherwise return false. 956 */ 957 public boolean hasUnsupportedCriticalExtension() { 958 if (extensions == null) 959 return false; 960 return extensions.hasUnsupportedCriticalExtension(); 961 } 962 963 /** 964 * Gets a Set of the extension(s) marked CRITICAL in the 965 * CRL. In the returned set, each extension is represented by 966 * its OID string. 967 * 968 * @return a set of the extension oid strings in the 969 * CRL that are marked critical. 970 */ 971 public Set<String> getCriticalExtensionOIDs() { 972 if (extensions == null) { 973 return null; 974 } 975 Set<String> extSet = new TreeSet<>(); 976 for (Extension ex : extensions.getAllExtensions()) { 977 if (ex.isCritical()) { 978 extSet.add(ex.getExtensionId().toString()); 979 } 980 } 981 return extSet; 982 } 983 984 /** 985 * Gets a Set of the extension(s) marked NON-CRITICAL in the 986 * CRL. In the returned set, each extension is represented by 987 * its OID string. 988 * 989 * @return a set of the extension oid strings in the 990 * CRL that are NOT marked critical. 991 */ 992 public Set<String> getNonCriticalExtensionOIDs() { 993 if (extensions == null) { 994 return null; 995 } 996 Set<String> extSet = new TreeSet<>(); 997 for (Extension ex : extensions.getAllExtensions()) { 998 if (!ex.isCritical()) { 999 extSet.add(ex.getExtensionId().toString()); 1000 } 1001 } 1002 return extSet; 1003 } 1004 1005 /** 1006 * Gets the DER encoded OCTET string for the extension value 1007 * (<code>extnValue</code>) identified by the passed in oid String. 1008 * The <code>oid</code> string is 1009 * represented by a set of positive whole number separated 1010 * by ".", that means,<br> 1011 * <positive whole number>.<positive whole number>.<...> 1012 * 1013 * @param oid the Object Identifier value for the extension. 1014 * @return the der encoded octet string of the extension value. 1015 */ 1016 public byte[] getExtensionValue(String oid) { 1017 if (extensions == null) 1018 return null; 1019 try { 1020 String extAlias = OIDMap.getName(new ObjectIdentifier(oid)); 1021 Extension crlExt = null; 1022 1023 if (extAlias == null) { // may be unknown 1024 ObjectIdentifier findOID = new ObjectIdentifier(oid); 1025 Extension ex = null; 1026 ObjectIdentifier inCertOID; 1027 for (Enumeration<Extension> e = extensions.getElements(); 1028 e.hasMoreElements();) { 1029 ex = e.nextElement(); 1030 inCertOID = ex.getExtensionId(); 1031 if (inCertOID.equals(findOID)) { 1032 crlExt = ex; 1033 break; 1034 } 1035 } 1036 } else 1037 crlExt = extensions.get(extAlias); 1038 if (crlExt == null) 1039 return null; 1040 byte[] extData = crlExt.getExtensionValue(); 1041 if (extData == null) 1042 return null; 1043 DerOutputStream out = new DerOutputStream(); 1044 out.putOctetString(extData); 1045 return out.toByteArray(); 1046 } catch (Exception e) { 1047 return null; 1048 } 1049 } 1050 1051 /** 1052 * get an extension 1053 * 1054 * @param oid ObjectIdentifier of extension desired 1055 * @return Object of type {@code <extension>} or null, if not found 1056 * @throws IOException on error 1057 */ 1058 public Object getExtension(ObjectIdentifier oid) { 1059 if (extensions == null) 1060 return null; 1061 1062 // XXX Consider cloning this 1063 return extensions.get(OIDMap.getName(oid)); 1064 } 1065 1066 /* 1067 * Parses an X.509 CRL, should be used only by constructors. 1068 */ 1069 private void parse(DerValue val) throws CRLException, IOException { 1070 // check if can over write the certificate 1071 if (readOnly) 1072 throw new CRLException("cannot over-write existing CRL"); 1073 1074 if ( val.getData() == null || val.tag != DerValue.tag_Sequence) 1075 throw new CRLException("Invalid DER-encoded CRL data"); 1076 1077 signedCRL = val.toByteArray(); 1078 DerValue[] seq = new DerValue[3]; 1079 1080 seq[0] = val.data.getDerValue(); 1081 seq[1] = val.data.getDerValue(); 1082 seq[2] = val.data.getDerValue(); 1083 1084 if (val.data.available() != 0) 1085 throw new CRLException("signed overrun, bytes = " 1086 + val.data.available()); 1087 1088 if (seq[0].tag != DerValue.tag_Sequence) 1089 throw new CRLException("signed CRL fields invalid"); 1090 1091 sigAlgId = AlgorithmId.parse(seq[1]); 1092 signature = seq[2].getBitString(); 1093 1094 if (seq[1].data.available() != 0) 1095 throw new CRLException("AlgorithmId field overrun"); 1096 1097 if (seq[2].data.available() != 0) 1098 throw new CRLException("Signature field overrun"); 1099 1100 // the tbsCertsList 1101 tbsCertList = seq[0].toByteArray(); 1102 1103 // parse the information 1104 DerInputStream derStrm = seq[0].data; 1105 DerValue tmp; 1106 byte nextByte; 1107 1108 // version (optional if v1) 1109 version = 0; // by default, version = v1 == 0 1110 nextByte = (byte)derStrm.peekByte(); 1111 if (nextByte == DerValue.tag_Integer) { 1112 version = derStrm.getInteger(); 1113 if (version != 1) // i.e. v2 1114 throw new CRLException("Invalid version"); 1115 } 1116 tmp = derStrm.getDerValue(); 1117 1118 // signature 1119 AlgorithmId tmpId = AlgorithmId.parse(tmp); 1120 1121 // the "inner" and "outer" signature algorithms must match 1122 if (! tmpId.equals(sigAlgId)) 1123 throw new CRLException("Signature algorithm mismatch"); 1124 infoSigAlgId = tmpId; 1125 1126 // issuer 1127 issuer = new X500Name(derStrm); 1128 if (issuer.isEmpty()) { 1129 throw new CRLException("Empty issuer DN not allowed in X509CRLs"); 1130 } 1131 1132 // thisUpdate 1133 // check if UTCTime encoded or GeneralizedTime 1134 1135 nextByte = (byte)derStrm.peekByte(); 1136 if (nextByte == DerValue.tag_UtcTime) { 1137 thisUpdate = derStrm.getUTCTime(); 1138 } else if (nextByte == DerValue.tag_GeneralizedTime) { 1139 thisUpdate = derStrm.getGeneralizedTime(); 1140 } else { 1141 throw new CRLException("Invalid encoding for thisUpdate" 1142 + " (tag=" + nextByte + ")"); 1143 } 1144 1145 if (derStrm.available() == 0) 1146 return; // done parsing no more optional fields present 1147 1148 // nextUpdate (optional) 1149 nextByte = (byte)derStrm.peekByte(); 1150 if (nextByte == DerValue.tag_UtcTime) { 1151 nextUpdate = derStrm.getUTCTime(); 1152 } else if (nextByte == DerValue.tag_GeneralizedTime) { 1153 nextUpdate = derStrm.getGeneralizedTime(); 1154 } // else it is not present 1155 1156 if (derStrm.available() == 0) 1157 return; // done parsing no more optional fields present 1158 1159 // revokedCertificates (optional) 1160 nextByte = (byte)derStrm.peekByte(); 1161 if ((nextByte == DerValue.tag_SequenceOf) 1162 && (! ((nextByte & 0x0c0) == 0x080))) { 1163 DerValue[] badCerts = derStrm.getSequence(4); 1164 1165 X500Principal crlIssuer = getIssuerX500Principal(); 1166 X500Principal badCertIssuer = crlIssuer; 1167 for (int i = 0; i < badCerts.length; i++) { 1168 X509CRLEntryImpl entry = new X509CRLEntryImpl(badCerts[i]); 1169 badCertIssuer = getCertIssuer(entry, badCertIssuer); 1170 entry.setCertificateIssuer(crlIssuer, badCertIssuer); 1171 X509IssuerSerial issuerSerial = new X509IssuerSerial 1172 (badCertIssuer, entry.getSerialNumber()); 1173 revokedMap.put(issuerSerial, entry); 1174 revokedList.add(entry); 1175 } 1176 } 1177 1178 if (derStrm.available() == 0) 1179 return; // done parsing no extensions 1180 1181 // crlExtensions (optional) 1182 tmp = derStrm.getDerValue(); 1183 if (tmp.isConstructed() && tmp.isContextSpecific((byte)0)) { 1184 extensions = new CRLExtensions(tmp.data); 1185 } 1186 readOnly = true; 1187 } 1188 1189 /** 1190 * Extract the issuer X500Principal from an X509CRL. Parses the encoded 1191 * form of the CRL to preserve the principal's ASN.1 encoding. 1192 * 1193 * Called by java.security.cert.X509CRL.getIssuerX500Principal(). 1194 */ 1195 public static X500Principal getIssuerX500Principal(X509CRL crl) { 1196 try { 1197 byte[] encoded = crl.getEncoded(); 1198 DerInputStream derIn = new DerInputStream(encoded); 1199 DerValue tbsCert = derIn.getSequence(3)[0]; 1200 DerInputStream tbsIn = tbsCert.data; 1201 1202 DerValue tmp; 1203 // skip version number if present 1204 byte nextByte = (byte)tbsIn.peekByte(); 1205 if (nextByte == DerValue.tag_Integer) { 1206 tmp = tbsIn.getDerValue(); 1207 } 1208 1209 tmp = tbsIn.getDerValue(); // skip signature 1210 tmp = tbsIn.getDerValue(); // issuer 1211 byte[] principalBytes = tmp.toByteArray(); 1212 return new X500Principal(principalBytes); 1213 } catch (Exception e) { 1214 throw new RuntimeException("Could not parse issuer", e); 1215 } 1216 } 1217 1218 /** 1219 * Returned the encoding of the given certificate for internal use. 1220 * Callers must guarantee that they neither modify it nor expose it 1221 * to untrusted code. Uses getEncodedInternal() if the certificate 1222 * is instance of X509CertImpl, getEncoded() otherwise. 1223 */ 1224 public static byte[] getEncodedInternal(X509CRL crl) throws CRLException { 1225 if (crl instanceof X509CRLImpl) { 1226 return ((X509CRLImpl)crl).getEncodedInternal(); 1227 } else { 1228 return crl.getEncoded(); 1229 } 1230 } 1231 1232 /** 1233 * Utility method to convert an arbitrary instance of X509CRL 1234 * to a X509CRLImpl. Does a cast if possible, otherwise reparses 1235 * the encoding. 1236 */ 1237 public static X509CRLImpl toImpl(X509CRL crl) 1238 throws CRLException { 1239 if (crl instanceof X509CRLImpl) { 1240 return (X509CRLImpl)crl; 1241 } else { 1242 return X509Factory.intern(crl); 1243 } 1244 } 1245 1246 /** 1247 * Returns the X500 certificate issuer DN of a CRL entry. 1248 * 1249 * @param entry the entry to check 1250 * @param prevCertIssuer the previous entry's certificate issuer 1251 * @return the X500Principal in a CertificateIssuerExtension, or 1252 * prevCertIssuer if it does not exist 1253 */ 1254 private X500Principal getCertIssuer(X509CRLEntryImpl entry, 1255 X500Principal prevCertIssuer) throws IOException { 1256 1257 CertificateIssuerExtension ciExt = 1258 entry.getCertificateIssuerExtension(); 1259 if (ciExt != null) { 1260 GeneralNames names = ciExt.get(CertificateIssuerExtension.ISSUER); 1261 X500Name issuerDN = (X500Name) names.get(0).getName(); 1262 return issuerDN.asX500Principal(); 1263 } else { 1264 return prevCertIssuer; 1265 } 1266 } 1267 1268 @Override 1269 public void derEncode(OutputStream out) throws IOException { 1270 if (signedCRL == null) 1271 throw new IOException("Null CRL to encode"); 1272 out.write(signedCRL.clone()); 1273 } 1274 1275 /** 1276 * Immutable X.509 Certificate Issuer DN and serial number pair 1277 */ 1278 private static final class X509IssuerSerial 1279 implements Comparable<X509IssuerSerial> { 1280 final X500Principal issuer; 1281 final BigInteger serial; 1282 volatile int hashcode; 1283 1284 /** 1285 * Create an X509IssuerSerial. 1286 * 1287 * @param issuer the issuer DN 1288 * @param serial the serial number 1289 */ 1290 X509IssuerSerial(X500Principal issuer, BigInteger serial) { 1291 this.issuer = issuer; 1292 this.serial = serial; 1293 } 1294 1295 /** 1296 * Construct an X509IssuerSerial from an X509Certificate. 1297 */ 1298 X509IssuerSerial(X509Certificate cert) { 1299 this(cert.getIssuerX500Principal(), cert.getSerialNumber()); 1300 } 1301 1302 /** 1303 * Returns the issuer. 1304 * 1305 * @return the issuer 1306 */ 1307 X500Principal getIssuer() { 1308 return issuer; 1309 } 1310 1311 /** 1312 * Returns the serial number. 1313 * 1314 * @return the serial number 1315 */ 1316 BigInteger getSerial() { 1317 return serial; 1318 } 1319 1320 /** 1321 * Compares this X509Serial with another and returns true if they 1322 * are equivalent. 1323 * 1324 * @param o the other object to compare with 1325 * @return true if equal, false otherwise 1326 */ 1327 public boolean equals(Object o) { 1328 if (o == this) { 1329 return true; 1330 } 1331 1332 if (!(o instanceof X509IssuerSerial)) { 1333 return false; 1334 } 1335 1336 X509IssuerSerial other = (X509IssuerSerial) o; 1337 if (serial.equals(other.getSerial()) && 1338 issuer.equals(other.getIssuer())) { 1339 return true; 1340 } 1341 return false; 1342 } 1343 1344 /** 1345 * Returns a hash code value for this X509IssuerSerial. 1346 * 1347 * @return the hash code value 1348 */ 1349 public int hashCode() { 1350 int h = hashcode; 1351 if (h == 0) { 1352 h = 17; 1353 h = 37*h + issuer.hashCode(); 1354 h = 37*h + serial.hashCode(); 1355 if (h != 0) { 1356 hashcode = h; 1357 } 1358 } 1359 return h; 1360 } 1361 1362 @Override 1363 public int compareTo(X509IssuerSerial another) { 1364 int cissuer = issuer.toString() 1365 .compareTo(another.issuer.toString()); 1366 if (cissuer != 0) return cissuer; 1367 return this.serial.compareTo(another.serial); 1368 } 1369 } 1370 }