1 /*
   2  * Copyright (c) 1997, 2011, 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 java.util.jar;
  27 
  28 import java.io.*;
  29 import java.net.URL;
  30 import java.util.*;
  31 import java.security.*;
  32 import java.security.cert.CertificateException;
  33 import java.util.zip.ZipEntry;
  34 
  35 import sun.security.util.ManifestDigester;
  36 import sun.security.util.ManifestEntryVerifier;
  37 import sun.security.util.SignatureFileVerifier;
  38 import sun.security.util.Debug;
  39 
  40 /**
  41  *
  42  * @author      Roland Schemers
  43  */
  44 class JarVerifier {
  45 
  46     /* Are we debugging ? */
  47     static final Debug debug = Debug.getInstance("jar");
  48 
  49     /* a table mapping names to code signers, for jar entries that have
  50        had their actual hashes verified */
  51     private Hashtable<String, CodeSigner[]> verifiedSigners;
  52 
  53     /* a table mapping names to code signers, for jar entries that have
  54        passed the .SF/.DSA/.EC -> MANIFEST check */
  55     private Hashtable<String, CodeSigner[]> sigFileSigners;
  56 
  57     /* a hash table to hold .SF bytes */
  58     private Hashtable<String, byte[]> sigFileData;
  59 
  60     /** "queue" of pending PKCS7 blocks that we couldn't parse
  61      *  until we parsed the .SF file */
  62     private ArrayList<SignatureFileVerifier> pendingBlocks;
  63 
  64     /* cache of CodeSigner objects */
  65     private ArrayList<CodeSigner[]> signerCache;
  66 
  67     /* Are we parsing a block? */
  68     private boolean parsingBlockOrSF = false;
  69 
  70     /* Are we done parsing META-INF entries? */
  71     private boolean parsingMeta = true;
  72 
  73     /* Are there are files to verify? */
  74     private boolean anyToVerify = true;
  75 
  76     /* The output stream to use when keeping track of files we are interested
  77        in */
  78     private ByteArrayOutputStream baos;
  79 
  80     /** The ManifestDigester object */
  81     private volatile ManifestDigester manDig;
  82 
  83     /** the bytes for the manDig object */
  84     byte manifestRawBytes[] = null;
  85 
  86     /** controls eager signature validation */
  87     boolean eagerValidation;
  88 
  89     /** makes code source singleton instances unique to us */
  90     private Object csdomain = new Object();
  91 
  92     /** collect -DIGEST-MANIFEST values for blacklist */
  93     private List<Object> manifestDigests;
  94 
  95     public JarVerifier(byte rawBytes[]) {
  96         manifestRawBytes = rawBytes;
  97         sigFileSigners = new Hashtable<>();
  98         verifiedSigners = new Hashtable<>();
  99         sigFileData = new Hashtable<>(11);
 100         pendingBlocks = new ArrayList<>();
 101         baos = new ByteArrayOutputStream();
 102         manifestDigests = new ArrayList<>();
 103     }
 104 
 105     /**
 106      * This method scans to see which entry we're parsing and
 107      * keeps various state information depending on what type of
 108      * file is being parsed.
 109      */
 110     public void beginEntry(JarEntry je, ManifestEntryVerifier mev)
 111         throws IOException
 112     {
 113         if (je == null)
 114             return;
 115 
 116         if (debug != null) {
 117             debug.println("beginEntry "+je.getName());
 118         }
 119 
 120         String name = je.getName();
 121 
 122         /*
 123          * Assumptions:
 124          * 1. The manifest should be the first entry in the META-INF directory.
 125          * 2. The .SF/.DSA/.EC files follow the manifest, before any normal entries
 126          * 3. Any of the following will throw a SecurityException:
 127          *    a. digest mismatch between a manifest section and
 128          *       the SF section.
 129          *    b. digest mismatch between the actual jar entry and the manifest
 130          */
 131 
 132         if (parsingMeta) {
 133             String uname = name.toUpperCase(Locale.ENGLISH);
 134             if ((uname.startsWith("META-INF/") ||
 135                  uname.startsWith("/META-INF/"))) {
 136 
 137                 if (je.isDirectory()) {
 138                     mev.setEntry(null, je);
 139                     return;
 140                 }
 141 
 142                 if (SignatureFileVerifier.isBlockOrSF(uname)) {
 143                     /* We parse only DSA, RSA or EC PKCS7 blocks. */
 144                     parsingBlockOrSF = true;
 145                     baos.reset();
 146                     mev.setEntry(null, je);
 147                 }
 148                 return;
 149             }
 150         }
 151 
 152         if (parsingMeta) {
 153             doneWithMeta();
 154         }
 155 
 156         if (je.isDirectory()) {
 157             mev.setEntry(null, je);
 158             return;
 159         }
 160 
 161         // be liberal in what you accept. If the name starts with ./, remove
 162         // it as we internally canonicalize it with out the ./.
 163         if (name.startsWith("./"))
 164             name = name.substring(2);
 165 
 166         // be liberal in what you accept. If the name starts with /, remove
 167         // it as we internally canonicalize it with out the /.
 168         if (name.startsWith("/"))
 169             name = name.substring(1);
 170 
 171         // only set the jev object for entries that have a signature
 172         if (sigFileSigners.get(name) != null) {
 173             mev.setEntry(name, je);
 174             return;
 175         }
 176 
 177         // don't compute the digest for this entry
 178         mev.setEntry(null, je);
 179 
 180         return;
 181     }
 182 
 183     /**
 184      * update a single byte.
 185      */
 186 
 187     public void update(int b, ManifestEntryVerifier mev)
 188         throws IOException
 189     {
 190         if (b != -1) {
 191             if (parsingBlockOrSF) {
 192                 baos.write(b);
 193             } else {
 194                 mev.update((byte)b);
 195             }
 196         } else {
 197             processEntry(mev);
 198         }
 199     }
 200 
 201     /**
 202      * update an array of bytes.
 203      */
 204 
 205     public void update(int n, byte[] b, int off, int len,
 206                        ManifestEntryVerifier mev)
 207         throws IOException
 208     {
 209         if (n != -1) {
 210             if (parsingBlockOrSF) {
 211                 baos.write(b, off, n);
 212             } else {
 213                 mev.update(b, off, n);
 214             }
 215         } else {
 216             processEntry(mev);
 217         }
 218     }
 219 
 220     /**
 221      * called when we reach the end of entry in one of the read() methods.
 222      */
 223     private void processEntry(ManifestEntryVerifier mev)
 224         throws IOException
 225     {
 226         if (!parsingBlockOrSF) {
 227             JarEntry je = mev.getEntry();
 228             if ((je != null) && (je.signers == null)) {
 229                 je.signers = mev.verify(verifiedSigners, sigFileSigners);
 230                 je.certs = mapSignersToCertArray(je.signers);
 231             }
 232         } else {
 233 
 234             try {
 235                 parsingBlockOrSF = false;
 236 
 237                 if (debug != null) {
 238                     debug.println("processEntry: processing block");
 239                 }
 240 
 241                 String uname = mev.getEntry().getName()
 242                                              .toUpperCase(Locale.ENGLISH);
 243 
 244                 if (uname.endsWith(".SF")) {
 245                     String key = uname.substring(0, uname.length()-3);
 246                     byte bytes[] = baos.toByteArray();
 247                     // add to sigFileData in case future blocks need it
 248                     sigFileData.put(key, bytes);
 249                     // check pending blocks, we can now process
 250                     // anyone waiting for this .SF file
 251                     Iterator<SignatureFileVerifier> it = pendingBlocks.iterator();
 252                     while (it.hasNext()) {
 253                         SignatureFileVerifier sfv = it.next();
 254                         if (sfv.needSignatureFile(key)) {
 255                             if (debug != null) {
 256                                 debug.println(
 257                                  "processEntry: processing pending block");
 258                             }
 259 
 260                             sfv.setSignatureFile(bytes);
 261                             sfv.process(sigFileSigners, manifestDigests);
 262                         }
 263                     }
 264                     return;
 265                 }
 266 
 267                 // now we are parsing a signature block file
 268 
 269                 String key = uname.substring(0, uname.lastIndexOf("."));
 270 
 271                 if (signerCache == null)
 272                     signerCache = new ArrayList<>();
 273 
 274                 if (manDig == null) {
 275                     synchronized(manifestRawBytes) {
 276                         if (manDig == null) {
 277                             manDig = new ManifestDigester(manifestRawBytes);
 278                             manifestRawBytes = null;
 279                         }
 280                     }
 281                 }
 282 
 283                 SignatureFileVerifier sfv =
 284                   new SignatureFileVerifier(signerCache,
 285                                             manDig, uname, baos.toByteArray());
 286 
 287                 if (sfv.needSignatureFileBytes()) {
 288                     // see if we have already parsed an external .SF file
 289                     byte[] bytes = sigFileData.get(key);
 290 
 291                     if (bytes == null) {
 292                         // put this block on queue for later processing
 293                         // since we don't have the .SF bytes yet
 294                         // (uname, block);
 295                         if (debug != null) {
 296                             debug.println("adding pending block");
 297                         }
 298                         pendingBlocks.add(sfv);
 299                         return;
 300                     } else {
 301                         sfv.setSignatureFile(bytes);
 302                     }
 303                 }
 304                 sfv.process(sigFileSigners, manifestDigests);
 305 
 306             } catch (IOException ioe) {
 307                 // e.g. sun.security.pkcs.ParsingException
 308                 if (debug != null) debug.println("processEntry caught: "+ioe);
 309                 // ignore and treat as unsigned
 310             } catch (SignatureException se) {
 311                 if (debug != null) debug.println("processEntry caught: "+se);
 312                 // ignore and treat as unsigned
 313             } catch (NoSuchAlgorithmException nsae) {
 314                 if (debug != null) debug.println("processEntry caught: "+nsae);
 315                 // ignore and treat as unsigned
 316             } catch (CertificateException ce) {
 317                 if (debug != null) debug.println("processEntry caught: "+ce);
 318                 // ignore and treat as unsigned
 319             }
 320         }
 321     }
 322 
 323     /**
 324      * Return an array of java.security.cert.Certificate objects for
 325      * the given file in the jar.
 326      * @deprecated
 327      */
 328     public java.security.cert.Certificate[] getCerts(String name)
 329     {
 330         return mapSignersToCertArray(getCodeSigners(name));
 331     }
 332 
 333     public java.security.cert.Certificate[] getCerts(JarFile jar, JarEntry entry)
 334     {
 335         return mapSignersToCertArray(getCodeSigners(jar, entry));
 336     }
 337 
 338     /**
 339      * return an array of CodeSigner objects for
 340      * the given file in the jar. this array is not cloned.
 341      *
 342      */
 343     public CodeSigner[] getCodeSigners(String name)
 344     {
 345         return verifiedSigners.get(name);
 346     }
 347 
 348     public CodeSigner[] getCodeSigners(JarFile jar, JarEntry entry)
 349     {
 350         String name = entry.getName();
 351         if (eagerValidation && sigFileSigners.get(name) != null) {
 352             /*
 353              * Force a read of the entry data to generate the
 354              * verification hash.
 355              */
 356             try {
 357                 InputStream s = jar.getInputStream(entry);
 358                 byte[] buffer = new byte[1024];
 359                 int n = buffer.length;
 360                 while (n != -1) {
 361                     n = s.read(buffer, 0, buffer.length);
 362                 }
 363                 s.close();
 364             } catch (IOException e) {
 365             }
 366         }
 367         return getCodeSigners(name);
 368     }
 369 
 370     /*
 371      * Convert an array of signers into an array of concatenated certificate
 372      * arrays.
 373      */
 374     private static java.security.cert.Certificate[] mapSignersToCertArray(
 375         CodeSigner[] signers) {
 376 
 377         if (signers != null) {
 378             ArrayList<java.security.cert.Certificate> certChains = new ArrayList<>();
 379             for (int i = 0; i < signers.length; i++) {
 380                 certChains.addAll(
 381                     signers[i].getSignerCertPath().getCertificates());
 382             }
 383 
 384             // Convert into a Certificate[]
 385             return certChains.toArray(
 386                     new java.security.cert.Certificate[certChains.size()]);
 387         }
 388         return null;
 389     }
 390 
 391     /**
 392      * returns true if there no files to verify.
 393      * should only be called after all the META-INF entries
 394      * have been processed.
 395      */
 396     boolean nothingToVerify()
 397     {
 398         return (anyToVerify == false);
 399     }
 400 
 401     /**
 402      * called to let us know we have processed all the
 403      * META-INF entries, and if we re-read one of them, don't
 404      * re-process it. Also gets rid of any data structures
 405      * we needed when parsing META-INF entries.
 406      */
 407     void doneWithMeta()
 408     {
 409         parsingMeta = false;
 410         anyToVerify = !sigFileSigners.isEmpty();
 411         baos = null;
 412         sigFileData = null;
 413         pendingBlocks = null;
 414         signerCache = null;
 415         manDig = null;
 416         // MANIFEST.MF is always treated as signed and verified,
 417         // move its signers from sigFileSigners to verifiedSigners.
 418         if (sigFileSigners.containsKey(JarFile.MANIFEST_NAME)) {
 419             CodeSigner[] codeSigners = sigFileSigners.remove(JarFile.MANIFEST_NAME);
 420             verifiedSigners.put(JarFile.MANIFEST_NAME, codeSigners);
 421         }
 422     }
 423 
 424     static class VerifierStream extends java.io.InputStream {
 425 
 426         private InputStream is;
 427         private JarVerifier jv;
 428         private ManifestEntryVerifier mev;
 429         private long numLeft;
 430 
 431         VerifierStream(Manifest man,
 432                        JarEntry je,
 433                        InputStream is,
 434                        JarVerifier jv) throws IOException
 435         {
 436             this.is = is;
 437             this.jv = jv;
 438             this.mev = new ManifestEntryVerifier(man);
 439             this.jv.beginEntry(je, mev);
 440             this.numLeft = je.getSize();
 441             if (this.numLeft == 0)
 442                 this.jv.update(-1, this.mev);
 443         }
 444 
 445         public int read() throws IOException
 446         {
 447             if (numLeft > 0) {
 448                 int b = is.read();
 449                 jv.update(b, mev);
 450                 numLeft--;
 451                 if (numLeft == 0)
 452                     jv.update(-1, mev);
 453                 return b;
 454             } else {
 455                 return -1;
 456             }
 457         }
 458 
 459         public int read(byte b[], int off, int len) throws IOException {
 460             if ((numLeft > 0) && (numLeft < len)) {
 461                 len = (int)numLeft;
 462             }
 463 
 464             if (numLeft > 0) {
 465                 int n = is.read(b, off, len);
 466                 jv.update(n, b, off, len, mev);
 467                 numLeft -= n;
 468                 if (numLeft == 0)
 469                     jv.update(-1, b, off, len, mev);
 470                 return n;
 471             } else {
 472                 return -1;
 473             }
 474         }
 475 
 476         public void close()
 477             throws IOException
 478         {
 479             if (is != null)
 480                 is.close();
 481             is = null;
 482             mev = null;
 483             jv = null;
 484         }
 485 
 486         public int available() throws IOException {
 487             return is.available();
 488         }
 489 
 490     }
 491 
 492     // Extended JavaUtilJarAccess CodeSource API Support
 493 
 494     private Map<URL, Map<CodeSigner[], CodeSource>> urlToCodeSourceMap = new HashMap<>();
 495     private Map<CodeSigner[], CodeSource> signerToCodeSource = new HashMap<>();
 496     private URL lastURL;
 497     private Map<CodeSigner[], CodeSource> lastURLMap;
 498 
 499     /*
 500      * Create a unique mapping from codeSigner cache entries to CodeSource.
 501      * In theory, multiple URLs origins could map to a single locally cached
 502      * and shared JAR file although in practice there will be a single URL in use.
 503      */
 504     private synchronized CodeSource mapSignersToCodeSource(URL url, CodeSigner[] signers) {
 505         Map<CodeSigner[], CodeSource> map;
 506         if (url == lastURL) {
 507             map = lastURLMap;
 508         } else {
 509             map = urlToCodeSourceMap.get(url);
 510             if (map == null) {
 511                 map = new HashMap<>();
 512                 urlToCodeSourceMap.put(url, map);
 513             }
 514             lastURLMap = map;
 515             lastURL = url;
 516         }
 517         CodeSource cs = map.get(signers);
 518         if (cs == null) {
 519             cs = new VerifierCodeSource(csdomain, url, signers);
 520             signerToCodeSource.put(signers, cs);
 521         }
 522         return cs;
 523     }
 524 
 525     private CodeSource[] mapSignersToCodeSources(URL url, List<CodeSigner[]> signers, boolean unsigned) {
 526         List<CodeSource> sources = new ArrayList<>();
 527 
 528         for (int i = 0; i < signers.size(); i++) {
 529             sources.add(mapSignersToCodeSource(url, signers.get(i)));
 530         }
 531         if (unsigned) {
 532             sources.add(mapSignersToCodeSource(url, null));
 533         }
 534         return sources.toArray(new CodeSource[sources.size()]);
 535     }
 536     private CodeSigner[] emptySigner = new CodeSigner[0];
 537 
 538     /*
 539      * Match CodeSource to a CodeSigner[] in the signer cache.
 540      */
 541     private CodeSigner[] findMatchingSigners(CodeSource cs) {
 542         if (cs instanceof VerifierCodeSource) {
 543             VerifierCodeSource vcs = (VerifierCodeSource) cs;
 544             if (vcs.isSameDomain(csdomain)) {
 545                 return ((VerifierCodeSource) cs).getPrivateSigners();
 546             }
 547         }
 548 
 549         /*
 550          * In practice signers should always be optimized above
 551          * but this handles a CodeSource of any type, just in case.
 552          */
 553         CodeSource[] sources = mapSignersToCodeSources(cs.getLocation(), getJarCodeSigners(), true);
 554         List<CodeSource> sourceList = new ArrayList<>();
 555         for (int i = 0; i < sources.length; i++) {
 556             sourceList.add(sources[i]);
 557         }
 558         int j = sourceList.indexOf(cs);
 559         if (j != -1) {
 560             CodeSigner[] match;
 561             match = ((VerifierCodeSource) sourceList.get(j)).getPrivateSigners();
 562             if (match == null) {
 563                 match = emptySigner;
 564             }
 565             return match;
 566         }
 567         return null;
 568     }
 569 
 570     /*
 571      * Instances of this class hold uncopied references to internal
 572      * signing data that can be compared by object reference identity.
 573      */
 574     private static class VerifierCodeSource extends CodeSource {
 575         private static final long serialVersionUID = -9047366145967768825L;
 576 
 577         URL vlocation;
 578         CodeSigner[] vsigners;
 579         java.security.cert.Certificate[] vcerts;
 580         Object csdomain;
 581 
 582         VerifierCodeSource(Object csdomain, URL location, CodeSigner[] signers) {
 583             super(location, signers);
 584             this.csdomain = csdomain;
 585             vlocation = location;
 586             vsigners = signers; // from signerCache
 587         }
 588 
 589         VerifierCodeSource(Object csdomain, URL location, java.security.cert.Certificate[] certs) {
 590             super(location, certs);
 591             this.csdomain = csdomain;
 592             vlocation = location;
 593             vcerts = certs; // from signerCache
 594         }
 595 
 596         /*
 597          * All VerifierCodeSource instances are constructed based on
 598          * singleton signerCache or signerCacheCert entries for each unique signer.
 599          * No CodeSigner<->Certificate[] conversion is required.
 600          * We use these assumptions to optimize equality comparisons.
 601          */
 602         public boolean equals(Object obj) {
 603             if (obj == this) {
 604                 return true;
 605             }
 606             if (obj instanceof VerifierCodeSource) {
 607                 VerifierCodeSource that = (VerifierCodeSource) obj;
 608 
 609                 /*
 610                  * Only compare against other per-signer singletons constructed
 611                  * on behalf of the same JarFile instance. Otherwise, compare
 612                  * things the slower way.
 613                  */
 614                 if (isSameDomain(that.csdomain)) {
 615                     if (that.vsigners != this.vsigners
 616                             || that.vcerts != this.vcerts) {
 617                         return false;
 618                     }
 619                     if (that.vlocation != null) {
 620                         return that.vlocation.equals(this.vlocation);
 621                     } else if (this.vlocation != null) {
 622                         return this.vlocation.equals(that.vlocation);
 623                     } else { // both null
 624                         return true;
 625                     }
 626                 }
 627             }
 628             return super.equals(obj);
 629         }
 630 
 631         boolean isSameDomain(Object csdomain) {
 632             return this.csdomain == csdomain;
 633         }
 634 
 635         private CodeSigner[] getPrivateSigners() {
 636             return vsigners;
 637         }
 638 
 639         private java.security.cert.Certificate[] getPrivateCertificates() {
 640             return vcerts;
 641         }
 642     }
 643     private Map<String, CodeSigner[]> signerMap;
 644 
 645     private synchronized Map<String, CodeSigner[]> signerMap() {
 646         if (signerMap == null) {
 647             /*
 648              * Snapshot signer state so it doesn't change on us. We care
 649              * only about the asserted signatures. Verification of
 650              * signature validity happens via the JarEntry apis.
 651              */
 652             signerMap = new HashMap<>(verifiedSigners.size() + sigFileSigners.size());
 653             signerMap.putAll(verifiedSigners);
 654             signerMap.putAll(sigFileSigners);
 655         }
 656         return signerMap;
 657     }
 658 
 659     public synchronized Enumeration<String> entryNames(JarFile jar, final CodeSource[] cs) {
 660         final Map<String, CodeSigner[]> map = signerMap();
 661         final Iterator<Map.Entry<String, CodeSigner[]>> itor = map.entrySet().iterator();
 662         boolean matchUnsigned = false;
 663 
 664         /*
 665          * Grab a single copy of the CodeSigner arrays. Check
 666          * to see if we can optimize CodeSigner equality test.
 667          */
 668         List<CodeSigner[]> req = new ArrayList<>(cs.length);
 669         for (int i = 0; i < cs.length; i++) {
 670             CodeSigner[] match = findMatchingSigners(cs[i]);
 671             if (match != null) {
 672                 if (match.length > 0) {
 673                     req.add(match);
 674                 } else {
 675                     matchUnsigned = true;
 676                 }
 677             }
 678         }
 679 
 680         final List<CodeSigner[]> signersReq = req;
 681         final Enumeration<String> enum2 = (matchUnsigned) ? unsignedEntryNames(jar) : emptyEnumeration;
 682 
 683         return new Enumeration<String>() {
 684 
 685             String name;
 686 
 687             public boolean hasMoreElements() {
 688                 if (name != null) {
 689                     return true;
 690                 }
 691 
 692                 while (itor.hasNext()) {
 693                     Map.Entry<String, CodeSigner[]> e = itor.next();
 694                     if (signersReq.contains(e.getValue())) {
 695                         name = e.getKey();
 696                         return true;
 697                     }
 698                 }
 699                 while (enum2.hasMoreElements()) {
 700                     name = enum2.nextElement();
 701                     return true;
 702                 }
 703                 return false;
 704             }
 705 
 706             public String nextElement() {
 707                 if (hasMoreElements()) {
 708                     String value = name;
 709                     name = null;
 710                     return value;
 711                 }
 712                 throw new NoSuchElementException();
 713             }
 714         };
 715     }
 716 
 717     /*
 718      * Like entries() but screens out internal JAR mechanism entries
 719      * and includes signed entries with no ZIP data.
 720      */
 721     public Enumeration<JarEntry> entries2(final JarFile jar, Enumeration<? extends ZipEntry> e) {
 722         final Map<String, CodeSigner[]> map = new HashMap<>();
 723         map.putAll(signerMap());
 724         final Enumeration<? extends ZipEntry> enum_ = e;
 725         return new Enumeration<JarEntry>() {
 726 
 727             Enumeration<String> signers = null;
 728             JarEntry entry;
 729 
 730             public boolean hasMoreElements() {
 731                 if (entry != null) {
 732                     return true;
 733                 }
 734                 while (enum_.hasMoreElements()) {
 735                     ZipEntry ze = enum_.nextElement();
 736                     if (JarVerifier.isSigningRelated(ze.getName())) {
 737                         continue;
 738                     }
 739                     entry = jar.newEntry(ze);
 740                     return true;
 741                 }
 742                 if (signers == null) {
 743                     signers = Collections.enumeration(map.keySet());
 744                 }
 745                 while (signers.hasMoreElements()) {
 746                     String name = signers.nextElement();
 747                     entry = jar.newEntry(new ZipEntry(name));
 748                     return true;
 749                 }
 750 
 751                 // Any map entries left?
 752                 return false;
 753             }
 754 
 755             public JarEntry nextElement() {
 756                 if (hasMoreElements()) {
 757                     JarEntry je = entry;
 758                     map.remove(je.getName());
 759                     entry = null;
 760                     return je;
 761                 }
 762                 throw new NoSuchElementException();
 763             }
 764         };
 765     }
 766     private Enumeration<String> emptyEnumeration = new Enumeration<String>() {
 767 
 768         public boolean hasMoreElements() {
 769             return false;
 770         }
 771 
 772         public String nextElement() {
 773             throw new NoSuchElementException();
 774         }
 775     };
 776 
 777     // true if file is part of the signature mechanism itself
 778     static boolean isSigningRelated(String name) {
 779         name = name.toUpperCase(Locale.ENGLISH);
 780         if (!name.startsWith("META-INF/")) {
 781             return false;
 782         }
 783         name = name.substring(9);
 784         if (name.indexOf('/') != -1) {
 785             return false;
 786         }
 787         if (name.endsWith(".DSA")
 788                 || name.endsWith(".RSA")
 789                 || name.endsWith(".SF")
 790                 || name.endsWith(".EC")
 791                 || name.startsWith("SIG-")
 792                 || name.equals("MANIFEST.MF")) {
 793             return true;
 794         }
 795         return false;
 796     }
 797 
 798     private Enumeration<String> unsignedEntryNames(JarFile jar) {
 799         final Map<String, CodeSigner[]> map = signerMap();
 800         final Enumeration<JarEntry> entries = jar.entries();
 801         return new Enumeration<String>() {
 802 
 803             String name;
 804 
 805             /*
 806              * Grab entries from ZIP directory but screen out
 807              * metadata.
 808              */
 809             public boolean hasMoreElements() {
 810                 if (name != null) {
 811                     return true;
 812                 }
 813                 while (entries.hasMoreElements()) {
 814                     String value;
 815                     ZipEntry e = entries.nextElement();
 816                     value = e.getName();
 817                     if (e.isDirectory() || isSigningRelated(value)) {
 818                         continue;
 819                     }
 820                     if (map.get(value) == null) {
 821                         name = value;
 822                         return true;
 823                     }
 824                 }
 825                 return false;
 826             }
 827 
 828             public String nextElement() {
 829                 if (hasMoreElements()) {
 830                     String value = name;
 831                     name = null;
 832                     return value;
 833                 }
 834                 throw new NoSuchElementException();
 835             }
 836         };
 837     }
 838     private List<CodeSigner[]> jarCodeSigners;
 839 
 840     private synchronized List<CodeSigner[]> getJarCodeSigners() {
 841         CodeSigner[] signers;
 842         if (jarCodeSigners == null) {
 843             HashSet<CodeSigner[]> set = new HashSet<>();
 844             set.addAll(signerMap().values());
 845             jarCodeSigners = new ArrayList<>();
 846             jarCodeSigners.addAll(set);
 847         }
 848         return jarCodeSigners;
 849     }
 850 
 851     public synchronized CodeSource[] getCodeSources(JarFile jar, URL url) {
 852         boolean hasUnsigned = unsignedEntryNames(jar).hasMoreElements();
 853 
 854         return mapSignersToCodeSources(url, getJarCodeSigners(), hasUnsigned);
 855     }
 856 
 857     public CodeSource getCodeSource(URL url, String name) {
 858         CodeSigner[] signers;
 859 
 860         signers = signerMap().get(name);
 861         return mapSignersToCodeSource(url, signers);
 862     }
 863 
 864     public CodeSource getCodeSource(URL url, JarFile jar, JarEntry je) {
 865         CodeSigner[] signers;
 866 
 867         return mapSignersToCodeSource(url, getCodeSigners(jar, je));
 868     }
 869 
 870     public void setEagerValidation(boolean eager) {
 871         eagerValidation = eager;
 872     }
 873 
 874     public synchronized List<Object> getManifestDigests() {
 875         return Collections.unmodifiableList(manifestDigests);
 876     }
 877 
 878     static CodeSource getUnsignedCS(URL url) {
 879         return new VerifierCodeSource(null, url, (java.security.cert.Certificate[]) null);
 880     }
 881 }