1 /*
   2  * reserved comment block
   3  * DO NOT REMOVE OR ALTER!
   4  */
   5 /**
   6  * Licensed to the Apache Software Foundation (ASF) under one
   7  * or more contributor license agreements. See the NOTICE file
   8  * distributed with this work for additional information
   9  * regarding copyright ownership. The ASF licenses this file
  10  * to you under the Apache License, Version 2.0 (the
  11  * "License"); you may not use this file except in compliance
  12  * with the License. You may obtain a copy of the License at
  13  *
  14  * http://www.apache.org/licenses/LICENSE-2.0
  15  *
  16  * Unless required by applicable law or agreed to in writing,
  17  * software distributed under the License is distributed on an
  18  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19  * KIND, either express or implied. See the License for the
  20  * specific language governing permissions and limitations
  21  * under the License.
  22  */
  23 /*
  24  * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  25  */
  26 /*
  27  * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $
  28  */
  29 package org.jcp.xml.dsig.internal.dom;
  30 
  31 import java.io.ByteArrayInputStream;
  32 import java.security.cert.*;
  33 import java.util.*;
  34 import javax.xml.crypto.*;
  35 import javax.xml.crypto.dom.DOMCryptoContext;
  36 import javax.xml.crypto.dsig.*;
  37 import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial;
  38 import javax.xml.crypto.dsig.keyinfo.X509Data;
  39 import javax.security.auth.x500.X500Principal;
  40 import org.w3c.dom.Document;
  41 import org.w3c.dom.Element;
  42 import org.w3c.dom.Node;
  43 import org.w3c.dom.NodeList;
  44 
  45 import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
  46 import com.sun.org.apache.xml.internal.security.utils.Base64;
  47 
  48 /**
  49  * DOM-based implementation of X509Data.
  50  *
  51  * @author Sean Mullan
  52  */
  53 //@@@ check for illegal combinations of data violating MUSTs in W3c spec
  54 public final class DOMX509Data extends DOMStructure implements X509Data {
  55 
  56     private final List<Object> content;
  57     private CertificateFactory cf;
  58 
  59     /**
  60      * Creates a DOMX509Data.
  61      *
  62      * @param content a list of one or more X.509 data types. Valid types are
  63      *    {@link String} (subject names), <code>byte[]</code> (subject key ids),
  64      *    {@link java.security.cert.X509Certificate}, {@link X509CRL},
  65      *    or {@link javax.xml.dsig.XMLStructure} ({@link X509IssuerSerial}
  66      *    objects or elements from an external namespace). The list is
  67      *    defensively copied to protect against subsequent modification.
  68      * @return a <code>X509Data</code>
  69      * @throws NullPointerException if <code>content</code> is <code>null</code>
  70      * @throws IllegalArgumentException if <code>content</code> is empty
  71      * @throws ClassCastException if <code>content</code> contains any entries
  72      *    that are not of one of the valid types mentioned above
  73      */
  74     public DOMX509Data(List<?> content) {
  75         if (content == null) {
  76             throw new NullPointerException("content cannot be null");
  77         }
  78         List<Object> contentCopy = new ArrayList<Object>(content);
  79         if (contentCopy.isEmpty()) {
  80             throw new IllegalArgumentException("content cannot be empty");
  81         }
  82         for (int i = 0, size = contentCopy.size(); i < size; i++) {
  83             Object x509Type = contentCopy.get(i);
  84             if (x509Type instanceof String) {
  85                 new X500Principal((String)x509Type);
  86             } else if (!(x509Type instanceof byte[]) &&
  87                 !(x509Type instanceof X509Certificate) &&
  88                 !(x509Type instanceof X509CRL) &&
  89                 !(x509Type instanceof XMLStructure)) {
  90                 throw new ClassCastException
  91                     ("content["+i+"] is not a valid X509Data type");
  92             }
  93         }
  94         this.content = Collections.unmodifiableList(contentCopy);
  95     }
  96 
  97     /**
  98      * Creates a <code>DOMX509Data</code> from an element.
  99      *
 100      * @param xdElem an X509Data element
 101      * @throws MarshalException if there is an error while unmarshalling
 102      */
 103     public DOMX509Data(Element xdElem) throws MarshalException {
 104         // get all children nodes
 105         NodeList nl = xdElem.getChildNodes();
 106         int length = nl.getLength();
 107         List<Object> content = new ArrayList<Object>(length);
 108         for (int i = 0; i < length; i++) {
 109             Node child = nl.item(i);
 110             // ignore all non-Element nodes
 111             if (child.getNodeType() != Node.ELEMENT_NODE) {
 112                 continue;
 113             }
 114 
 115             Element childElem = (Element)child;
 116             String localName = childElem.getLocalName();
 117             if (localName.equals("X509Certificate")) {
 118                 content.add(unmarshalX509Certificate(childElem));
 119             } else if (localName.equals("X509IssuerSerial")) {
 120                 content.add(new DOMX509IssuerSerial(childElem));
 121             } else if (localName.equals("X509SubjectName")) {
 122                 content.add(childElem.getFirstChild().getNodeValue());
 123             } else if (localName.equals("X509SKI")) {
 124                 try {
 125                     content.add(Base64.decode(childElem));
 126                 } catch (Base64DecodingException bde) {
 127                     throw new MarshalException("cannot decode X509SKI", bde);
 128                 }
 129             } else if (localName.equals("X509CRL")) {
 130                 content.add(unmarshalX509CRL(childElem));
 131             } else {
 132                 content.add(new javax.xml.crypto.dom.DOMStructure(childElem));
 133             }
 134         }
 135         this.content = Collections.unmodifiableList(content);
 136     }
 137 
 138     public List getContent() {
 139         return content;
 140     }
 141 
 142     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
 143         throws MarshalException
 144     {
 145         Document ownerDoc = DOMUtils.getOwnerDocument(parent);
 146         Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data",
 147                                                 XMLSignature.XMLNS, dsPrefix);
 148 
 149         // append children and preserve order
 150         for (int i = 0, size = content.size(); i < size; i++) {
 151             Object object = content.get(i);
 152             if (object instanceof X509Certificate) {
 153                 marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix);
 154             } else if (object instanceof XMLStructure) {
 155                 if (object instanceof X509IssuerSerial) {
 156                     ((DOMX509IssuerSerial)object).marshal
 157                         (xdElem, dsPrefix, context);
 158                 } else {
 159                     javax.xml.crypto.dom.DOMStructure domContent =
 160                         (javax.xml.crypto.dom.DOMStructure)object;
 161                     DOMUtils.appendChild(xdElem, domContent.getNode());
 162                 }
 163             } else if (object instanceof byte[]) {
 164                 marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix);
 165             } else if (object instanceof String) {
 166                 marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix);
 167             } else if (object instanceof X509CRL) {
 168                 marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix);
 169             }
 170         }
 171 
 172         parent.appendChild(xdElem);
 173     }
 174 
 175     private void marshalSKI(byte[] skid, Node parent, Document doc,
 176                             String dsPrefix)
 177     {
 178         Element skidElem = DOMUtils.createElement(doc, "X509SKI",
 179                                                   XMLSignature.XMLNS, dsPrefix);
 180         skidElem.appendChild(doc.createTextNode(Base64.encode(skid)));
 181         parent.appendChild(skidElem);
 182     }
 183 
 184     private void marshalSubjectName(String name, Node parent, Document doc,
 185                                     String dsPrefix)
 186     {
 187         Element snElem = DOMUtils.createElement(doc, "X509SubjectName",
 188                                                 XMLSignature.XMLNS, dsPrefix);
 189         snElem.appendChild(doc.createTextNode(name));
 190         parent.appendChild(snElem);
 191     }
 192 
 193     private void marshalCert(X509Certificate cert, Node parent, Document doc,
 194                              String dsPrefix)
 195         throws MarshalException
 196     {
 197         Element certElem = DOMUtils.createElement(doc, "X509Certificate",
 198                                                   XMLSignature.XMLNS, dsPrefix);
 199         try {
 200             certElem.appendChild(doc.createTextNode
 201                                  (Base64.encode(cert.getEncoded())));
 202         } catch (CertificateEncodingException e) {
 203             throw new MarshalException("Error encoding X509Certificate", e);
 204         }
 205         parent.appendChild(certElem);
 206     }
 207 
 208     private void marshalCRL(X509CRL crl, Node parent, Document doc,
 209                             String dsPrefix)
 210         throws MarshalException
 211     {
 212         Element crlElem = DOMUtils.createElement(doc, "X509CRL",
 213                                                  XMLSignature.XMLNS, dsPrefix);
 214         try {
 215             crlElem.appendChild(doc.createTextNode
 216                                 (Base64.encode(crl.getEncoded())));
 217         } catch (CRLException e) {
 218             throw new MarshalException("Error encoding X509CRL", e);
 219         }
 220         parent.appendChild(crlElem);
 221     }
 222 
 223     private X509Certificate unmarshalX509Certificate(Element elem)
 224         throws MarshalException
 225     {
 226         try {
 227             ByteArrayInputStream bs = unmarshalBase64Binary(elem);
 228             return (X509Certificate)cf.generateCertificate(bs);
 229         } catch (CertificateException e) {
 230             throw new MarshalException("Cannot create X509Certificate", e);
 231         }
 232     }
 233 
 234     private X509CRL unmarshalX509CRL(Element elem) throws MarshalException {
 235         try {
 236             ByteArrayInputStream bs = unmarshalBase64Binary(elem);
 237             return (X509CRL)cf.generateCRL(bs);
 238         } catch (CRLException e) {
 239             throw new MarshalException("Cannot create X509CRL", e);
 240         }
 241     }
 242 
 243     private ByteArrayInputStream unmarshalBase64Binary(Element elem)
 244         throws MarshalException {
 245         try {
 246             if (cf == null) {
 247                 cf = CertificateFactory.getInstance("X.509");
 248             }
 249             return new ByteArrayInputStream(Base64.decode(elem));
 250         } catch (CertificateException e) {
 251             throw new MarshalException("Cannot create CertificateFactory", e);
 252         } catch (Base64DecodingException bde) {
 253             throw new MarshalException("Cannot decode Base64-encoded val", bde);
 254         }
 255     }
 256 
 257     @Override
 258     public boolean equals(Object o) {
 259         if (this == o) {
 260             return true;
 261         }
 262 
 263         if (!(o instanceof X509Data)) {
 264             return false;
 265         }
 266         X509Data oxd = (X509Data)o;
 267 
 268         @SuppressWarnings("unchecked") List<Object> ocontent = oxd.getContent();
 269         int size = content.size();
 270         if (size != ocontent.size()) {
 271             return false;
 272         }
 273 
 274         for (int i = 0; i < size; i++) {
 275             Object x = content.get(i);
 276             Object ox = ocontent.get(i);
 277             if (x instanceof byte[]) {
 278                 if (!(ox instanceof byte[]) ||
 279                     !Arrays.equals((byte[])x, (byte[])ox)) {
 280                     return false;
 281                 }
 282             } else {
 283                 if (!(x.equals(ox))) {
 284                     return false;
 285                 }
 286             }
 287         }
 288 
 289         return true;
 290     }
 291 
 292     @Override
 293     public int hashCode() {
 294         int result = 17;
 295         result = 31 * result + content.hashCode();
 296 
 297         return result;
 298     }
 299 }