CodeSource.java 12 KB
Newer Older
1
/* CodeSource.java -- Code location and certifcates
2
   Copyright (C) 1998, 2002, 2004  Free Software Foundation, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath 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 for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
37

38

39 40
package java.security;

41 42 43 44
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
45 46
import java.io.Serializable;
import java.net.SocketPermission;
47
import java.net.URL;
48 49 50 51
// Note that this overrides Certificate in this package.
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
52
import java.security.cert.CertificateFactory;
53 54 55
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
56 57 58

/**
 * This class represents a location from which code is loaded (as
59
 * represented by a URL), and the list of certificates that are used to
60 61
 * check the signatures of signed code loaded from this source.
 *
62 63
 * @author Aaron M. Renn (arenn@urbanophile.com)
 * @author Eric Blake (ebb9@email.byu.edu)
64 65
 * @since 1.1
 * @status updated to 1.4
66 67 68
 */
public class CodeSource implements Serializable
{
69 70 71 72
  /**
   * Compatible with JDK 1.1+.
   */
  private static final long serialVersionUID = 4977541819976013951L;
73 74 75 76

  /**
   * This is the URL that represents the code base from which code will
   * be loaded.
77 78
   *
   * @serial the code location
79
   */
80 81 82 83
  private final URL location;

  /** The set of certificates for this code base. */
  private transient HashSet certs;
84 85

  /**
86 87 88 89 90 91
   * This creates a new instance of <code>CodeSource</code> that loads code
   * from the specified URL location and which uses the specified certificates
   * for verifying signatures.
   *
   * @param location the location from which code will be loaded
   * @param certs the list of certificates
92
   */
93 94 95 96 97 98
  public CodeSource(URL location, Certificate[] certs)
  {
    this.location = location;
    if (certs != null)
      this.certs = new HashSet(Arrays.asList(certs));
  }
99 100

  /**
101
   * This method returns a hash value for this object.
102
   *
103
   * @return a hash value for this object
104
   */
105
  public int hashCode()
106
  {
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    return (location == null ? 0 : location.hashCode())
      ^ (certs == null ? 0 : certs.hashCode());
  }

  /**
   * This method tests the specified <code>Object</code> for equality with
   * this object.  This will be true if and only if the locations are equal
   * and the certificate sets are identical (ignoring order).
   *
   * @param obj the <code>Object</code> to test against
   * @return true if the specified object is equal to this one
   */
  public boolean equals(Object obj)
  {
    if (! (obj instanceof CodeSource))
      return false;
    CodeSource cs = (CodeSource) obj;
    return (certs == null ? cs.certs == null : certs.equals(cs.certs))
      && (location == null ? cs.location == null
          : location.equals(cs.location));
127 128 129 130 131 132
  }

  /**
   * This method returns the URL specifying the location from which code
   * will be loaded under this <code>CodeSource</code>.
   *
133
   * @return the code location for this <code>CodeSource</code>
134 135 136 137 138 139 140 141
   */
  public final URL getLocation()
  {
    return location;
  }

  /**
   * This method returns the list of digital certificates that can be used
142 143
   * to verify the signatures of code loaded under this
   * <code>CodeSource</code>.
144
   *
145
   * @return the certifcate list for this <code>CodeSource</code>
146
   */
147
  public final Certificate[] getCertificates()
148
  {
149 150 151 152 153
    if (certs == null)
      return null;
    Certificate[] c = new Certificate[certs.size()];
    certs.toArray(c);
    return c;
154 155 156
  }

  /**
157
   * This method tests to see if a specified <code>CodeSource</code> is
158
   * implied by this object.  Effectively, to meet this test, the specified
159 160
   * object must have all the certifcates this object has (but may have more),
   * and must have a location that is a subset of this object's.  In order
161
   * for this object to imply the specified object, the following must be
162 163 164
   * true:
   *
   * <ol>
165 166 167 168
   * <li><em>codesource</em> must not be <code>null</code>.</li>
   * <li>If <em>codesource</em> has a certificate list, all of it's
   *     certificates must be present in the certificate list of this
   *     code source.</li>
169
   * <li>If this object does not have a <code>null</code> location, then
170 171 172
   *     the following addtional tests must be passed.
   *
   *     <ol>
173 174 175
   *     <li><em>codesource</em> must not have a <code>null</code>
   *         location.</li>
   *     <li><em>codesource</em>'s location must be equal to this object's
176 177
   *         location, or
   *         <ul>
178 179 180 181 182 183 184 185 186 187 188 189 190
   *         <li><em>codesource</em>'s location protocol, port, and ref (aka,
   *             anchor) must equal this objects</li>
   *         <li><em>codesource</em>'s location host must imply this object's
   *             location host, as determined by contructing
   *             <code>SocketPermission</code> objects from each with no
   *             action list and using that classes's <code>implies</code>
   *             method</li>
   *         <li>If this object's location file ends with a '/', then the
   *             specified object's location file must start with this
   *             object's location file. Otherwise, the specified object's
   *             location file must start with this object's location file
   *             with the '/' character appended to it.</li>
   *         </ul></li>
191
   *     </ol></li>
192 193
   * </ol>
   *
194
   * <p>For example, each of these locations imply the location
195 196
   * "http://java.sun.com/classes/foo.jar":</p>
   * 
197 198 199 200 201 202
   * <pre>
   * http:
   * http://*.sun.com/classes/*
   * http://java.sun.com/classes/-
   * http://java.sun.com/classes/foo.jar
   * </pre>
203 204 205
   * 
   * <p>Note that the code source with null location and null certificates implies
   * all other code sources.</p>
206
   *
207 208
   * @param cs the <code>CodeSource</code> to test against this object
   * @return true if this specified <code>CodeSource</code> is implied
209 210 211 212 213
   */
  public boolean implies(CodeSource cs)
  {
    if (cs == null)
      return false;
214 215
    // First check the certificate list.
    if (certs != null && (cs.certs == null || ! certs.containsAll(cs.certs)))
216
      return false;
217 218 219 220 221 222 223 224 225
    // Next check the location.
    if (location == null)
      return true;
    if (cs.location == null
        || ! location.getProtocol().equals(cs.location.getProtocol())
        || (location.getPort() != -1
            && location.getPort() != cs.location.getPort())
        || (location.getRef() != null
            && ! location.getRef().equals(cs.location.getRef())))
226
      return false;
227
    if (location.getHost() != null)
228
      {
229 230 231 232 233 234 235 236 237
        String their_host = cs.location.getHost();
        if (their_host == null)
          return false;
        SocketPermission our_sockperm =
          new SocketPermission(location.getHost(), "accept");
        SocketPermission their_sockperm =
          new SocketPermission(their_host, "accept");
        if (! our_sockperm.implies(their_sockperm))
          return false;
238
      }
239
    String our_file = location.getFile();
240 241
    if (our_file != null)
      {
242 243 244 245 246 247
        if (! our_file.endsWith("/"))
          our_file += "/";
        String their_file = cs.location.getFile();
        if (their_file == null
            || ! their_file.startsWith(our_file))
          return false;
248 249 250 251 252
      }
    return true;
  }

  /**
253 254
   * This method returns a <code>String</code> that represents this object.
   * The result is in the format <code>"(" + getLocation()</code> followed
255
   * by a space separated list of certificates (or "&lt;no certificates&gt;"),
256
   * followed by <code>")"</code>.
257
   *
258
   * @return a <code>String</code> for this object
259
   */
260
  public String toString()
261
  {
262 263 264 265
    StringBuffer sb = new StringBuffer("(").append(location);
    if (certs == null || certs.isEmpty())
      sb.append(" <no certificates>");
    else
266
      {
267 268 269
        Iterator iter = certs.iterator();
        for (int i = certs.size(); --i >= 0; )
          sb.append(' ').append(iter.next());
270
      }
271
    return sb.append(")").toString();
272 273 274
  }

  /**
275
   * Reads this object from a serialization stream.
276
   *
277 278 279 280 281 282
   * @param s the input stream
   * @throws IOException if reading fails
   * @throws ClassNotFoundException if deserialization fails
   * @serialData this reads the location, then expects an int indicating the
   *             number of certificates. Each certificate is a String type
   *             followed by an int encoding length, then a byte[] encoding
283
   */
284 285
  private void readObject(ObjectInputStream s)
    throws IOException, ClassNotFoundException
286
  {
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    s.defaultReadObject();
    int count = s.readInt();
    certs = new HashSet();
    while (--count >= 0)
      {
        String type = (String) s.readObject();
        int bytes = s.readInt();
        byte[] encoded = new byte[bytes];
        for (int i = 0; i < bytes; i++)
          encoded[i] = s.readByte();
        ByteArrayInputStream stream = new ByteArrayInputStream(encoded);
        try
          {
            CertificateFactory factory = CertificateFactory.getInstance(type);
            certs.add(factory.generateCertificate(stream));
          }
        catch (CertificateException e)
          {
            // XXX Should we ignore this certificate?
          }
      }
308 309 310
  }

  /**
311
   * Writes this object to a serialization stream.
312
   *
313 314 315 316 317
   * @param s the output stream
   * @throws IOException if writing fails
   * @serialData this writes the location, then writes an int indicating the
   *             number of certificates. Each certificate is a String type
   *             followed by an int encoding length, then a byte[] encoding
318
   */
319
  private void writeObject(ObjectOutputStream s) throws IOException
320
  {
321
    s.defaultWriteObject();
322
    if (certs == null)
323
      s.writeInt(0);
324
    else
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
      {
        int count = certs.size();
        s.writeInt(count);
        Iterator iter = certs.iterator();
        while (--count >= 0)
          {
            Certificate c = (Certificate) iter.next();
            s.writeObject(c.getType());
            byte[] encoded;
            try
              {
                encoded = c.getEncoded();
              }
            catch (CertificateEncodingException e)
              {
                // XXX Should we ignore this certificate?
                encoded = null;
              }
            if (encoded == null)
              s.writeInt(0);
            else
              {
                s.writeInt(encoded.length);
                for (int i = 0; i < encoded.length; i++)
                  s.writeByte(encoded[i]);
              }
          }
      }
353
  }
354
} // class CodeSource