JarFile.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. /* JarFile.java - Representation of a jar file
  2. Copyright (C) 2000, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util.jar;
  32. import gnu.java.io.Base64InputStream;
  33. import gnu.java.security.OID;
  34. import gnu.java.security.pkcs.PKCS7SignedData;
  35. import gnu.java.security.pkcs.SignerInfo;
  36. import gnu.java.security.provider.Gnu;
  37. import java.io.ByteArrayOutputStream;
  38. import java.io.File;
  39. import java.io.FileNotFoundException;
  40. import java.io.FilterInputStream;
  41. import java.io.IOException;
  42. import java.io.InputStream;
  43. import java.security.InvalidKeyException;
  44. import java.security.MessageDigest;
  45. import java.security.NoSuchAlgorithmException;
  46. import java.security.Signature;
  47. import java.security.SignatureException;
  48. import java.security.cert.CRLException;
  49. import java.security.cert.Certificate;
  50. import java.security.cert.CertificateException;
  51. import java.security.cert.X509Certificate;
  52. import java.util.Arrays;
  53. import java.util.Enumeration;
  54. import java.util.HashMap;
  55. import java.util.HashSet;
  56. import java.util.Iterator;
  57. import java.util.LinkedList;
  58. import java.util.List;
  59. import java.util.Map;
  60. import java.util.Set;
  61. import java.util.regex.Matcher;
  62. import java.util.regex.Pattern;
  63. import java.util.zip.ZipEntry;
  64. import java.util.zip.ZipException;
  65. import java.util.zip.ZipFile;
  66. /**
  67. * Representation of a jar file.
  68. * <p>
  69. * Note that this class is not a subclass of java.io.File but a subclass of
  70. * java.util.zip.ZipFile and you can only read JarFiles with it (although
  71. * there are constructors that take a File object).
  72. *
  73. * @since 1.2
  74. * @author Mark Wielaard (mark@klomp.org)
  75. * @author Casey Marshall (csm@gnu.org) wrote the certificate and entry
  76. * verification code.
  77. */
  78. public class JarFile extends ZipFile
  79. {
  80. // Fields
  81. /** The name of the manifest entry: META-INF/MANIFEST.MF */
  82. public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
  83. /** The META-INF directory entry. */
  84. private static final String META_INF = "META-INF/";
  85. /** The suffix for PKCS7 DSA signature entries. */
  86. private static final String PKCS7_DSA_SUFFIX = ".DSA";
  87. /** The suffix for PKCS7 RSA signature entries. */
  88. private static final String PKCS7_RSA_SUFFIX = ".RSA";
  89. /** The suffix for digest attributes. */
  90. private static final String DIGEST_KEY_SUFFIX = "-Digest";
  91. /** The suffix for signature files. */
  92. private static final String SF_SUFFIX = ".SF";
  93. /**
  94. * The security provider to use for signature verification.
  95. * We need a known fallback to be able to read any signed jar file
  96. * (which might contain the user selected security provider).
  97. * This is package-private to avoid accessor methods for inner classes.
  98. */
  99. static final Gnu provider = new Gnu();
  100. // Signature OIDs.
  101. private static final OID MD2_OID = new OID("1.2.840.113549.2.2");
  102. private static final OID MD4_OID = new OID("1.2.840.113549.2.4");
  103. private static final OID MD5_OID = new OID("1.2.840.113549.2.5");
  104. private static final OID SHA1_OID = new OID("1.3.14.3.2.26");
  105. private static final OID DSA_ENCRYPTION_OID = new OID("1.2.840.10040.4.1");
  106. private static final OID RSA_ENCRYPTION_OID = new OID("1.2.840.113549.1.1.1");
  107. /**
  108. * The manifest of this file, if any, otherwise null.
  109. * Read when first needed.
  110. */
  111. private Manifest manifest;
  112. /** Whether to verify the manifest and all entries. */
  113. boolean verify;
  114. /** Whether the has already been loaded. */
  115. private boolean manifestRead = false;
  116. /** Whether the signature files have been loaded. */
  117. boolean signaturesRead = false;
  118. /**
  119. * A map between entry names and booleans, signaling whether or
  120. * not that entry has been verified.
  121. * Only be accessed with lock on this JarFile*/
  122. HashMap verified = new HashMap();
  123. /**
  124. * A mapping from entry name to certificates, if any.
  125. * Only accessed with lock on this JarFile.
  126. */
  127. HashMap entryCerts;
  128. /**
  129. * A {@link Map} of message digest algorithm names to their implementation.
  130. * Used to reduce object (algorithm implementation) instantiation.
  131. */
  132. private HashMap digestAlgorithms = new HashMap();
  133. static boolean DEBUG = false;
  134. static void debug(Object msg)
  135. {
  136. System.err.print(JarFile.class.getName());
  137. System.err.print(" >>> ");
  138. System.err.println(msg);
  139. }
  140. // Constructors
  141. /**
  142. * Creates a new JarFile. All jar entries are verified (when a Manifest file
  143. * for this JarFile exists). You need to actually open and read the complete
  144. * jar entry (with <code>getInputStream()</code>) to check its signature.
  145. *
  146. * @param fileName the name of the file to open
  147. * @exception FileNotFoundException if the fileName cannot be found
  148. * @exception IOException if another IO exception occurs while reading
  149. */
  150. public JarFile(String fileName) throws FileNotFoundException, IOException
  151. {
  152. this(fileName, true);
  153. }
  154. /**
  155. * Creates a new JarFile. If verify is true then all jar entries are
  156. * verified (when a Manifest file for this JarFile exists). You need to
  157. * actually open and read the complete jar entry
  158. * (with <code>getInputStream()</code>) to check its signature.
  159. *
  160. * @param fileName the name of the file to open
  161. * @param verify checks manifest and entries when true and a manifest
  162. * exists, when false no checks are made
  163. * @exception FileNotFoundException if the fileName cannot be found
  164. * @exception IOException if another IO exception occurs while reading
  165. */
  166. public JarFile(String fileName, boolean verify) throws
  167. FileNotFoundException, IOException
  168. {
  169. super(fileName);
  170. if (verify)
  171. {
  172. manifest = readManifest();
  173. verify();
  174. }
  175. }
  176. /**
  177. * Creates a new JarFile. All jar entries are verified (when a Manifest file
  178. * for this JarFile exists). You need to actually open and read the complete
  179. * jar entry (with <code>getInputStream()</code>) to check its signature.
  180. *
  181. * @param file the file to open as a jar file
  182. * @exception FileNotFoundException if the file does not exits
  183. * @exception IOException if another IO exception occurs while reading
  184. */
  185. public JarFile(File file) throws FileNotFoundException, IOException
  186. {
  187. this(file, true);
  188. }
  189. /**
  190. * Creates a new JarFile. If verify is true then all jar entries are
  191. * verified (when a Manifest file for this JarFile exists). You need to
  192. * actually open and read the complete jar entry
  193. * (with <code>getInputStream()</code>) to check its signature.
  194. *
  195. * @param file the file to open to open as a jar file
  196. * @param verify checks manifest and entries when true and a manifest
  197. * exists, when false no checks are made
  198. * @exception FileNotFoundException if file does not exist
  199. * @exception IOException if another IO exception occurs while reading
  200. */
  201. public JarFile(File file, boolean verify) throws FileNotFoundException,
  202. IOException
  203. {
  204. super(file);
  205. if (verify)
  206. {
  207. manifest = readManifest();
  208. verify();
  209. }
  210. }
  211. /**
  212. * Creates a new JarFile with the indicated mode. If verify is true then
  213. * all jar entries are verified (when a Manifest file for this JarFile
  214. * exists). You need to actually open and read the complete jar entry
  215. * (with <code>getInputStream()</code>) to check its signature.
  216. * manifest and if the manifest exists and verify is true verfies it.
  217. *
  218. * @param file the file to open to open as a jar file
  219. * @param verify checks manifest and entries when true and a manifest
  220. * exists, when false no checks are made
  221. * @param mode either ZipFile.OPEN_READ or
  222. * (ZipFile.OPEN_READ | ZipFile.OPEN_DELETE)
  223. * @exception FileNotFoundException if the file does not exist
  224. * @exception IOException if another IO exception occurs while reading
  225. * @exception IllegalArgumentException when given an illegal mode
  226. *
  227. * @since 1.3
  228. */
  229. public JarFile(File file, boolean verify, int mode) throws
  230. FileNotFoundException, IOException, IllegalArgumentException
  231. {
  232. super(file, mode);
  233. if (verify)
  234. {
  235. manifest = readManifest();
  236. verify();
  237. }
  238. }
  239. // Methods
  240. /**
  241. * XXX - should verify the manifest file
  242. */
  243. private void verify()
  244. {
  245. // only check if manifest is not null
  246. if (manifest == null)
  247. {
  248. verify = false;
  249. return;
  250. }
  251. verify = true;
  252. // XXX - verify manifest
  253. }
  254. /**
  255. * Parses and returns the manifest if it exists, otherwise returns null.
  256. */
  257. private Manifest readManifest()
  258. {
  259. try
  260. {
  261. ZipEntry manEntry = super.getEntry(MANIFEST_NAME);
  262. if (manEntry != null)
  263. {
  264. InputStream in = super.getInputStream(manEntry);
  265. manifestRead = true;
  266. return new Manifest(in);
  267. }
  268. else
  269. {
  270. manifestRead = true;
  271. return null;
  272. }
  273. }
  274. catch (IOException ioe)
  275. {
  276. manifestRead = true;
  277. return null;
  278. }
  279. }
  280. /**
  281. * Returns a enumeration of all the entries in the JarFile.
  282. * Note that also the Jar META-INF entries are returned.
  283. *
  284. * @exception IllegalStateException when the JarFile is already closed
  285. */
  286. public Enumeration<JarEntry> entries() throws IllegalStateException
  287. {
  288. return new JarEnumeration(super.entries(), this);
  289. }
  290. /**
  291. * Wraps a given Zip Entries Enumeration. For every zip entry a
  292. * JarEntry is created and the corresponding Attributes are looked up.
  293. */
  294. private static class JarEnumeration implements Enumeration<JarEntry>
  295. {
  296. private final Enumeration<? extends ZipEntry> entries;
  297. private final JarFile jarfile;
  298. JarEnumeration(Enumeration<? extends ZipEntry> e, JarFile f)
  299. {
  300. entries = e;
  301. jarfile = f;
  302. }
  303. public boolean hasMoreElements()
  304. {
  305. return entries.hasMoreElements();
  306. }
  307. public JarEntry nextElement()
  308. {
  309. ZipEntry zip = (ZipEntry) entries.nextElement();
  310. JarEntry jar = new JarEntry(zip);
  311. Manifest manifest;
  312. try
  313. {
  314. manifest = jarfile.getManifest();
  315. }
  316. catch (IOException ioe)
  317. {
  318. manifest = null;
  319. }
  320. if (manifest != null)
  321. {
  322. jar.attr = manifest.getAttributes(jar.getName());
  323. }
  324. synchronized(jarfile)
  325. {
  326. if (jarfile.verify && !jarfile.signaturesRead)
  327. try
  328. {
  329. jarfile.readSignatures();
  330. }
  331. catch (IOException ioe)
  332. {
  333. if (JarFile.DEBUG)
  334. {
  335. JarFile.debug(ioe);
  336. ioe.printStackTrace();
  337. }
  338. jarfile.signaturesRead = true; // fudge it.
  339. }
  340. }
  341. jar.jarfile = jarfile;
  342. return jar;
  343. }
  344. }
  345. /**
  346. * XXX
  347. * It actually returns a JarEntry not a zipEntry
  348. * @param name XXX
  349. */
  350. public synchronized ZipEntry getEntry(String name)
  351. {
  352. ZipEntry entry = super.getEntry(name);
  353. if (entry != null)
  354. {
  355. JarEntry jarEntry = new JarEntry(entry);
  356. Manifest manifest;
  357. try
  358. {
  359. manifest = getManifest();
  360. }
  361. catch (IOException ioe)
  362. {
  363. manifest = null;
  364. }
  365. if (manifest != null)
  366. {
  367. jarEntry.attr = manifest.getAttributes(name);
  368. }
  369. if (verify && !signaturesRead)
  370. try
  371. {
  372. readSignatures();
  373. }
  374. catch (IOException ioe)
  375. {
  376. if (DEBUG)
  377. {
  378. debug(ioe);
  379. ioe.printStackTrace();
  380. }
  381. signaturesRead = true;
  382. }
  383. jarEntry.jarfile = this;
  384. return jarEntry;
  385. }
  386. return null;
  387. }
  388. /**
  389. * Returns an input stream for the given entry. If configured to
  390. * verify entries, the input stream returned will verify them while
  391. * the stream is read, but only on the first time.
  392. *
  393. * @param entry The entry to get the input stream for.
  394. * @exception ZipException XXX
  395. * @exception IOException XXX
  396. */
  397. public synchronized InputStream getInputStream(ZipEntry entry) throws
  398. ZipException, IOException
  399. {
  400. // If we haven't verified the hash, do it now.
  401. if (!verified.containsKey(entry.getName()) && verify)
  402. {
  403. if (DEBUG)
  404. debug("reading and verifying " + entry);
  405. return new EntryInputStream(entry, super.getInputStream(entry), this);
  406. }
  407. else
  408. {
  409. if (DEBUG)
  410. debug("reading already verified entry " + entry);
  411. if (verify && verified.get(entry.getName()) == Boolean.FALSE)
  412. throw new ZipException("digest for " + entry + " is invalid");
  413. return super.getInputStream(entry);
  414. }
  415. }
  416. /**
  417. * Returns the JarEntry that belongs to the name if such an entry
  418. * exists in the JarFile. Returns null otherwise
  419. * Convenience method that just casts the result from <code>getEntry</code>
  420. * to a JarEntry.
  421. *
  422. * @param name the jar entry name to look up
  423. * @return the JarEntry if it exists, null otherwise
  424. */
  425. public JarEntry getJarEntry(String name)
  426. {
  427. return (JarEntry) getEntry(name);
  428. }
  429. /**
  430. * Returns the manifest for this JarFile or null when the JarFile does not
  431. * contain a manifest file.
  432. */
  433. public synchronized Manifest getManifest() throws IOException
  434. {
  435. if (!manifestRead)
  436. manifest = readManifest();
  437. return manifest;
  438. }
  439. // Only called with lock on this JarFile.
  440. // Package private for use in inner classes.
  441. void readSignatures() throws IOException
  442. {
  443. Map pkcs7Dsa = new HashMap();
  444. Map pkcs7Rsa = new HashMap();
  445. Map sigFiles = new HashMap();
  446. // Phase 1: Read all signature files. These contain the user
  447. // certificates as well as the signatures themselves.
  448. for (Enumeration e = super.entries(); e.hasMoreElements(); )
  449. {
  450. ZipEntry ze = (ZipEntry) e.nextElement();
  451. String name = ze.getName();
  452. if (name.startsWith(META_INF))
  453. {
  454. String alias = name.substring(META_INF.length());
  455. if (alias.lastIndexOf('.') >= 0)
  456. alias = alias.substring(0, alias.lastIndexOf('.'));
  457. if (name.endsWith(PKCS7_DSA_SUFFIX) || name.endsWith(PKCS7_RSA_SUFFIX))
  458. {
  459. if (DEBUG)
  460. debug("reading PKCS7 info from " + name + ", alias=" + alias);
  461. PKCS7SignedData sig = null;
  462. try
  463. {
  464. sig = new PKCS7SignedData(super.getInputStream(ze));
  465. }
  466. catch (CertificateException ce)
  467. {
  468. IOException ioe = new IOException("certificate parsing error");
  469. ioe.initCause(ce);
  470. throw ioe;
  471. }
  472. catch (CRLException crle)
  473. {
  474. IOException ioe = new IOException("CRL parsing error");
  475. ioe.initCause(crle);
  476. throw ioe;
  477. }
  478. if (name.endsWith(PKCS7_DSA_SUFFIX))
  479. pkcs7Dsa.put(alias, sig);
  480. else if (name.endsWith(PKCS7_RSA_SUFFIX))
  481. pkcs7Rsa.put(alias, sig);
  482. }
  483. else if (name.endsWith(SF_SUFFIX))
  484. {
  485. if (DEBUG)
  486. debug("reading signature file for " + alias + ": " + name);
  487. Manifest sf = new Manifest(super.getInputStream(ze));
  488. sigFiles.put(alias, sf);
  489. if (DEBUG)
  490. debug("result: " + sf);
  491. }
  492. }
  493. }
  494. // Phase 2: verify the signatures on any signature files.
  495. Set validCerts = new HashSet();
  496. Map entryCerts = new HashMap();
  497. for (Iterator it = sigFiles.entrySet().iterator(); it.hasNext(); )
  498. {
  499. int valid = 0;
  500. Map.Entry e = (Map.Entry) it.next();
  501. String alias = (String) e.getKey();
  502. PKCS7SignedData sig = (PKCS7SignedData) pkcs7Dsa.get(alias);
  503. if (sig != null)
  504. {
  505. Certificate[] certs = sig.getCertificates();
  506. Set signerInfos = sig.getSignerInfos();
  507. for (Iterator it2 = signerInfos.iterator(); it2.hasNext(); )
  508. verify(certs, (SignerInfo) it2.next(), alias, validCerts);
  509. }
  510. sig = (PKCS7SignedData) pkcs7Rsa.get(alias);
  511. if (sig != null)
  512. {
  513. Certificate[] certs = sig.getCertificates();
  514. Set signerInfos = sig.getSignerInfos();
  515. for (Iterator it2 = signerInfos.iterator(); it2.hasNext(); )
  516. verify(certs, (SignerInfo) it2.next(), alias, validCerts);
  517. }
  518. // It isn't a signature for anything. Punt it.
  519. if (validCerts.isEmpty())
  520. {
  521. it.remove();
  522. continue;
  523. }
  524. entryCerts.put(e.getValue(), new HashSet(validCerts));
  525. validCerts.clear();
  526. }
  527. // Read the manifest into a HashMap (String fileName, String entry)
  528. // The fileName might be split into multiple lines in the manifest.
  529. // Such additional lines will start with a space.
  530. InputStream in = super.getInputStream(super.getEntry(MANIFEST_NAME));
  531. ByteArrayOutputStream baStream = new ByteArrayOutputStream();
  532. byte[] ba = new byte[1024];
  533. while (true)
  534. {
  535. int len = in.read(ba);
  536. if (len < 0)
  537. break;
  538. baStream.write(ba, 0, len);
  539. }
  540. in.close();
  541. HashMap hmManifestEntries = new HashMap();
  542. Pattern p = Pattern.compile("Name: (.+?\r?\n(?: .+?\r?\n)*)"
  543. + ".+?-Digest: .+?\r?\n\r?\n");
  544. Matcher m = p.matcher(baStream.toString());
  545. while (m.find())
  546. {
  547. String fileName = m.group(1).replaceAll("\r?\n ?", "");
  548. hmManifestEntries.put(fileName, m.group());
  549. }
  550. // Phase 3: verify the signature file signatures against the manifest,
  551. // mapping the entry name to the target certificates.
  552. this.entryCerts = new HashMap();
  553. for (Iterator it = entryCerts.entrySet().iterator(); it.hasNext(); )
  554. {
  555. Map.Entry e = (Map.Entry) it.next();
  556. Manifest sigfile = (Manifest) e.getKey();
  557. Map entries = sigfile.getEntries();
  558. Set certificates = (Set) e.getValue();
  559. for (Iterator it2 = entries.entrySet().iterator(); it2.hasNext(); )
  560. {
  561. Map.Entry e2 = (Map.Entry) it2.next();
  562. String entryname = String.valueOf(e2.getKey());
  563. Attributes attr = (Attributes) e2.getValue();
  564. if (verifyHashes(entryname, attr, hmManifestEntries))
  565. {
  566. if (DEBUG)
  567. debug("entry " + entryname + " has certificates " + certificates);
  568. Set s = (Set) this.entryCerts.get(entryname);
  569. if (s != null)
  570. s.addAll(certificates);
  571. else
  572. this.entryCerts.put(entryname, new HashSet(certificates));
  573. }
  574. }
  575. }
  576. signaturesRead = true;
  577. }
  578. /**
  579. * Tell if the given signer info is over the given alias's signature file,
  580. * given one of the certificates specified.
  581. */
  582. private void verify(Certificate[] certs, SignerInfo signerInfo,
  583. String alias, Set validCerts)
  584. {
  585. Signature sig = null;
  586. try
  587. {
  588. OID alg = signerInfo.getDigestEncryptionAlgorithmId();
  589. if (alg.equals(DSA_ENCRYPTION_OID))
  590. {
  591. if (!signerInfo.getDigestAlgorithmId().equals(SHA1_OID))
  592. return;
  593. sig = Signature.getInstance("SHA1withDSA", provider);
  594. }
  595. else if (alg.equals(RSA_ENCRYPTION_OID))
  596. {
  597. OID hash = signerInfo.getDigestAlgorithmId();
  598. if (hash.equals(MD2_OID))
  599. sig = Signature.getInstance("md2WithRsaEncryption", provider);
  600. else if (hash.equals(MD4_OID))
  601. sig = Signature.getInstance("md4WithRsaEncryption", provider);
  602. else if (hash.equals(MD5_OID))
  603. sig = Signature.getInstance("md5WithRsaEncryption", provider);
  604. else if (hash.equals(SHA1_OID))
  605. sig = Signature.getInstance("sha1WithRsaEncryption", provider);
  606. else
  607. return;
  608. }
  609. else
  610. {
  611. if (DEBUG)
  612. debug("unsupported signature algorithm: " + alg);
  613. return;
  614. }
  615. }
  616. catch (NoSuchAlgorithmException nsae)
  617. {
  618. if (DEBUG)
  619. {
  620. debug(nsae);
  621. nsae.printStackTrace();
  622. }
  623. return;
  624. }
  625. ZipEntry sigFileEntry = super.getEntry(META_INF + alias + SF_SUFFIX);
  626. if (sigFileEntry == null)
  627. return;
  628. for (int i = 0; i < certs.length; i++)
  629. {
  630. if (!(certs[i] instanceof X509Certificate))
  631. continue;
  632. X509Certificate cert = (X509Certificate) certs[i];
  633. if (!cert.getIssuerX500Principal().equals(signerInfo.getIssuer()) ||
  634. !cert.getSerialNumber().equals(signerInfo.getSerialNumber()))
  635. continue;
  636. try
  637. {
  638. sig.initVerify(cert.getPublicKey());
  639. InputStream in = super.getInputStream(sigFileEntry);
  640. if (in == null)
  641. continue;
  642. byte[] buf = new byte[1024];
  643. int len = 0;
  644. while ((len = in.read(buf)) != -1)
  645. sig.update(buf, 0, len);
  646. if (sig.verify(signerInfo.getEncryptedDigest()))
  647. {
  648. if (DEBUG)
  649. debug("signature for " + cert.getSubjectDN() + " is good");
  650. validCerts.add(cert);
  651. }
  652. }
  653. catch (IOException ioe)
  654. {
  655. continue;
  656. }
  657. catch (InvalidKeyException ike)
  658. {
  659. continue;
  660. }
  661. catch (SignatureException se)
  662. {
  663. continue;
  664. }
  665. }
  666. }
  667. /**
  668. * Verifies that the digest(s) in a signature file were, in fact, made over
  669. * the manifest entry for ENTRY.
  670. *
  671. * @param entry The entry name.
  672. * @param attr The attributes from the signature file to verify.
  673. * @param hmManifestEntries Mappings of Jar file entry names to their manifest
  674. * entry text; i.e. the base-64 encoding of their
  675. */
  676. private boolean verifyHashes(String entry, Attributes attr,
  677. HashMap hmManifestEntries)
  678. {
  679. int verified = 0;
  680. String stringEntry = (String) hmManifestEntries.get(entry);
  681. if (stringEntry == null)
  682. {
  683. if (DEBUG)
  684. debug("could not find " + entry + " in manifest");
  685. return false;
  686. }
  687. // The bytes for ENTRY's manifest entry, which are signed in the
  688. // signature file.
  689. byte[] entryBytes = stringEntry.getBytes();
  690. for (Iterator it = attr.entrySet().iterator(); it.hasNext(); )
  691. {
  692. Map.Entry e = (Map.Entry) it.next();
  693. String key = String.valueOf(e.getKey());
  694. if (!key.endsWith(DIGEST_KEY_SUFFIX))
  695. continue;
  696. String alg = key.substring(0, key.length() - DIGEST_KEY_SUFFIX.length());
  697. try
  698. {
  699. byte[] hash = Base64InputStream.decode((String) e.getValue());
  700. MessageDigest md = (MessageDigest) digestAlgorithms.get(alg);
  701. if (md == null)
  702. {
  703. md = MessageDigest.getInstance(alg, provider);
  704. digestAlgorithms.put(alg, md);
  705. }
  706. md.reset();
  707. byte[] hash2 = md.digest(entryBytes);
  708. if (DEBUG)
  709. debug("verifying SF entry " + entry + " alg: " + md.getAlgorithm()
  710. + " expect=" + new java.math.BigInteger(hash).toString(16)
  711. + " comp=" + new java.math.BigInteger(hash2).toString(16));
  712. if (!Arrays.equals(hash, hash2))
  713. return false;
  714. verified++;
  715. }
  716. catch (IOException ioe)
  717. {
  718. if (DEBUG)
  719. {
  720. debug(ioe);
  721. ioe.printStackTrace();
  722. }
  723. return false;
  724. }
  725. catch (NoSuchAlgorithmException nsae)
  726. {
  727. if (DEBUG)
  728. {
  729. debug(nsae);
  730. nsae.printStackTrace();
  731. }
  732. return false;
  733. }
  734. }
  735. // We have to find at least one valid digest.
  736. return verified > 0;
  737. }
  738. /**
  739. * A utility class that verifies jar entries as they are read.
  740. */
  741. private static class EntryInputStream extends FilterInputStream
  742. {
  743. private final JarFile jarfile;
  744. private final long length;
  745. private long pos;
  746. private final ZipEntry entry;
  747. private final byte[][] hashes;
  748. private final MessageDigest[] md;
  749. private boolean checked;
  750. EntryInputStream(final ZipEntry entry,
  751. final InputStream in,
  752. final JarFile jar)
  753. throws IOException
  754. {
  755. super(in);
  756. this.entry = entry;
  757. this.jarfile = jar;
  758. length = entry.getSize();
  759. pos = 0;
  760. checked = false;
  761. Attributes attr;
  762. Manifest manifest = jarfile.getManifest();
  763. if (manifest != null)
  764. attr = manifest.getAttributes(entry.getName());
  765. else
  766. attr = null;
  767. if (DEBUG)
  768. debug("verifying entry " + entry + " attr=" + attr);
  769. if (attr == null)
  770. {
  771. hashes = new byte[0][];
  772. md = new MessageDigest[0];
  773. }
  774. else
  775. {
  776. List hashes = new LinkedList();
  777. List md = new LinkedList();
  778. for (Iterator it = attr.entrySet().iterator(); it.hasNext(); )
  779. {
  780. Map.Entry e = (Map.Entry) it.next();
  781. String key = String.valueOf(e.getKey());
  782. if (key == null)
  783. continue;
  784. if (!key.endsWith(DIGEST_KEY_SUFFIX))
  785. continue;
  786. hashes.add(Base64InputStream.decode((String) e.getValue()));
  787. try
  788. {
  789. int length = key.length() - DIGEST_KEY_SUFFIX.length();
  790. String alg = key.substring(0, length);
  791. md.add(MessageDigest.getInstance(alg, provider));
  792. }
  793. catch (NoSuchAlgorithmException nsae)
  794. {
  795. IOException ioe = new IOException("no such message digest: " + key);
  796. ioe.initCause(nsae);
  797. throw ioe;
  798. }
  799. }
  800. if (DEBUG)
  801. debug("digests=" + md);
  802. this.hashes = (byte[][]) hashes.toArray(new byte[hashes.size()][]);
  803. this.md = (MessageDigest[]) md.toArray(new MessageDigest[md.size()]);
  804. }
  805. }
  806. public boolean markSupported()
  807. {
  808. return false;
  809. }
  810. public void mark(int readLimit)
  811. {
  812. }
  813. public void reset()
  814. {
  815. }
  816. public int read() throws IOException
  817. {
  818. int b = super.read();
  819. if (b == -1)
  820. {
  821. eof();
  822. return -1;
  823. }
  824. for (int i = 0; i < md.length; i++)
  825. md[i].update((byte) b);
  826. pos++;
  827. if (length > 0 && pos >= length)
  828. eof();
  829. return b;
  830. }
  831. public int read(byte[] buf, int off, int len) throws IOException
  832. {
  833. int count = super.read(buf, off, (int) Math.min(len, (length != 0
  834. ? length - pos
  835. : Integer.MAX_VALUE)));
  836. if (count == -1 || (length > 0 && pos >= length))
  837. {
  838. eof();
  839. return -1;
  840. }
  841. for (int i = 0; i < md.length; i++)
  842. md[i].update(buf, off, count);
  843. pos += count;
  844. if (length != 0 && pos >= length)
  845. eof();
  846. return count;
  847. }
  848. public int read(byte[] buf) throws IOException
  849. {
  850. return read(buf, 0, buf.length);
  851. }
  852. public long skip(long bytes) throws IOException
  853. {
  854. byte[] b = new byte[1024];
  855. long amount = 0;
  856. while (amount < bytes)
  857. {
  858. int l = read(b, 0, (int) Math.min(b.length, bytes - amount));
  859. if (l == -1)
  860. break;
  861. amount += l;
  862. }
  863. return amount;
  864. }
  865. private void eof() throws IOException
  866. {
  867. if (checked)
  868. return;
  869. checked = true;
  870. for (int i = 0; i < md.length; i++)
  871. {
  872. byte[] hash = md[i].digest();
  873. if (DEBUG)
  874. debug("verifying " + md[i].getAlgorithm() + " expect="
  875. + new java.math.BigInteger(hashes[i]).toString(16)
  876. + " comp=" + new java.math.BigInteger(hash).toString(16));
  877. if (!Arrays.equals(hash, hashes[i]))
  878. {
  879. synchronized(jarfile)
  880. {
  881. if (DEBUG)
  882. debug(entry + " could NOT be verified");
  883. jarfile.verified.put(entry.getName(), Boolean.FALSE);
  884. }
  885. return;
  886. // XXX ??? what do we do here?
  887. // throw new ZipException("message digest mismatch");
  888. }
  889. }
  890. synchronized(jarfile)
  891. {
  892. if (DEBUG)
  893. debug(entry + " has been VERIFIED");
  894. jarfile.verified.put(entry.getName(), Boolean.TRUE);
  895. }
  896. }
  897. }
  898. }