JarVerifier.java 29.9 KB
Newer Older
D
duke 已提交
1
/*
I
igerasim 已提交
2
 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28
 */

package java.util.jar;

import java.io.*;
29
import java.net.URL;
D
duke 已提交
30 31 32
import java.util.*;
import java.security.*;
import java.security.cert.CertificateException;
33
import java.util.zip.ZipEntry;
D
duke 已提交
34

35
import sun.misc.JarIndex;
D
duke 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
import sun.security.util.ManifestDigester;
import sun.security.util.ManifestEntryVerifier;
import sun.security.util.SignatureFileVerifier;
import sun.security.util.Debug;

/**
 *
 * @author      Roland Schemers
 */
class JarVerifier {

    /* Are we debugging ? */
    static final Debug debug = Debug.getInstance("jar");

    /* a table mapping names to code signers, for jar entries that have
       had their actual hashes verified */
52
    private Hashtable<String, CodeSigner[]> verifiedSigners;
D
duke 已提交
53 54

    /* a table mapping names to code signers, for jar entries that have
55
       passed the .SF/.DSA/.EC -> MANIFEST check */
56
    private Hashtable<String, CodeSigner[]> sigFileSigners;
57 58

    /* a hash table to hold .SF bytes */
59
    private Hashtable<String, byte[]> sigFileData;
60 61 62

    /** "queue" of pending PKCS7 blocks that we couldn't parse
     *  until we parsed the .SF file */
63
    private ArrayList<SignatureFileVerifier> pendingBlocks;
D
duke 已提交
64 65

    /* cache of CodeSigner objects */
66
    private ArrayList<CodeSigner[]> signerCache;
D
duke 已提交
67

68 69 70 71 72 73
    /* Are we parsing a block? */
    private boolean parsingBlockOrSF = false;

    /* Are we done parsing META-INF entries? */
    private boolean parsingMeta = true;

D
duke 已提交
74 75 76
    /* Are there are files to verify? */
    private boolean anyToVerify = true;

77 78 79 80
    /* The output stream to use when keeping track of files we are interested
       in */
    private ByteArrayOutputStream baos;

D
duke 已提交
81
    /** The ManifestDigester object */
82
    private volatile ManifestDigester manDig;
D
duke 已提交
83 84 85 86

    /** the bytes for the manDig object */
    byte manifestRawBytes[] = null;

87 88 89 90 91 92 93
    /** controls eager signature validation */
    boolean eagerValidation;

    /** makes code source singleton instances unique to us */
    private Object csdomain = new Object();

    /** collect -DIGEST-MANIFEST values for blacklist */
94
    private List<Object> manifestDigests;
95

96
    public JarVerifier(byte rawBytes[]) {
D
duke 已提交
97
        manifestRawBytes = rawBytes;
98 99 100 101
        sigFileSigners = new Hashtable<>();
        verifiedSigners = new Hashtable<>();
        sigFileData = new Hashtable<>(11);
        pendingBlocks = new ArrayList<>();
102
        baos = new ByteArrayOutputStream();
103
        manifestDigests = new ArrayList<>();
D
duke 已提交
104 105 106
    }

    /**
107 108 109
     * This method scans to see which entry we're parsing and
     * keeps various state information depending on what type of
     * file is being parsed.
D
duke 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
     */
    public void beginEntry(JarEntry je, ManifestEntryVerifier mev)
        throws IOException
    {
        if (je == null)
            return;

        if (debug != null) {
            debug.println("beginEntry "+je.getName());
        }

        String name = je.getName();

        /*
         * Assumptions:
         * 1. The manifest should be the first entry in the META-INF directory.
126
         * 2. The .SF/.DSA/.EC files follow the manifest, before any normal entries
D
duke 已提交
127 128 129 130 131 132
         * 3. Any of the following will throw a SecurityException:
         *    a. digest mismatch between a manifest section and
         *       the SF section.
         *    b. digest mismatch between the actual jar entry and the manifest
         */

133 134 135 136 137 138 139 140 141 142
        if (parsingMeta) {
            String uname = name.toUpperCase(Locale.ENGLISH);
            if ((uname.startsWith("META-INF/") ||
                 uname.startsWith("/META-INF/"))) {

                if (je.isDirectory()) {
                    mev.setEntry(null, je);
                    return;
                }

143 144
                if (uname.equals(JarFile.MANIFEST_NAME) ||
                        uname.equals(JarIndex.INDEX_NAME)) {
145 146 147
                    return;
                }

148 149 150 151 152
                if (SignatureFileVerifier.isBlockOrSF(uname)) {
                    /* We parse only DSA, RSA or EC PKCS7 blocks. */
                    parsingBlockOrSF = true;
                    baos.reset();
                    mev.setEntry(null, je);
153
                    return;
154
                }
155 156 157 158

                // If a META-INF entry is not MF or block or SF, they should
                // be normal entries. According to 2 above, no more block or
                // SF will appear. Let's doneWithMeta.
159 160 161 162 163 164 165
            }
        }

        if (parsingMeta) {
            doneWithMeta();
        }

D
duke 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        if (je.isDirectory()) {
            mev.setEntry(null, je);
            return;
        }

        // be liberal in what you accept. If the name starts with ./, remove
        // it as we internally canonicalize it with out the ./.
        if (name.startsWith("./"))
            name = name.substring(2);

        // be liberal in what you accept. If the name starts with /, remove
        // it as we internally canonicalize it with out the /.
        if (name.startsWith("/"))
            name = name.substring(1);

        // only set the jev object for entries that have a signature
W
weijun 已提交
182
        // (either verified or not)
183 184 185 186 187 188
        if (!name.equals(JarFile.MANIFEST_NAME)) {
            if (sigFileSigners.get(name) != null ||
                    verifiedSigners.get(name) != null) {
                mev.setEntry(name, je);
                return;
            }
D
duke 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        }

        // don't compute the digest for this entry
        mev.setEntry(null, je);

        return;
    }

    /**
     * update a single byte.
     */

    public void update(int b, ManifestEntryVerifier mev)
        throws IOException
    {
        if (b != -1) {
205 206 207 208 209
            if (parsingBlockOrSF) {
                baos.write(b);
            } else {
                mev.update((byte)b);
            }
D
duke 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223
        } else {
            processEntry(mev);
        }
    }

    /**
     * update an array of bytes.
     */

    public void update(int n, byte[] b, int off, int len,
                       ManifestEntryVerifier mev)
        throws IOException
    {
        if (n != -1) {
224 225 226 227 228
            if (parsingBlockOrSF) {
                baos.write(b, off, n);
            } else {
                mev.update(b, off, n);
            }
D
duke 已提交
229 230 231 232 233 234 235 236 237 238 239
        } else {
            processEntry(mev);
        }
    }

    /**
     * called when we reach the end of entry in one of the read() methods.
     */
    private void processEntry(ManifestEntryVerifier mev)
        throws IOException
    {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        if (!parsingBlockOrSF) {
            JarEntry je = mev.getEntry();
            if ((je != null) && (je.signers == null)) {
                je.signers = mev.verify(verifiedSigners, sigFileSigners);
                je.certs = mapSignersToCertArray(je.signers);
            }
        } else {

            try {
                parsingBlockOrSF = false;

                if (debug != null) {
                    debug.println("processEntry: processing block");
                }

                String uname = mev.getEntry().getName()
                                             .toUpperCase(Locale.ENGLISH);

                if (uname.endsWith(".SF")) {
                    String key = uname.substring(0, uname.length()-3);
                    byte bytes[] = baos.toByteArray();
                    // add to sigFileData in case future blocks need it
                    sigFileData.put(key, bytes);
                    // check pending blocks, we can now process
                    // anyone waiting for this .SF file
265
                    Iterator<SignatureFileVerifier> it = pendingBlocks.iterator();
266
                    while (it.hasNext()) {
267
                        SignatureFileVerifier sfv = it.next();
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
                        if (sfv.needSignatureFile(key)) {
                            if (debug != null) {
                                debug.println(
                                 "processEntry: processing pending block");
                            }

                            sfv.setSignatureFile(bytes);
                            sfv.process(sigFileSigners, manifestDigests);
                        }
                    }
                    return;
                }

                // now we are parsing a signature block file

                String key = uname.substring(0, uname.lastIndexOf("."));

                if (signerCache == null)
286
                    signerCache = new ArrayList<>();
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

                if (manDig == null) {
                    synchronized(manifestRawBytes) {
                        if (manDig == null) {
                            manDig = new ManifestDigester(manifestRawBytes);
                            manifestRawBytes = null;
                        }
                    }
                }

                SignatureFileVerifier sfv =
                  new SignatureFileVerifier(signerCache,
                                            manDig, uname, baos.toByteArray());

                if (sfv.needSignatureFileBytes()) {
                    // see if we have already parsed an external .SF file
303
                    byte[] bytes = sigFileData.get(key);
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

                    if (bytes == null) {
                        // put this block on queue for later processing
                        // since we don't have the .SF bytes yet
                        // (uname, block);
                        if (debug != null) {
                            debug.println("adding pending block");
                        }
                        pendingBlocks.add(sfv);
                        return;
                    } else {
                        sfv.setSignatureFile(bytes);
                    }
                }
                sfv.process(sigFileSigners, manifestDigests);

            } catch (IOException ioe) {
                // e.g. sun.security.pkcs.ParsingException
                if (debug != null) debug.println("processEntry caught: "+ioe);
                // ignore and treat as unsigned
            } catch (SignatureException se) {
                if (debug != null) debug.println("processEntry caught: "+se);
                // ignore and treat as unsigned
            } catch (NoSuchAlgorithmException nsae) {
                if (debug != null) debug.println("processEntry caught: "+nsae);
                // ignore and treat as unsigned
            } catch (CertificateException ce) {
                if (debug != null) debug.println("processEntry caught: "+ce);
                // ignore and treat as unsigned
            }
D
duke 已提交
334 335 336 337 338 339
        }
    }

    /**
     * Return an array of java.security.cert.Certificate objects for
     * the given file in the jar.
340
     * @deprecated
D
duke 已提交
341
     */
342
    @Deprecated
D
duke 已提交
343 344 345 346 347
    public java.security.cert.Certificate[] getCerts(String name)
    {
        return mapSignersToCertArray(getCodeSigners(name));
    }

348 349 350 351 352
    public java.security.cert.Certificate[] getCerts(JarFile jar, JarEntry entry)
    {
        return mapSignersToCertArray(getCodeSigners(jar, entry));
    }

D
duke 已提交
353 354 355 356 357 358 359
    /**
     * return an array of CodeSigner objects for
     * the given file in the jar. this array is not cloned.
     *
     */
    public CodeSigner[] getCodeSigners(String name)
    {
360
        return verifiedSigners.get(name);
D
duke 已提交
361 362
    }

363 364 365 366 367 368 369 370
    public CodeSigner[] getCodeSigners(JarFile jar, JarEntry entry)
    {
        String name = entry.getName();
        if (eagerValidation && sigFileSigners.get(name) != null) {
            /*
             * Force a read of the entry data to generate the
             * verification hash.
             */
371 372
            try {
                InputStream s = jar.getInputStream(entry);
373 374 375 376 377
                byte[] buffer = new byte[1024];
                int n = buffer.length;
                while (n != -1) {
                    n = s.read(buffer, 0, buffer.length);
                }
378
                s.close();
379 380 381 382 383 384
            } catch (IOException e) {
            }
        }
        return getCodeSigners(name);
    }

D
duke 已提交
385 386 387 388 389 390 391 392
    /*
     * Convert an array of signers into an array of concatenated certificate
     * arrays.
     */
    private static java.security.cert.Certificate[] mapSignersToCertArray(
        CodeSigner[] signers) {

        if (signers != null) {
393
            ArrayList<java.security.cert.Certificate> certChains = new ArrayList<>();
D
duke 已提交
394 395 396 397 398 399
            for (int i = 0; i < signers.length; i++) {
                certChains.addAll(
                    signers[i].getSignerCertPath().getCertificates());
            }

            // Convert into a Certificate[]
400
            return certChains.toArray(
D
duke 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
                    new java.security.cert.Certificate[certChains.size()]);
        }
        return null;
    }

    /**
     * returns true if there no files to verify.
     * should only be called after all the META-INF entries
     * have been processed.
     */
    boolean nothingToVerify()
    {
        return (anyToVerify == false);
    }

    /**
     * called to let us know we have processed all the
     * META-INF entries, and if we re-read one of them, don't
     * re-process it. Also gets rid of any data structures
     * we needed when parsing META-INF entries.
     */
    void doneWithMeta()
    {
424
        parsingMeta = false;
D
duke 已提交
425
        anyToVerify = !sigFileSigners.isEmpty();
426 427 428
        baos = null;
        sigFileData = null;
        pendingBlocks = null;
D
duke 已提交
429 430
        signerCache = null;
        manDig = null;
431 432 433
        // MANIFEST.MF is always treated as signed and verified,
        // move its signers from sigFileSigners to verifiedSigners.
        if (sigFileSigners.containsKey(JarFile.MANIFEST_NAME)) {
434 435
            CodeSigner[] codeSigners = sigFileSigners.remove(JarFile.MANIFEST_NAME);
            verifiedSigners.put(JarFile.MANIFEST_NAME, codeSigners);
436
        }
D
duke 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    }

    static class VerifierStream extends java.io.InputStream {

        private InputStream is;
        private JarVerifier jv;
        private ManifestEntryVerifier mev;
        private long numLeft;

        VerifierStream(Manifest man,
                       JarEntry je,
                       InputStream is,
                       JarVerifier jv) throws IOException
        {
            this.is = is;
            this.jv = jv;
            this.mev = new ManifestEntryVerifier(man);
            this.jv.beginEntry(je, mev);
            this.numLeft = je.getSize();
            if (this.numLeft == 0)
                this.jv.update(-1, this.mev);
        }

        public int read() throws IOException
        {
            if (numLeft > 0) {
                int b = is.read();
                jv.update(b, mev);
                numLeft--;
                if (numLeft == 0)
                    jv.update(-1, mev);
                return b;
            } else {
                return -1;
            }
        }

        public int read(byte b[], int off, int len) throws IOException {
            if ((numLeft > 0) && (numLeft < len)) {
                len = (int)numLeft;
            }

            if (numLeft > 0) {
                int n = is.read(b, off, len);
                jv.update(n, b, off, len, mev);
                numLeft -= n;
                if (numLeft == 0)
                    jv.update(-1, b, off, len, mev);
                return n;
            } else {
                return -1;
            }
        }

        public void close()
            throws IOException
        {
            if (is != null)
                is.close();
            is = null;
            mev = null;
            jv = null;
        }

        public int available() throws IOException {
            return is.available();
        }

    }
506 507 508

    // Extended JavaUtilJarAccess CodeSource API Support

509 510
    private Map<URL, Map<CodeSigner[], CodeSource>> urlToCodeSourceMap = new HashMap<>();
    private Map<CodeSigner[], CodeSource> signerToCodeSource = new HashMap<>();
511
    private URL lastURL;
512
    private Map<CodeSigner[], CodeSource> lastURLMap;
513 514 515 516 517 518 519

    /*
     * Create a unique mapping from codeSigner cache entries to CodeSource.
     * In theory, multiple URLs origins could map to a single locally cached
     * and shared JAR file although in practice there will be a single URL in use.
     */
    private synchronized CodeSource mapSignersToCodeSource(URL url, CodeSigner[] signers) {
520
        Map<CodeSigner[], CodeSource> map;
521 522 523
        if (url == lastURL) {
            map = lastURLMap;
        } else {
524
            map = urlToCodeSourceMap.get(url);
525
            if (map == null) {
526
                map = new HashMap<>();
527 528 529 530 531
                urlToCodeSourceMap.put(url, map);
            }
            lastURLMap = map;
            lastURL = url;
        }
532
        CodeSource cs = map.get(signers);
533 534 535 536 537 538 539
        if (cs == null) {
            cs = new VerifierCodeSource(csdomain, url, signers);
            signerToCodeSource.put(signers, cs);
        }
        return cs;
    }

540 541
    private CodeSource[] mapSignersToCodeSources(URL url, List<CodeSigner[]> signers, boolean unsigned) {
        List<CodeSource> sources = new ArrayList<>();
542 543

        for (int i = 0; i < signers.size(); i++) {
544
            sources.add(mapSignersToCodeSource(url, signers.get(i)));
545 546 547 548
        }
        if (unsigned) {
            sources.add(mapSignersToCodeSource(url, null));
        }
549
        return sources.toArray(new CodeSource[sources.size()]);
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    }
    private CodeSigner[] emptySigner = new CodeSigner[0];

    /*
     * Match CodeSource to a CodeSigner[] in the signer cache.
     */
    private CodeSigner[] findMatchingSigners(CodeSource cs) {
        if (cs instanceof VerifierCodeSource) {
            VerifierCodeSource vcs = (VerifierCodeSource) cs;
            if (vcs.isSameDomain(csdomain)) {
                return ((VerifierCodeSource) cs).getPrivateSigners();
            }
        }

        /*
         * In practice signers should always be optimized above
         * but this handles a CodeSource of any type, just in case.
         */
        CodeSource[] sources = mapSignersToCodeSources(cs.getLocation(), getJarCodeSigners(), true);
569
        List<CodeSource> sourceList = new ArrayList<>();
570 571 572
        for (int i = 0; i < sources.length; i++) {
            sourceList.add(sources[i]);
        }
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
        int j = sourceList.indexOf(cs);
        if (j != -1) {
            CodeSigner[] match;
            match = ((VerifierCodeSource) sourceList.get(j)).getPrivateSigners();
            if (match == null) {
                match = emptySigner;
            }
            return match;
        }
        return null;
    }

    /*
     * Instances of this class hold uncopied references to internal
     * signing data that can be compared by object reference identity.
     */
    private static class VerifierCodeSource extends CodeSource {
590
        private static final long serialVersionUID = -9047366145967768825L;
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

        URL vlocation;
        CodeSigner[] vsigners;
        java.security.cert.Certificate[] vcerts;
        Object csdomain;

        VerifierCodeSource(Object csdomain, URL location, CodeSigner[] signers) {
            super(location, signers);
            this.csdomain = csdomain;
            vlocation = location;
            vsigners = signers; // from signerCache
        }

        VerifierCodeSource(Object csdomain, URL location, java.security.cert.Certificate[] certs) {
            super(location, certs);
            this.csdomain = csdomain;
            vlocation = location;
            vcerts = certs; // from signerCache
        }

        /*
         * All VerifierCodeSource instances are constructed based on
         * singleton signerCache or signerCacheCert entries for each unique signer.
         * No CodeSigner<->Certificate[] conversion is required.
         * We use these assumptions to optimize equality comparisons.
         */
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj instanceof VerifierCodeSource) {
                VerifierCodeSource that = (VerifierCodeSource) obj;

                /*
                 * Only compare against other per-signer singletons constructed
                 * on behalf of the same JarFile instance. Otherwise, compare
                 * things the slower way.
                 */
                if (isSameDomain(that.csdomain)) {
                    if (that.vsigners != this.vsigners
                            || that.vcerts != this.vcerts) {
                        return false;
                    }
                    if (that.vlocation != null) {
                        return that.vlocation.equals(this.vlocation);
                    } else if (this.vlocation != null) {
                        return this.vlocation.equals(that.vlocation);
                    } else { // both null
                        return true;
                    }
                }
            }
            return super.equals(obj);
        }

        boolean isSameDomain(Object csdomain) {
            return this.csdomain == csdomain;
        }

        private CodeSigner[] getPrivateSigners() {
            return vsigners;
        }

        private java.security.cert.Certificate[] getPrivateCertificates() {
            return vcerts;
        }
    }
658
    private Map<String, CodeSigner[]> signerMap;
659

660
    private synchronized Map<String, CodeSigner[]> signerMap() {
661 662 663 664 665 666
        if (signerMap == null) {
            /*
             * Snapshot signer state so it doesn't change on us. We care
             * only about the asserted signatures. Verification of
             * signature validity happens via the JarEntry apis.
             */
667
            signerMap = new HashMap<>(verifiedSigners.size() + sigFileSigners.size());
668 669 670 671 672 673 674
            signerMap.putAll(verifiedSigners);
            signerMap.putAll(sigFileSigners);
        }
        return signerMap;
    }

    public synchronized Enumeration<String> entryNames(JarFile jar, final CodeSource[] cs) {
675 676
        final Map<String, CodeSigner[]> map = signerMap();
        final Iterator<Map.Entry<String, CodeSigner[]>> itor = map.entrySet().iterator();
677 678 679 680 681 682
        boolean matchUnsigned = false;

        /*
         * Grab a single copy of the CodeSigner arrays. Check
         * to see if we can optimize CodeSigner equality test.
         */
683
        List<CodeSigner[]> req = new ArrayList<>(cs.length);
684 685 686 687 688 689 690 691
        for (int i = 0; i < cs.length; i++) {
            CodeSigner[] match = findMatchingSigners(cs[i]);
            if (match != null) {
                if (match.length > 0) {
                    req.add(match);
                } else {
                    matchUnsigned = true;
                }
W
weijun 已提交
692 693
            } else {
                matchUnsigned = true;
694 695 696
            }
        }

697 698
        final List<CodeSigner[]> signersReq = req;
        final Enumeration<String> enum2 = (matchUnsigned) ? unsignedEntryNames(jar) : emptyEnumeration;
699 700 701 702 703 704 705 706 707 708 709

        return new Enumeration<String>() {

            String name;

            public boolean hasMoreElements() {
                if (name != null) {
                    return true;
                }

                while (itor.hasNext()) {
710 711 712
                    Map.Entry<String, CodeSigner[]> e = itor.next();
                    if (signersReq.contains(e.getValue())) {
                        name = e.getKey();
713 714 715 716
                        return true;
                    }
                }
                while (enum2.hasMoreElements()) {
717
                    name = enum2.nextElement();
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
                    return true;
                }
                return false;
            }

            public String nextElement() {
                if (hasMoreElements()) {
                    String value = name;
                    name = null;
                    return value;
                }
                throw new NoSuchElementException();
            }
        };
    }

    /*
     * Like entries() but screens out internal JAR mechanism entries
     * and includes signed entries with no ZIP data.
     */
738 739
    public Enumeration<JarEntry> entries2(final JarFile jar, Enumeration<? extends ZipEntry> e) {
        final Map<String, CodeSigner[]> map = new HashMap<>();
740
        map.putAll(signerMap());
741
        final Enumeration<? extends ZipEntry> enum_ = e;
742 743
        return new Enumeration<JarEntry>() {

744
            Enumeration<String> signers = null;
745 746 747 748 749 750 751
            JarEntry entry;

            public boolean hasMoreElements() {
                if (entry != null) {
                    return true;
                }
                while (enum_.hasMoreElements()) {
752
                    ZipEntry ze = enum_.nextElement();
753 754 755 756 757 758 759 760 761 762
                    if (JarVerifier.isSigningRelated(ze.getName())) {
                        continue;
                    }
                    entry = jar.newEntry(ze);
                    return true;
                }
                if (signers == null) {
                    signers = Collections.enumeration(map.keySet());
                }
                while (signers.hasMoreElements()) {
763
                    String name = signers.nextElement();
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
                    entry = jar.newEntry(new ZipEntry(name));
                    return true;
                }

                // Any map entries left?
                return false;
            }

            public JarEntry nextElement() {
                if (hasMoreElements()) {
                    JarEntry je = entry;
                    map.remove(je.getName());
                    entry = null;
                    return je;
                }
                throw new NoSuchElementException();
            }
        };
    }
783
    private Enumeration<String> emptyEnumeration = new Enumeration<String>() {
784 785 786 787 788 789 790 791 792 793 794 795

        public boolean hasMoreElements() {
            return false;
        }

        public String nextElement() {
            throw new NoSuchElementException();
        }
    };

    // true if file is part of the signature mechanism itself
    static boolean isSigningRelated(String name) {
W
weijun 已提交
796
        return SignatureFileVerifier.isSigningRelated(name);
797 798 799
    }

    private Enumeration<String> unsignedEntryNames(JarFile jar) {
800 801
        final Map<String, CodeSigner[]> map = signerMap();
        final Enumeration<JarEntry> entries = jar.entries();
802 803 804 805 806 807 808 809 810 811 812 813 814 815
        return new Enumeration<String>() {

            String name;

            /*
             * Grab entries from ZIP directory but screen out
             * metadata.
             */
            public boolean hasMoreElements() {
                if (name != null) {
                    return true;
                }
                while (entries.hasMoreElements()) {
                    String value;
816
                    ZipEntry e = entries.nextElement();
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
                    value = e.getName();
                    if (e.isDirectory() || isSigningRelated(value)) {
                        continue;
                    }
                    if (map.get(value) == null) {
                        name = value;
                        return true;
                    }
                }
                return false;
            }

            public String nextElement() {
                if (hasMoreElements()) {
                    String value = name;
                    name = null;
                    return value;
                }
                throw new NoSuchElementException();
            }
        };
    }
839
    private List<CodeSigner[]> jarCodeSigners;
840

841
    private synchronized List<CodeSigner[]> getJarCodeSigners() {
842 843
        CodeSigner[] signers;
        if (jarCodeSigners == null) {
844
            HashSet<CodeSigner[]> set = new HashSet<>();
845
            set.addAll(signerMap().values());
846
            jarCodeSigners = new ArrayList<>();
847 848 849 850 851 852 853 854 855 856 857 858 859 860
            jarCodeSigners.addAll(set);
        }
        return jarCodeSigners;
    }

    public synchronized CodeSource[] getCodeSources(JarFile jar, URL url) {
        boolean hasUnsigned = unsignedEntryNames(jar).hasMoreElements();

        return mapSignersToCodeSources(url, getJarCodeSigners(), hasUnsigned);
    }

    public CodeSource getCodeSource(URL url, String name) {
        CodeSigner[] signers;

861
        signers = signerMap().get(name);
862 863 864 865 866 867 868 869 870 871 872 873 874
        return mapSignersToCodeSource(url, signers);
    }

    public CodeSource getCodeSource(URL url, JarFile jar, JarEntry je) {
        CodeSigner[] signers;

        return mapSignersToCodeSource(url, getCodeSigners(jar, je));
    }

    public void setEagerValidation(boolean eager) {
        eagerValidation = eager;
    }

875
    public synchronized List<Object> getManifestDigests() {
876 877 878 879 880 881
        return Collections.unmodifiableList(manifestDigests);
    }

    static CodeSource getUnsignedCS(URL url) {
        return new VerifierCodeSource(null, url, (java.security.cert.Certificate[]) null);
    }
I
igerasim 已提交
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901

    /**
     * Returns whether the name is trusted. Used by
     * {@link Manifest#getTrustedAttributes(String)}.
     */
    boolean isTrustedManifestEntry(String name) {
        // How many signers? MANIFEST.MF is always verified
        CodeSigner[] forMan = verifiedSigners.get(JarFile.MANIFEST_NAME);
        if (forMan == null) {
            return true;
        }
        // Check sigFileSigners first, because we are mainly dealing with
        // non-file entries which will stay in sigFileSigners forever.
        CodeSigner[] forName = sigFileSigners.get(name);
        if (forName == null) {
            forName = verifiedSigners.get(name);
        }
        // Returns trusted if all signers sign the entry
        return forName != null && forName.length == forMan.length;
    }
D
duke 已提交
902
}