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.IOException;
  29 import java.io.OutputStream;
  30 import java.security.cert.CertificateException;
  31 import java.security.cert.X509Certificate;
  32 import java.util.*;
  33 
  34 import javax.security.auth.x500.X500Principal;
  35 
  36 import sun.net.util.IPAddressUtil;
  37 import sun.security.util.*;
  38 import sun.security.pkcs.PKCS9Attribute;
  39 
  40 /**
  41  * This class defines the Name Constraints Extension.
  42  * <p>
  43  * The name constraints extension provides permitted and excluded
  44  * subtrees that place restrictions on names that may be included within
  45  * a certificate issued by a given CA.  Restrictions may apply to the
  46  * subject distinguished name or subject alternative names.  Any name
  47  * matching a restriction in the excluded subtrees field is invalid
  48  * regardless of information appearing in the permitted subtrees.
  49  * <p>
  50  * The ASN.1 syntax for this is:
  51  * <pre>
  52  * NameConstraints ::= SEQUENCE {
  53  *    permittedSubtrees [0]  GeneralSubtrees OPTIONAL,
  54  *    excludedSubtrees  [1]  GeneralSubtrees OPTIONAL
  55  * }
  56  * GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
  57  * </pre>
  58  *
  59  * @author Amit Kapoor
  60  * @author Hemma Prafullchandra
  61  * @see Extension
  62  * @see CertAttrSet
  63  */
  64 public class NameConstraintsExtension extends Extension
  65 implements CertAttrSet<String>, Cloneable {
  66     /**
  67      * Identifier for this attribute, to be used with the
  68      * get, set, delete methods of Certificate, x509 type.
  69      */
  70     public static final String IDENT = "x509.info.extensions.NameConstraints";
  71     /**
  72      * Attribute names.
  73      */
  74     public static final String NAME = "NameConstraints";
  75     public static final String PERMITTED_SUBTREES = "permitted_subtrees";
  76     public static final String EXCLUDED_SUBTREES = "excluded_subtrees";
  77 
  78     // Private data members
  79     private static final byte TAG_PERMITTED = 0;
  80     private static final byte TAG_EXCLUDED = 1;
  81 
  82     private GeneralSubtrees     permitted = null;
  83     private GeneralSubtrees     excluded = null;
  84 
  85     private boolean hasMin;
  86     private boolean hasMax;
  87     private boolean minMaxValid = false;
  88 
  89     // Recalculate hasMin and hasMax flags.
  90     private void calcMinMax() throws IOException {
  91         hasMin = false;
  92         hasMax = false;
  93         if (excluded != null) {
  94             for (int i = 0; i < excluded.size(); i++) {
  95                 GeneralSubtree subtree = excluded.get(i);
  96                 if (subtree.getMinimum() != 0)
  97                     hasMin = true;
  98                 if (subtree.getMaximum() != -1)
  99                     hasMax = true;
 100             }
 101         }
 102 
 103         if (permitted != null) {
 104             for (int i = 0; i < permitted.size(); i++) {
 105                 GeneralSubtree subtree = permitted.get(i);
 106                 if (subtree.getMinimum() != 0)
 107                     hasMin = true;
 108                 if (subtree.getMaximum() != -1)
 109                     hasMax = true;
 110             }
 111         }
 112         minMaxValid = true;
 113     }
 114 
 115     // Encode this extension value.
 116     private void encodeThis() throws IOException {
 117         minMaxValid = false;
 118         if (permitted == null && excluded == null) {
 119             this.extensionValue = null;
 120             return;
 121         }
 122         DerOutputStream seq = new DerOutputStream();
 123 
 124         DerOutputStream tagged = new DerOutputStream();
 125         if (permitted != null) {
 126             DerOutputStream tmp = new DerOutputStream();
 127             permitted.encode(tmp);
 128             tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
 129                                  true, TAG_PERMITTED), tmp);
 130         }
 131         if (excluded != null) {
 132             DerOutputStream tmp = new DerOutputStream();
 133             excluded.encode(tmp);
 134             tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
 135                                  true, TAG_EXCLUDED), tmp);
 136         }
 137         seq.write(DerValue.tag_Sequence, tagged);
 138         this.extensionValue = seq.toByteArray();
 139     }
 140 
 141     /**
 142      * The default constructor for this class. Both parameters
 143      * are optional and can be set to null.  The extension criticality
 144      * is set to true.
 145      *
 146      * @param permitted the permitted GeneralSubtrees (null for optional).
 147      * @param excluded the excluded GeneralSubtrees (null for optional).
 148      */
 149     public NameConstraintsExtension(GeneralSubtrees permitted,
 150                                     GeneralSubtrees excluded)
 151     throws IOException {
 152         this.permitted = permitted;
 153         this.excluded = excluded;
 154 
 155         this.extensionId = PKIXExtensions.NameConstraints_Id;
 156         this.critical = true;
 157         encodeThis();
 158     }
 159 
 160     /**
 161      * Create the extension from the passed DER encoded value.
 162      *
 163      * @param critical true if the extension is to be treated as critical.
 164      * @param value an array of DER encoded bytes of the actual value.
 165      * @exception ClassCastException if value is not an array of bytes
 166      * @exception IOException on error.
 167      */
 168     public NameConstraintsExtension(Boolean critical, Object value)
 169     throws IOException {
 170         this.extensionId = PKIXExtensions.NameConstraints_Id;
 171         this.critical = critical.booleanValue();
 172 
 173         this.extensionValue = (byte[]) value;
 174         DerValue val = new DerValue(this.extensionValue);
 175         if (val.tag != DerValue.tag_Sequence) {
 176             throw new IOException("Invalid encoding for" +
 177                                   " NameConstraintsExtension.");
 178         }
 179 
 180         // NB. this is always encoded with the IMPLICIT tag
 181         // The checks only make sense if we assume implicit tagging,
 182         // with explicit tagging the form is always constructed.
 183         // Note that all the fields in NameConstraints are defined as
 184         // being OPTIONAL, i.e., there could be an empty SEQUENCE, resulting
 185         // in val.data being null.
 186         if (val.data == null)
 187             return;
 188         while (val.data.available() != 0) {
 189             DerValue opt = val.data.getDerValue();
 190 
 191             if (opt.isContextSpecific(TAG_PERMITTED) && opt.isConstructed()) {
 192                 if (permitted != null) {
 193                     throw new IOException("Duplicate permitted " +
 194                          "GeneralSubtrees in NameConstraintsExtension.");
 195                 }
 196                 opt.resetTag(DerValue.tag_Sequence);
 197                 permitted = new GeneralSubtrees(opt);
 198 
 199             } else if (opt.isContextSpecific(TAG_EXCLUDED) &&
 200                        opt.isConstructed()) {
 201                 if (excluded != null) {
 202                     throw new IOException("Duplicate excluded " +
 203                              "GeneralSubtrees in NameConstraintsExtension.");
 204                 }
 205                 opt.resetTag(DerValue.tag_Sequence);
 206                 excluded = new GeneralSubtrees(opt);
 207             } else
 208                 throw new IOException("Invalid encoding of " +
 209                                       "NameConstraintsExtension.");
 210         }
 211         minMaxValid = false;
 212     }
 213 
 214     /**
 215      * Return the printable string.
 216      */
 217     public String toString() {
 218         return (super.toString() + "NameConstraints: [" +
 219                 ((permitted == null) ? "" :
 220                      ("\n    Permitted:" + permitted.toString())) +
 221                 ((excluded == null) ? "" :
 222                      ("\n    Excluded:" + excluded.toString()))
 223                 + "   ]\n");
 224     }
 225 
 226     /**
 227      * Write the extension to the OutputStream.
 228      *
 229      * @param out the OutputStream to write the extension to.
 230      * @exception IOException on encoding errors.
 231      */
 232     public void encode(OutputStream out) throws IOException {
 233         DerOutputStream tmp = new DerOutputStream();
 234         if (this.extensionValue == null) {
 235             this.extensionId = PKIXExtensions.NameConstraints_Id;
 236             this.critical = true;
 237             encodeThis();
 238         }
 239         super.encode(tmp);
 240         out.write(tmp.toByteArray());
 241     }
 242 
 243     /**
 244      * Set the attribute value.
 245      */
 246     public void set(String name, Object obj) throws IOException {
 247         if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
 248             if (!(obj instanceof GeneralSubtrees)) {
 249                 throw new IOException("Attribute value should be"
 250                                     + " of type GeneralSubtrees.");
 251             }
 252             permitted = (GeneralSubtrees)obj;
 253         } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
 254             if (!(obj instanceof GeneralSubtrees)) {
 255                 throw new IOException("Attribute value should be "
 256                                     + "of type GeneralSubtrees.");
 257             }
 258             excluded = (GeneralSubtrees)obj;
 259         } else {
 260           throw new IOException("Attribute name not recognized by " +
 261                         "CertAttrSet:NameConstraintsExtension.");
 262         }
 263         encodeThis();
 264     }
 265 
 266     /**
 267      * Get the attribute value.
 268      */
 269     public GeneralSubtrees get(String name) throws IOException {
 270         if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
 271             return (permitted);
 272         } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
 273             return (excluded);
 274         } else {
 275           throw new IOException("Attribute name not recognized by " +
 276                         "CertAttrSet:NameConstraintsExtension.");
 277         }
 278     }
 279 
 280     /**
 281      * Delete the attribute value.
 282      */
 283     public void delete(String name) throws IOException {
 284         if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
 285             permitted = null;
 286         } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
 287             excluded = null;
 288         } else {
 289           throw new IOException("Attribute name not recognized by " +
 290                         "CertAttrSet:NameConstraintsExtension.");
 291         }
 292         encodeThis();
 293     }
 294 
 295     /**
 296      * Return an enumeration of names of attributes existing within this
 297      * attribute.
 298      */
 299     public Enumeration<String> getElements() {
 300         AttributeNameEnumeration elements = new AttributeNameEnumeration();
 301         elements.addElement(PERMITTED_SUBTREES);
 302         elements.addElement(EXCLUDED_SUBTREES);
 303 
 304         return (elements.elements());
 305     }
 306 
 307     /**
 308      * Return the name of this attribute.
 309      */
 310     public String getName() {
 311         return (NAME);
 312     }
 313 
 314     /**
 315      * Merge additional name constraints with existing ones.
 316      * This function is used in certification path processing
 317      * to accumulate name constraints from successive certificates
 318      * in the path.  Note that NameConstraints can never be
 319      * expanded by a merge, just remain constant or become more
 320      * limiting.
 321      * <p>
 322      * IETF RFC2459 specifies the processing of Name Constraints as
 323      * follows:
 324      * <p>
 325      * (j)  If permittedSubtrees is present in the certificate, set the
 326      * constrained subtrees state variable to the intersection of its
 327      * previous value and the value indicated in the extension field.
 328      * <p>
 329      * (k)  If excludedSubtrees is present in the certificate, set the
 330      * excluded subtrees state variable to the union of its previous
 331      * value and the value indicated in the extension field.
 332      * <p>
 333      * @param newConstraints additional NameConstraints to be applied
 334      * @throws IOException on error
 335      */
 336     public void merge(NameConstraintsExtension newConstraints)
 337             throws IOException {
 338 
 339         if (newConstraints == null) {
 340             // absence of any explicit constraints implies unconstrained
 341             return;
 342         }
 343 
 344         /*
 345          * If excludedSubtrees is present in the certificate, set the
 346          * excluded subtrees state variable to the union of its previous
 347          * value and the value indicated in the extension field.
 348          */
 349 
 350         GeneralSubtrees newExcluded = newConstraints.get(EXCLUDED_SUBTREES);
 351         if (excluded == null) {
 352             excluded = (newExcluded != null) ?
 353                         (GeneralSubtrees)newExcluded.clone() : null;
 354         } else {
 355             if (newExcluded != null) {
 356                 // Merge new excluded with current excluded (union)
 357                 excluded.union(newExcluded);
 358             }
 359         }
 360 
 361         /*
 362          * If permittedSubtrees is present in the certificate, set the
 363          * constrained subtrees state variable to the intersection of its
 364          * previous value and the value indicated in the extension field.
 365          */
 366 
 367         GeneralSubtrees newPermitted = newConstraints.get(PERMITTED_SUBTREES);
 368         if (permitted == null) {
 369             permitted = (newPermitted != null) ?
 370                         (GeneralSubtrees)newPermitted.clone() : null;
 371         } else {
 372             if (newPermitted != null) {
 373                 // Merge new permitted with current permitted (intersection)
 374                 newExcluded = permitted.intersect(newPermitted);
 375 
 376                 // Merge new excluded subtrees to current excluded (union)
 377                 if (newExcluded != null) {
 378                     if (excluded != null) {
 379                         excluded.union(newExcluded);
 380                     } else {
 381                         excluded = (GeneralSubtrees)newExcluded.clone();
 382                     }
 383                 }
 384             }
 385         }
 386 
 387         // Optional optimization: remove permitted subtrees that are excluded.
 388         // This is not necessary for algorithm correctness, but it makes
 389         // subsequent operations on the NameConstraints faster and require
 390         // less space.
 391         if (permitted != null) {
 392             permitted.reduce(excluded);
 393         }
 394 
 395         // The NameConstraints have been changed, so re-encode them.  Methods in
 396         // this class assume that the encodings have already been done.
 397         encodeThis();
 398 
 399     }
 400 
 401     /**
 402      * check whether a certificate conforms to these NameConstraints.
 403      * This involves verifying that the subject name and subjectAltName
 404      * extension (critical or noncritical) is consistent with the permitted
 405      * subtrees state variables.  Also verify that the subject name and
 406      * subjectAltName extension (critical or noncritical) is consistent with
 407      * the excluded subtrees state variables.
 408      *
 409      * @param cert X509Certificate to be verified
 410      * @returns true if certificate verifies successfully
 411      * @throws IOException on error
 412      */
 413     public boolean verify(X509Certificate cert) throws IOException {
 414 
 415         if (cert == null) {
 416             throw new IOException("Certificate is null");
 417         }
 418 
 419         // Calculate hasMin and hasMax booleans (if necessary)
 420         if (!minMaxValid) {
 421             calcMinMax();
 422         }
 423 
 424         if (hasMin) {
 425             throw new IOException("Non-zero minimum BaseDistance in"
 426                                 + " name constraints not supported");
 427         }
 428 
 429         if (hasMax) {
 430             throw new IOException("Maximum BaseDistance in"
 431                                 + " name constraints not supported");
 432         }
 433 
 434         X500Principal subjectPrincipal = cert.getSubjectX500Principal();
 435         X500Name subject = X500Name.asX500Name(subjectPrincipal);
 436 
 437         // Check subject as an X500Name
 438         if (subject.isEmpty() == false) {
 439             if (verify(subject) == false) {
 440                 return false;
 441             }
 442         }
 443 
 444         GeneralNames altNames = null;
 445         // extract altNames
 446         try {
 447             // extract extensions, if any, from certInfo
 448             // following returns null if certificate contains no extensions
 449             X509CertImpl certImpl = X509CertImpl.toImpl(cert);
 450             SubjectAlternativeNameExtension altNameExt =
 451                 certImpl.getSubjectAlternativeNameExtension();
 452             if (altNameExt != null) {
 453                 // extract altNames from extension; this call does not
 454                 // return an IOException on null altnames
 455                 altNames = altNameExt.get(
 456                         SubjectAlternativeNameExtension.SUBJECT_NAME);
 457             }
 458         } catch (CertificateException ce) {
 459             throw new IOException("Unable to extract extensions from " +
 460                         "certificate: " + ce.getMessage());
 461         }
 462 
 463         if (altNames == null) {
 464             altNames = new GeneralNames();
 465 
 466             // RFC 5280 4.2.1.10:
 467             // When constraints are imposed on the rfc822Name name form,
 468             // but the certificate does not include a subject alternative name,
 469             // the rfc822Name constraint MUST be applied to the attribute of
 470             // type emailAddress in the subject distinguished name.
 471             for (AVA ava : subject.allAvas()) {
 472                 ObjectIdentifier attrOID = ava.getObjectIdentifier();
 473                 if (attrOID.equals(PKCS9Attribute.EMAIL_ADDRESS_OID)) {
 474                     String attrValue = ava.getValueString();
 475                     if (attrValue != null) {
 476                         try {
 477                             altNames.add(new GeneralName(
 478                                     new RFC822Name(attrValue)));
 479                         } catch (IOException ioe) {
 480                             continue;
 481                         }
 482                     }
 483                 }
 484             }
 485         }
 486 
 487         // If there is no IPAddressName or DNSName in subjectAlternativeNames,
 488         // see if the last CN inside subjectName can be used instead.
 489         DerValue derValue = subject.findMostSpecificAttribute
 490                 (X500Name.commonName_oid);
 491         String cn = derValue == null ? null : derValue.getAsString();
 492 
 493         if (cn != null) {
 494             try {
 495                 if (IPAddressUtil.isIPv4LiteralAddress(cn) ||
 496                         IPAddressUtil.isIPv6LiteralAddress(cn)) {
 497                     if (!hasNameType(altNames, GeneralNameInterface.NAME_IP)) {
 498                         altNames.add(new GeneralName(new IPAddressName(cn)));
 499                     }
 500                 } else {
 501                     if (!hasNameType(altNames, GeneralNameInterface.NAME_DNS)) {
 502                         altNames.add(new GeneralName(new DNSName(cn)));
 503                     }
 504                 }
 505             } catch (IOException ioe) {
 506                 // OK, cn is neither IP nor DNS
 507             }
 508         }
 509 
 510         // verify each subjectAltName
 511         for (int i = 0; i < altNames.size(); i++) {
 512             GeneralNameInterface altGNI = altNames.get(i).getName();
 513             if (!verify(altGNI)) {
 514                 return false;
 515             }
 516         }
 517 
 518         // All tests passed.
 519         return true;
 520     }
 521 
 522     private static boolean hasNameType(GeneralNames names, int type) {
 523         for (GeneralName name : names.names()) {
 524             if (name.getType() == type) {
 525                 return true;
 526             }
 527         }
 528         return false;
 529     }
 530 
 531     /**
 532      * check whether a name conforms to these NameConstraints.
 533      * This involves verifying that the name is consistent with the
 534      * permitted and excluded subtrees variables.
 535      *
 536      * @param name GeneralNameInterface name to be verified
 537      * @returns true if certificate verifies successfully
 538      * @throws IOException on error
 539      */
 540     public boolean verify(GeneralNameInterface name) throws IOException {
 541         if (name == null) {
 542             throw new IOException("name is null");
 543         }
 544 
 545         // Verify that the name is consistent with the excluded subtrees
 546         if (excluded != null && excluded.size() > 0) {
 547 
 548             for (int i = 0; i < excluded.size(); i++) {
 549                 GeneralSubtree gs = excluded.get(i);
 550                 if (gs == null)
 551                     continue;
 552                 GeneralName gn = gs.getName();
 553                 if (gn == null)
 554                     continue;
 555                 GeneralNameInterface exName = gn.getName();
 556                 if (exName == null)
 557                     continue;
 558 
 559                 // if name matches or narrows any excluded subtree,
 560                 // return false
 561                 switch (exName.constrains(name)) {
 562                 case GeneralNameInterface.NAME_DIFF_TYPE:
 563                 case GeneralNameInterface.NAME_WIDENS: // name widens excluded
 564                 case GeneralNameInterface.NAME_SAME_TYPE:
 565                     break;
 566                 case GeneralNameInterface.NAME_MATCH:
 567                 case GeneralNameInterface.NAME_NARROWS: // subject name excluded
 568                     return false;
 569                 }
 570             }
 571         }
 572 
 573         // Verify that the name is consistent with the permitted subtrees
 574         if (permitted != null && permitted.size() > 0) {
 575 
 576             boolean sameType = false;
 577 
 578             for (int i = 0; i < permitted.size(); i++) {
 579                 GeneralSubtree gs = permitted.get(i);
 580                 if (gs == null)
 581                     continue;
 582                 GeneralName gn = gs.getName();
 583                 if (gn == null)
 584                     continue;
 585                 GeneralNameInterface perName = gn.getName();
 586                 if (perName == null)
 587                     continue;
 588 
 589                 // if Name matches any type in permitted,
 590                 // and Name does not match or narrow some permitted subtree,
 591                 // return false
 592                 switch (perName.constrains(name)) {
 593                 case GeneralNameInterface.NAME_DIFF_TYPE:
 594                     continue; // continue checking other permitted names
 595                 case GeneralNameInterface.NAME_WIDENS: // name widens permitted
 596                 case GeneralNameInterface.NAME_SAME_TYPE:
 597                     sameType = true;
 598                     continue; // continue to look for a match or narrow
 599                 case GeneralNameInterface.NAME_MATCH:
 600                 case GeneralNameInterface.NAME_NARROWS:
 601                     // name narrows permitted
 602                     return true; // name is definitely OK, so break out of loop
 603                 }
 604             }
 605             if (sameType) {
 606                 return false;
 607             }
 608         }
 609         return true;
 610     }
 611 
 612     /**
 613      * Clone all objects that may be modified during certificate validation.
 614      */
 615     public Object clone() {
 616         try {
 617             NameConstraintsExtension newNCE =
 618                 (NameConstraintsExtension) super.clone();
 619 
 620             if (permitted != null) {
 621                 newNCE.permitted = (GeneralSubtrees) permitted.clone();
 622             }
 623             if (excluded != null) {
 624                 newNCE.excluded = (GeneralSubtrees) excluded.clone();
 625             }
 626             return newNCE;
 627         } catch (CloneNotSupportedException cnsee) {
 628             throw new RuntimeException("CloneNotSupportedException while " +
 629                 "cloning NameConstraintsException. This should never happen.");
 630         }
 631     }
 632 }