/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package java.net; import java.util.Enumeration; import java.util.Vector; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import java.net.InetAddress; import java.security.Permission; import java.security.PermissionCollection; import java.io.Serializable; import java.io.ObjectStreamField; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import sun.net.util.IPAddressUtil; import sun.net.RegisteredDomain; import sun.security.util.SecurityConstants; import sun.security.util.Debug; /** * This class represents access to a network via sockets. * A SocketPermission consists of a * host specification and a set of "actions" specifying ways to * connect to that host. The host is specified as *
* host = (hostname | IPv4address | iPv6reference) [:portrange] * portrange = portnumber | -portnumber | portnumber-[portnumber] ** The host is expressed as a DNS name, as a numerical IP address, * or as "localhost" (for the local machine). * The wildcard "*" may be included once in a DNS name host * specification. If it is included, it must be in the leftmost * position, as in "*.sun.com". *
* The format of the IPv6reference should follow that specified in RFC 2732: Format * for Literal IPv6 Addresses in URLs: *
* ipv6reference = "[" IPv6address "]" ** For example, you can construct a SocketPermission instance * as the following: *
* String hostAddress = inetaddress.getHostAddress(); * if (inetaddress instanceof Inet6Address) { * sp = new SocketPermission("[" + hostAddress + "]:" + port, action); * } else { * sp = new SocketPermission(hostAddress + ":" + port, action); * } ** or *
* String host = url.getHost(); * sp = new SocketPermission(host + ":" + port, action); **
* The full uncompressed form of * an IPv6 literal address is also valid. *
* The port or portrange is optional. A port specification of the * form "N-", where N is a port number, signifies all ports * numbered N and above, while a specification of the * form "-N" indicates all ports numbered N and below. *
* The possible ways to connect to the host are *
* accept * connect * listen * resolve ** The "listen" action is only meaningful when used with "localhost". * The "resolve" action is implied when any of the other actions are present. * The action "resolve" refers to host/ip name service lookups. *
* The actions string is converted to lowercase before processing. *
As an example of the creation and meaning of SocketPermissions, * note that if the following permission: * *
* p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept"); ** * is granted to some code, it allows that code to connect to port 7777 on *
puffin.eng.sun.com
, and to accept connections on that port.
*
* Similarly, if the following permission: * *
* p2 = new SocketPermission("localhost:1024-", "accept,connect,listen"); ** * is granted to some code, it allows that code to * accept connections on, connect to, or listen on any port between * 1024 and 65535 on the local host. * *
Note: Granting code permission to accept or make connections to remote * hosts may be dangerous because malevolent code can then more easily * transfer and share confidential data among parties who may not * otherwise have access to the data. * * @see java.security.Permissions * @see SocketPermission * * * @author Marianne Mueller * @author Roland Schemers * * @serial exclude */ public final class SocketPermission extends Permission implements java.io.Serializable { private static final long serialVersionUID = -7204263841984476862L; /** * Connect to host:port */ private final static int CONNECT = 0x1; /** * Listen on host:port */ private final static int LISTEN = 0x2; /** * Accept a connection from host:port */ private final static int ACCEPT = 0x4; /** * Resolve DNS queries */ private final static int RESOLVE = 0x8; /** * No actions */ private final static int NONE = 0x0; /** * All actions */ private final static int ALL = CONNECT|LISTEN|ACCEPT|RESOLVE; // various port constants private static final int PORT_MIN = 0; private static final int PORT_MAX = 65535; private static final int PRIV_PORT_MAX = 1023; // the actions mask private transient int mask; /** * the actions string. * * @serial */ private String actions; // Left null as long as possible, then // created and re-used in the getAction function. // hostname part as it is passed private transient String hostname; // the canonical name of the host // in the case of "*.foo.com", cname is ".foo.com". private transient String cname; // all the IP addresses of the host private transient InetAddress[] addresses; // true if the hostname is a wildcard (e.g. "*.sun.com") private transient boolean wildcard; // true if we were initialized with a single numeric IP address private transient boolean init_with_ip; // true if this SocketPermission represents an invalid/unknown host // used for implies when the delayed lookup has already failed private transient boolean invalid; // port range on host private transient int[] portrange; private transient boolean defaultDeny = false; // true if this SocketPermission represents a hostname // that failed our reverse mapping heuristic test private transient boolean untrusted; private transient boolean trusted; // true if the sun.net.trustNameService system property is set private static boolean trustNameService; private static Debug debug = null; private static boolean debugInit = false; static { Boolean tmp = java.security.AccessController.doPrivileged( new sun.security.action.GetBooleanAction("sun.net.trustNameService")); trustNameService = tmp.booleanValue(); } private static synchronized Debug getDebug() { if (!debugInit) { debug = Debug.getInstance("access"); debugInit = true; } return debug; } /** * Creates a new SocketPermission object with the specified actions. * The host is expressed as a DNS name, or as a numerical IP address. * Optionally, a port or a portrange may be supplied (separated * from the DNS name or IP address by a colon). *
* To specify the local machine, use "localhost" as the host. * Also note: An empty host String ("") is equivalent to "localhost". *
* The actions parameter contains a comma-separated list of the * actions granted for the specified host (and port(s)). Possible actions are * "connect", "listen", "accept", "resolve", or * any combination of those. "resolve" is automatically added * when any of the other three are specified. *
* Examples of SocketPermission instantiation are the following: *
* nr = new SocketPermission("www.catalog.com", "connect"); * nr = new SocketPermission("www.sun.com:80", "connect"); * nr = new SocketPermission("*.sun.com", "connect"); * nr = new SocketPermission("*.edu", "resolve"); * nr = new SocketPermission("204.160.241.0", "connect"); * nr = new SocketPermission("localhost:1024-65535", "listen"); * nr = new SocketPermission("204.160.241.0:1024-65535", "connect"); ** * @param host the hostname or IPaddress of the computer, optionally * including a colon followed by a port or port range. * @param action the action string. */ public SocketPermission(String host, String action) { super(getHost(host)); // name initialized to getHost(host); NPE detected in getHost() init(getName(), getMask(action)); } SocketPermission(String host, int mask) { super(getHost(host)); // name initialized to getHost(host); NPE detected in getHost() init(getName(), mask); } private void setDeny() { defaultDeny = true; } private static String getHost(String host) { if (host.equals("")) { return "localhost"; } else { /* IPv6 literal address used in this context should follow * the format specified in RFC 2732; * if not, we try to solve the unambiguous case */ int ind; if (host.charAt(0) != '[') { if ((ind = host.indexOf(':')) != host.lastIndexOf(':')) { /* More than one ":", meaning IPv6 address is not * in RFC 2732 format; * We will rectify user errors for all unambiguious cases */ StringTokenizer st = new StringTokenizer(host, ":"); int tokens = st.countTokens(); if (tokens == 9) { // IPv6 address followed by port ind = host.lastIndexOf(':'); host = "[" + host.substring(0, ind) + "]" + host.substring(ind); } else if (tokens == 8 && host.indexOf("::") == -1) { // IPv6 address only, not followed by port host = "[" + host + "]"; } else { // could be ambiguous throw new IllegalArgumentException("Ambiguous"+ " hostport part"); } } } return host; } } private int[] parsePort(String port) throws Exception { if (port == null || port.equals("") || port.equals("*")) { return new int[] {PORT_MIN, PORT_MAX}; } int dash = port.indexOf('-'); if (dash == -1) { int p = Integer.parseInt(port); return new int[] {p, p}; } else { String low = port.substring(0, dash); String high = port.substring(dash+1); int l,h; if (low.equals("")) { l = PORT_MIN; } else { l = Integer.parseInt(low); } if (high.equals("")) { h = PORT_MAX; } else { h = Integer.parseInt(high); } if (l < 0 || h < 0 || h
* More specifically, this method first ensures that all of the following * are true (and returns false if any of them are not):
*
*
*
*
implies
checks each of the following, in order,
* and for each returns true if the stated condition is true:*
*
*
*
*
implies
returns false.
* @param p the permission to check against.
*
* @return true if the specified permission is implied by this object,
* false if not.
*/
public boolean implies(Permission p) {
int i,j;
if (!(p instanceof SocketPermission))
return false;
if (p == this)
return true;
SocketPermission that = (SocketPermission) p;
return ((this.mask & that.mask) == that.mask) &&
impliesIgnoreMask(that);
}
/**
* Checks if the incoming Permission's action are a proper subset of
* the this object's actions.
* * Check, in the following order: *
* @param obj the object to test for equality with this object. * * @return true if obj is a SocketPermission, and has the * same hostname, port range, and actions as this * SocketPermission object. However, port range will be ignored * in the comparison if obj only contains the action, 'resolve'. */ public boolean equals(Object obj) { if (obj == this) return true; if (! (obj instanceof SocketPermission)) return false; SocketPermission that = (SocketPermission) obj; //this is (overly?) complex!!! // check the mask first if (this.mask != that.mask) return false; if ((that.mask & RESOLVE) != that.mask) { // now check the port range... if ((this.portrange[0] != that.portrange[0]) || (this.portrange[1] != that.portrange[1])) { return false; } } // short cut. This catches: // "crypto" equal to "crypto", or // "1.2.3.4" equal to "1.2.3.4.", or // "*.edu" equal to "*.edu", but it // does not catch "crypto" equal to // "crypto.eng.sun.com". if (this.getName().equalsIgnoreCase(that.getName())) { return true; } // we now attempt to get the Canonical (FQDN) name and // compare that. If this fails, about all we can do is return // false. try { this.getCanonName(); that.getCanonName(); } catch (UnknownHostException uhe) { return false; } if (this.invalid || that.invalid) return false; if (this.cname != null) { return this.cname.equalsIgnoreCase(that.cname); } return false; } /** * Returns the hash code value for this object. * * @return a hash code value for this object. */ public int hashCode() { /* * If this SocketPermission was initialized with an IP address * or a wildcard, use getName().hashCode(), otherwise use * the hashCode() of the host name returned from * java.net.InetAddress.getHostName method. */ if (init_with_ip || wildcard) { return this.getName().hashCode(); } try { getCanonName(); } catch (UnknownHostException uhe) { } if (invalid || cname == null) return this.getName().hashCode(); else return this.cname.hashCode(); } /** * Return the current action mask. * * @return the actions mask. */ int getMask() { return mask; } /** * Returns the "canonical string representation" of the actions in the * specified mask. * Always returns present actions in the following order: * connect, listen, accept, resolve. * * @param mask a specific integer action mask to translate into a string * @return the canonical string representation of the actions */ private static String getActions(int mask) { StringBuilder sb = new StringBuilder(); boolean comma = false; if ((mask & CONNECT) == CONNECT) { comma = true; sb.append("connect"); } if ((mask & LISTEN) == LISTEN) { if (comma) sb.append(','); else comma = true; sb.append("listen"); } if ((mask & ACCEPT) == ACCEPT) { if (comma) sb.append(','); else comma = true; sb.append("accept"); } if ((mask & RESOLVE) == RESOLVE) { if (comma) sb.append(','); else comma = true; sb.append("resolve"); } return sb.toString(); } /** * Returns the canonical string representation of the actions. * Always returns present actions in the following order: * connect, listen, accept, resolve. * * @return the canonical string representation of the actions. */ public String getActions() { if (actions == null) actions = getActions(this.mask); return actions; } /** * Returns a new PermissionCollection object for storing SocketPermission * objects. *
* SocketPermission objects must be stored in a manner that allows them
* to be inserted into the collection in any order, but that also enables the
* PermissionCollection implies
* method to be implemented in an efficient (and consistent) manner.
*
* @return a new PermissionCollection object suitable for storing SocketPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new SocketPermissionCollection();
}
/**
* WriteObject is called to save the state of the SocketPermission
* to a stream. The actions are serialized, and the superclass
* takes care of the name.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the actions. The superclass takes care of the name
// call getActions to make sure actions field is initialized
if (actions == null)
getActions();
s.defaultWriteObject();
}
/**
* readObject is called to restore the state of the SocketPermission from
* a stream.
*/
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the action, then initialize the rest
s.defaultReadObject();
init(getName(),getMask(actions));
}
/*
public String toString()
{
StringBuffer s = new StringBuffer(super.toString() + "\n" +
"cname = " + cname + "\n" +
"wildcard = " + wildcard + "\n" +
"invalid = " + invalid + "\n" +
"portrange = " + portrange[0] + "," + portrange[1] + "\n");
if (addresses != null) for (int i=0; i