J. Duke | 319a3b9 | 2007-12-01 00:00:00 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2005-2007 Sun Microsystems, Inc. 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. |
| 8 | * |
| 9 | * This code is distributed in the hope that it will be useful, but WITHOUT |
| 10 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 11 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| 12 | * version 2 for more details (a copy is included in the LICENSE file that |
| 13 | * accompanied this code). |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License version |
| 16 | * 2 along with this work; if not, write to the Free Software Foundation, |
| 17 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
| 18 | * |
| 19 | * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, |
| 20 | * CA 95054 USA or visit www.sun.com if you need additional information or |
| 21 | * have any questions. |
| 22 | */ |
| 23 | |
| 24 | import java.io.*; |
| 25 | import java.security.*; |
| 26 | import java.security.cert.*; |
| 27 | import java.util.*; |
| 28 | import javax.crypto.SecretKey; |
| 29 | import javax.xml.crypto.*; |
| 30 | import javax.xml.crypto.dsig.*; |
| 31 | import javax.xml.crypto.dom.*; |
| 32 | import javax.xml.crypto.dsig.keyinfo.*; |
| 33 | import javax.xml.parsers.DocumentBuilderFactory; |
| 34 | import javax.xml.parsers.DocumentBuilder; |
| 35 | import org.w3c.dom.Document; |
| 36 | import org.w3c.dom.Node; |
| 37 | import org.w3c.dom.Element; |
| 38 | import org.w3c.dom.traversal.*; |
| 39 | import sun.security.util.DerValue; |
| 40 | import sun.security.x509.X500Name; |
| 41 | |
| 42 | /** |
| 43 | * This is a class which supplies several KeySelector implementations |
| 44 | */ |
| 45 | class KeySelectors { |
| 46 | |
| 47 | /** |
| 48 | * KeySelector which would always return the secret key specified in its |
| 49 | * constructor. |
| 50 | */ |
| 51 | static class SecretKeySelector extends KeySelector { |
| 52 | private SecretKey key; |
| 53 | SecretKeySelector(byte[] bytes) { |
| 54 | key = wrapBytes(bytes); |
| 55 | } |
| 56 | SecretKeySelector(SecretKey key) { |
| 57 | this.key = key; |
| 58 | } |
| 59 | |
| 60 | public KeySelectorResult select(KeyInfo ki, |
| 61 | KeySelector.Purpose purpose, |
| 62 | AlgorithmMethod method, |
| 63 | XMLCryptoContext context) |
| 64 | throws KeySelectorException { |
| 65 | return new SimpleKSResult(key); |
| 66 | } |
| 67 | |
| 68 | private SecretKey wrapBytes(final byte[] bytes) { |
| 69 | return new SecretKey() { |
| 70 | public String getFormat() { |
| 71 | return "RAW"; |
| 72 | } |
| 73 | |
| 74 | public String getAlgorithm() { |
| 75 | return "Secret key"; |
| 76 | } |
| 77 | |
| 78 | public byte[] getEncoded() { |
| 79 | return (byte[]) bytes.clone(); |
| 80 | } |
| 81 | }; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * KeySelector which would retrieve the X509Certificate out of the |
| 87 | * KeyInfo element and return the public key. |
| 88 | * NOTE: If there is an X509CRL in the KeyInfo element, then revoked |
| 89 | * certificate will be ignored. |
| 90 | */ |
| 91 | static class RawX509KeySelector extends KeySelector { |
| 92 | |
| 93 | public KeySelectorResult select(KeyInfo keyInfo, |
| 94 | KeySelector.Purpose purpose, |
| 95 | AlgorithmMethod method, |
| 96 | XMLCryptoContext context) |
| 97 | throws KeySelectorException { |
| 98 | if (keyInfo == null) { |
| 99 | throw new KeySelectorException("Null KeyInfo object!"); |
| 100 | } |
| 101 | // search for X509Data in keyinfo |
| 102 | Iterator iter = keyInfo.getContent().iterator(); |
| 103 | while (iter.hasNext()) { |
| 104 | XMLStructure kiType = (XMLStructure) iter.next(); |
| 105 | if (kiType instanceof X509Data) { |
| 106 | X509Data xd = (X509Data) kiType; |
| 107 | Object[] entries = xd.getContent().toArray(); |
| 108 | X509CRL crl = null; |
| 109 | // Looking for CRL before finding certificates |
| 110 | for (int i = 0; (i<entries.length&&crl != null); i++) { |
| 111 | if (entries[i] instanceof X509CRL) { |
| 112 | crl = (X509CRL) entries[i]; |
| 113 | } |
| 114 | } |
| 115 | Iterator xi = xd.getContent().iterator(); |
| 116 | boolean hasCRL = false; |
| 117 | while (xi.hasNext()) { |
| 118 | Object o = xi.next(); |
| 119 | // skip non-X509Certificate entries |
| 120 | if (o instanceof X509Certificate) { |
| 121 | if ((purpose != KeySelector.Purpose.VERIFY) && |
| 122 | (crl != null) && |
| 123 | crl.isRevoked((X509Certificate)o)) { |
| 124 | continue; |
| 125 | } else { |
| 126 | return new SimpleKSResult |
| 127 | (((X509Certificate)o).getPublicKey()); |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | throw new KeySelectorException("No X509Certificate found!"); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * KeySelector which would retrieve the public key out of the |
| 139 | * KeyValue element and return it. |
| 140 | * NOTE: If the key algorithm doesn't match signature algorithm, |
| 141 | * then the public key will be ignored. |
| 142 | */ |
| 143 | static class KeyValueKeySelector extends KeySelector { |
| 144 | public KeySelectorResult select(KeyInfo keyInfo, |
| 145 | KeySelector.Purpose purpose, |
| 146 | AlgorithmMethod method, |
| 147 | XMLCryptoContext context) |
| 148 | throws KeySelectorException { |
| 149 | if (keyInfo == null) { |
| 150 | throw new KeySelectorException("Null KeyInfo object!"); |
| 151 | } |
| 152 | SignatureMethod sm = (SignatureMethod) method; |
| 153 | List list = keyInfo.getContent(); |
| 154 | |
| 155 | for (int i = 0; i < list.size(); i++) { |
| 156 | XMLStructure xmlStructure = (XMLStructure) list.get(i); |
| 157 | if (xmlStructure instanceof KeyValue) { |
| 158 | PublicKey pk = null; |
| 159 | try { |
| 160 | pk = ((KeyValue)xmlStructure).getPublicKey(); |
| 161 | } catch (KeyException ke) { |
| 162 | throw new KeySelectorException(ke); |
| 163 | } |
| 164 | // make sure algorithm is compatible with method |
| 165 | if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) { |
| 166 | return new SimpleKSResult(pk); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | throw new KeySelectorException("No KeyValue element found!"); |
| 171 | } |
| 172 | |
| 173 | //@@@FIXME: this should also work for key types other than DSA/RSA |
| 174 | static boolean algEquals(String algURI, String algName) { |
| 175 | if (algName.equalsIgnoreCase("DSA") && |
| 176 | algURI.equals(SignatureMethod.DSA_SHA1)) { |
| 177 | return true; |
| 178 | } else if (algName.equalsIgnoreCase("RSA") && |
| 179 | (algURI.equals(SignatureMethod.RSA_SHA1) || |
| 180 | algURI.equals |
| 181 | ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") || |
| 182 | algURI.equals |
| 183 | ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384") || |
| 184 | algURI.equals |
| 185 | ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"))) { |
| 186 | return true; |
| 187 | } else { |
| 188 | return false; |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /** |
| 194 | * KeySelector which would perform special lookup as documented |
| 195 | * by the ie/baltimore/merlin-examples testcases and return the |
| 196 | * matching public key. |
| 197 | */ |
| 198 | static class CollectionKeySelector extends KeySelector { |
| 199 | private CertificateFactory certFac; |
| 200 | private File certDir; |
| 201 | private Vector certs; |
| 202 | private static final int MATCH_SUBJECT = 0; |
| 203 | private static final int MATCH_ISSUER = 1; |
| 204 | private static final int MATCH_SERIAL = 2; |
| 205 | private static final int MATCH_SUBJECT_KEY_ID = 3; |
| 206 | private static final int MATCH_CERTIFICATE = 4; |
| 207 | |
| 208 | CollectionKeySelector(File dir) { |
| 209 | certDir = dir; |
| 210 | try { |
| 211 | certFac = CertificateFactory.getInstance("X509"); |
| 212 | } catch (CertificateException ex) { |
| 213 | // not going to happen |
| 214 | } |
| 215 | certs = new Vector(); |
| 216 | File[] files = new File(certDir, "certs").listFiles(); |
| 217 | for (int i = 0; i < files.length; i++) { |
| 218 | try { |
| 219 | certs.add(certFac.generateCertificate |
| 220 | (new FileInputStream(files[i]))); |
| 221 | } catch (Exception ex) { } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | Vector match(int matchType, Object value, Vector pool) { |
| 226 | Vector matchResult = new Vector(); |
| 227 | for (int j=0; j < pool.size(); j++) { |
| 228 | X509Certificate c = (X509Certificate) pool.get(j); |
| 229 | switch (matchType) { |
| 230 | case MATCH_SUBJECT: |
| 231 | try { |
| 232 | if (c.getSubjectDN().equals(new X500Name((String)value))) { |
| 233 | matchResult.add(c); |
| 234 | } |
| 235 | } catch (IOException ioe) { } |
| 236 | break; |
| 237 | case MATCH_ISSUER: |
| 238 | try { |
| 239 | if (c.getIssuerDN().equals(new X500Name((String)value))) { |
| 240 | matchResult.add(c); |
| 241 | } |
| 242 | } catch (IOException ioe) { } |
| 243 | break; |
| 244 | case MATCH_SERIAL: |
| 245 | if (c.getSerialNumber().equals(value)) { |
| 246 | matchResult.add(c); |
| 247 | } |
| 248 | |
| 249 | break; |
| 250 | case MATCH_SUBJECT_KEY_ID: |
| 251 | byte[] extension = c.getExtensionValue("2.5.29.14"); |
| 252 | if (extension != null) { |
| 253 | try { |
| 254 | DerValue derValue = new DerValue(extension); |
| 255 | DerValue derValue2 = new DerValue(derValue.getOctetString()); |
| 256 | byte[] extVal = derValue2.getOctetString(); |
| 257 | |
| 258 | if (Arrays.equals(extVal, (byte[]) value)) { |
| 259 | matchResult.add(c); |
| 260 | } |
| 261 | } catch (IOException ex) { } |
| 262 | } |
| 263 | break; |
| 264 | case MATCH_CERTIFICATE: |
| 265 | if (c.equals(value)) { |
| 266 | matchResult.add(c); |
| 267 | } |
| 268 | break; |
| 269 | } |
| 270 | } |
| 271 | return matchResult; |
| 272 | } |
| 273 | |
| 274 | public KeySelectorResult select(KeyInfo keyInfo, |
| 275 | KeySelector.Purpose purpose, |
| 276 | AlgorithmMethod method, |
| 277 | XMLCryptoContext context) |
| 278 | throws KeySelectorException { |
| 279 | if (keyInfo == null) { |
| 280 | throw new KeySelectorException("Null KeyInfo object!"); |
| 281 | } |
| 282 | Iterator iter = keyInfo.getContent().iterator(); |
| 283 | while (iter.hasNext()) { |
| 284 | XMLStructure xmlStructure = (XMLStructure) iter.next(); |
| 285 | try { |
| 286 | if (xmlStructure instanceof KeyName) { |
| 287 | String name = ((KeyName)xmlStructure).getName(); |
| 288 | PublicKey pk = null; |
| 289 | try { |
| 290 | // Lookup the public key using the key name 'Xxx', |
| 291 | // i.e. the public key is in "certs/xxx.crt". |
| 292 | File certFile = new File(new File(certDir, "certs"), |
| 293 | name.toLowerCase()+".crt"); |
| 294 | X509Certificate cert = (X509Certificate) |
| 295 | certFac.generateCertificate |
| 296 | (new FileInputStream(certFile)); |
| 297 | pk = cert.getPublicKey(); |
| 298 | } catch (FileNotFoundException e) { |
| 299 | // assume KeyName contains subject DN and search |
| 300 | // collection of certs for match |
| 301 | Vector result = |
| 302 | match(MATCH_SUBJECT, name, certs); |
| 303 | int numOfMatches = (result==null? 0:result.size()); |
| 304 | if (numOfMatches != 1) { |
| 305 | throw new KeySelectorException |
| 306 | ((numOfMatches==0?"No":"More than one") + |
| 307 | " match found"); |
| 308 | } |
| 309 | pk =((X509Certificate)result.get(0)).getPublicKey(); |
| 310 | } |
| 311 | return new SimpleKSResult(pk); |
| 312 | } else if (xmlStructure instanceof RetrievalMethod) { |
| 313 | // Lookup the public key using the retrievel method. |
| 314 | // NOTE: only X509Certificate type is supported. |
| 315 | RetrievalMethod rm = (RetrievalMethod) xmlStructure; |
| 316 | String type = rm.getType(); |
| 317 | if (type.equals(X509Data.RAW_X509_CERTIFICATE_TYPE)) { |
| 318 | String uri = rm.getURI(); |
| 319 | X509Certificate cert = (X509Certificate) |
| 320 | certFac.generateCertificate |
| 321 | (new FileInputStream(new File(certDir, uri))); |
| 322 | return new SimpleKSResult(cert.getPublicKey()); |
| 323 | } else { |
| 324 | throw new KeySelectorException |
| 325 | ("Unsupported RetrievalMethod type"); |
| 326 | } |
| 327 | } else if (xmlStructure instanceof X509Data) { |
| 328 | List content = ((X509Data)xmlStructure).getContent(); |
| 329 | int size = content.size(); |
| 330 | Vector result = null; |
| 331 | // Lookup the public key using the information |
| 332 | // specified in X509Data element, i.e. searching |
| 333 | // over the collection of certificate files under |
| 334 | // "certs" subdirectory and return those match. |
| 335 | for (int k = 0; k<size; k++) { |
| 336 | Object obj = content.get(k); |
| 337 | if (obj instanceof String) { |
| 338 | result = match(MATCH_SUBJECT, obj, certs); |
| 339 | } else if (obj instanceof byte[]) { |
| 340 | result = match(MATCH_SUBJECT_KEY_ID, obj, |
| 341 | certs); |
| 342 | } else if (obj instanceof X509Certificate) { |
| 343 | result = match(MATCH_CERTIFICATE, obj, certs); |
| 344 | } else if (obj instanceof X509IssuerSerial) { |
| 345 | X509IssuerSerial is = (X509IssuerSerial) obj; |
| 346 | result = match(MATCH_SERIAL, |
| 347 | is.getSerialNumber(), certs); |
| 348 | result = match(MATCH_ISSUER, |
| 349 | is.getIssuerName(), result); |
| 350 | } else { |
| 351 | throw new KeySelectorException("Unsupported X509Data: " + obj); |
| 352 | } |
| 353 | } |
| 354 | int numOfMatches = (result==null? 0:result.size()); |
| 355 | if (numOfMatches != 1) { |
| 356 | throw new KeySelectorException |
| 357 | ((numOfMatches==0?"No":"More than one") + |
| 358 | " match found"); |
| 359 | } |
| 360 | return new SimpleKSResult(((X509Certificate) |
| 361 | result.get(0)).getPublicKey()); |
| 362 | } |
| 363 | } catch (Exception ex) { |
| 364 | throw new KeySelectorException(ex); |
| 365 | } |
| 366 | } |
| 367 | throw new KeySelectorException("No matching key found!"); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | static class ByteUtil { |
| 372 | |
| 373 | private static String mapping = "0123456789ABCDEF"; |
| 374 | private static int numBytesPerRow = 6; |
| 375 | |
| 376 | private static String getHex(byte value) { |
| 377 | int low = value & 0x0f; |
| 378 | int high = ((value >> 4) & 0x0f); |
| 379 | char[] res = new char[2]; |
| 380 | res[0] = mapping.charAt(high); |
| 381 | res[1] = mapping.charAt(low); |
| 382 | return new String(res); |
| 383 | } |
| 384 | |
| 385 | static String dumpArray(byte[] in) { |
| 386 | int numDumped = 0; |
| 387 | StringBuffer buf = new StringBuffer(512); |
| 388 | buf.append("{"); |
| 389 | for (int i=0;i<(in.length/numBytesPerRow); i++) { |
| 390 | for (int j=0; j<(numBytesPerRow); j++) { |
| 391 | buf.append("(byte)0x" + getHex(in[i*numBytesPerRow+j]) + |
| 392 | ", "); |
| 393 | } |
| 394 | numDumped += numBytesPerRow; |
| 395 | } |
| 396 | while (numDumped < in.length) { |
| 397 | buf.append("(byte)0x" + getHex(in[numDumped]) + " "); |
| 398 | numDumped += 1; |
| 399 | } |
| 400 | buf.append("}"); |
| 401 | return buf.toString(); |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | class SimpleKSResult implements KeySelectorResult { |
| 407 | private final Key key; |
| 408 | |
| 409 | SimpleKSResult(Key key) { this.key = key; } |
| 410 | |
| 411 | public Key getKey() { return key; } |
| 412 | } |