FileDocCategorySizeDatePackage
SocketPermission.javaAPI DocJava SE 5 API34566Fri Aug 26 14:57:08 BST 2005java.net

SocketPermission

public final class SocketPermission extends Permission implements Serializable
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.

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:

p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept");
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
version
1.59 04/02/12
author
Marianne Mueller
author
Roland Schemers
serial
exclude

Fields Summary
private static final long
serialVersionUID
private static final int
CONNECT
Connect to host:port
private static final int
LISTEN
Listen on host:port
private static final int
ACCEPT
Accept a connection from host:port
private static final int
RESOLVE
Resolve DNS queries
private static final int
NONE
No actions
private static final int
ALL
All actions
private static final int
PORT_MIN
private static final int
PORT_MAX
private static final int
PRIV_PORT_MAX
private transient int
mask
private String
actions
the actions string.
private transient String
hostname
private transient String
cname
private transient InetAddress[]
addresses
private transient boolean
wildcard
private transient boolean
init_with_ip
private transient boolean
invalid
private transient int[]
portrange
private static boolean
trustProxy
Constructors Summary
public SocketPermission(String host, String action)
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.


     
	Boolean tmp = (Boolean) java.security.AccessController.doPrivileged(
                new sun.security.action.GetBooleanAction("trustProxy"));
	trustProxy = tmp.booleanValue();
    
	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);
    
Methods Summary
public booleanequals(java.lang.Object obj)
Checks two SocketPermission objects for equality.

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'.

	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;
    
private static java.lang.StringgetActions(int 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

	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();
    
public java.lang.StringgetActions()
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.

	if (actions == null)
	    actions = getActions(this.mask);

	return actions;
    
voidgetCanonName()
attempt to get the fully qualified domain name

	if (cname != null || invalid) return;

	// attempt to get the canonical name

	try { 
	    // first get the IP addresses if we don't have them yet
	    // this is because we need the IP address to then get 
	    // FQDN.
	    if (addresses == null) {
		getIP();
	    }

	    // we have to do this check, otherwise we might not
	    // get the fully qualified domain name
	    if (init_with_ip) {
		cname = addresses[0].getHostName(false).toLowerCase();
	    } else {
	     cname = InetAddress.getByName(addresses[0].getHostAddress()).
                                              getHostName(false).toLowerCase();
	    }
	} catch (UnknownHostException uhe) {
	    invalid = true;
	    throw uhe;
	}
    
private static java.lang.StringgetHost(java.lang.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;
	}
    
voidgetIP()
get IP addresses. Sets invalid to true if we can't get them.

	if (addresses != null || wildcard || invalid) return;

	try { 
	    // now get all the IP addresses
	    String host;
	    if (getName().charAt(0) == '[") {
		// Literal IPv6 address
		host = getName().substring(1, getName().indexOf(']"));
	    } else {
		int i = getName().indexOf(":");
		if (i == -1)
		    host = getName();
		else {
		    host = getName().substring(0,i);
		}
	    }

	    addresses = 
		new InetAddress[] {InetAddress.getAllByName0(host, false)[0]};

	} catch (UnknownHostException uhe) {
	    invalid = true;
	    throw uhe;
	}  catch (IndexOutOfBoundsException iobe) {
	    invalid = true;
	    throw new UnknownHostException(getName());
	}
    
intgetMask()
Return the current action mask.

return
the actions mask.

	return mask;
    
private static intgetMask(java.lang.String action)
Convert an action string to an integer actions mask.

param
action the action string
return
the action mask


	if (action == null) {
	    throw new NullPointerException("action can't be null");
	}

	if (action.equals("")) {
	    throw new IllegalArgumentException("action can't be empty");
	}

	int mask = NONE;

	// Check against use of constants (used heavily within the JDK)
	if (action == SecurityConstants.SOCKET_RESOLVE_ACTION) {
	    return RESOLVE;
	} else if (action == SecurityConstants.SOCKET_CONNECT_ACTION) {
	    return CONNECT;
	} else if (action == SecurityConstants.SOCKET_LISTEN_ACTION) {
	    return LISTEN;
	} else if (action == SecurityConstants.SOCKET_ACCEPT_ACTION) {
	    return ACCEPT;
	} else if (action == SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION) {
	    return CONNECT|ACCEPT;
	}

	char[] a = action.toCharArray();

	int i = a.length - 1;
	if (i < 0)
	    return mask;

	while (i != -1) {
	    char c;

	    // skip whitespace
	    while ((i!=-1) && ((c = a[i]) == ' " ||
			       c == '\r" ||
			       c == '\n" ||
			       c == '\f" ||
			       c == '\t"))
		i--;

	    // check for the known strings
	    int matchlen;

	    if (i >= 6 && (a[i-6] == 'c" || a[i-6] == 'C") &&
			  (a[i-5] == 'o" || a[i-5] == 'O") &&
			  (a[i-4] == 'n" || a[i-4] == 'N") &&
			  (a[i-3] == 'n" || a[i-3] == 'N") &&
			  (a[i-2] == 'e" || a[i-2] == 'E") &&
			  (a[i-1] == 'c" || a[i-1] == 'C") &&
			  (a[i] == 't" || a[i] == 'T"))
	    {
		matchlen = 7;
		mask |= CONNECT;

	    } else if (i >= 6 && (a[i-6] == 'r" || a[i-6] == 'R") &&
				 (a[i-5] == 'e" || a[i-5] == 'E") &&
				 (a[i-4] == 's" || a[i-4] == 'S") &&
				 (a[i-3] == 'o" || a[i-3] == 'O") &&
				 (a[i-2] == 'l" || a[i-2] == 'L") &&
				 (a[i-1] == 'v" || a[i-1] == 'V") &&
				 (a[i] == 'e" || a[i] == 'E"))
	    {
		matchlen = 7;
		mask |= RESOLVE;

	    } else if (i >= 5 && (a[i-5] == 'l" || a[i-5] == 'L") &&
				 (a[i-4] == 'i" || a[i-4] == 'I") &&
				 (a[i-3] == 's" || a[i-3] == 'S") &&
				 (a[i-2] == 't" || a[i-2] == 'T") &&
				 (a[i-1] == 'e" || a[i-1] == 'E") &&
				 (a[i] == 'n" || a[i] == 'N"))
	    {
		matchlen = 6;
		mask |= LISTEN;

	    } else if (i >= 5 && (a[i-5] == 'a" || a[i-5] == 'A") &&
				 (a[i-4] == 'c" || a[i-4] == 'C") &&
				 (a[i-3] == 'c" || a[i-3] == 'C") &&
				 (a[i-2] == 'e" || a[i-2] == 'E") &&
				 (a[i-1] == 'p" || a[i-1] == 'P") &&
				 (a[i] == 't" || a[i] == 'T"))
	    {
		matchlen = 6;
		mask |= ACCEPT;

	    } else {
		// parse error
		throw new IllegalArgumentException(
			"invalid permission: " + action);
	    }

	    // make sure we didn't just match the tail of a word
	    // like "ackbarfaccept".  Also, skip to the comma.
	    boolean seencomma = false;
	    while (i >= matchlen && !seencomma) {
		switch(a[i-matchlen]) {
		case ',":
		    seencomma = true;
		    /*FALLTHROUGH*/
		case ' ": case '\r": case '\n":
		case '\f": case '\t":
		    break;
		default:
		    throw new IllegalArgumentException(
			    "invalid permission: " + action);
		}
		i--;
	    }

	    // point i at the location of the comma minus one (or -1).
	    i -= matchlen;
	}

	return mask;
    
public inthashCode()
Returns the hash code value for this object.

return
a hash code value for this object.

	/*
	 * 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();
    
public booleanimplies(java.security.Permission p)
Checks if this socket permission object "implies" the specified permission.

More specifically, this method first ensures that all of the following are true (and returns false if any of them are not):

  • p is an instanceof SocketPermission,

  • p's actions are a proper subset of this object's actions, and

  • p's port range is included in this port range. Note: port range is ignored when p only contains the action, 'resolve'.

Then implies checks each of the following, in order, and for each returns true if the stated condition is true:

  • If this object was initialized with a single IP address and one of p's IP addresses is equal to this object's IP address.

  • If this object is a wildcard domain (such as *.sun.com), and p's canonical name (the name without any preceding *) ends with this object's canonical host name. For example, *.sun.com implies *.eng.sun.com..

  • If this object was not initialized with a single IP address, and one of this object's IP addresses equals one of p's IP addresses.

  • If this canonical name equals p's canonical name.

If none of the above are 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.

	int i,j;

	if (!(p instanceof SocketPermission))
	    return false;

	SocketPermission that = (SocketPermission) p;

	return ((this.mask & that.mask) == that.mask) && 
	                                impliesIgnoreMask(that);
    
booleanimpliesIgnoreMask(java.net.SocketPermission that)
Checks if the incoming Permission's action are a proper subset of the this object's actions.

Check, in the following order:

  • Checks that "p" is an instanceof a SocketPermission
  • Checks that "p"'s actions are a proper subset of the current object's actions.
  • Checks that "p"'s port range is included in this port range
  • If this object was initialized with an IP address, checks that one of "p"'s IP addresses is equal to this object's IP address.
  • If either object is a wildcard domain (i.e., "*.sun.com"), attempt to match based on the wildcard.
  • If this object was not initialized with an IP address, attempt to find a match based on the IP addresses in both objects.
  • Attempt to match on the canonical hostnames of both objects.

param
p the incoming permission request
return
true if "permission" is a proper subset of the current object, false if not.

	int i,j;

	if ((that.mask & RESOLVE) != that.mask) {
	    // check port range
	    if ((that.portrange[0] < this.portrange[0]) ||
		    (that.portrange[1] > this.portrange[1])) {
		    return false;
	    }
	}

	// allow a "*" wildcard to always match anything
	if (this.wildcard && "".equals(this.cname))
	    return true;

	// return if either one of these NetPerm objects are invalid...
	if (this.invalid || that.invalid) {
	    return (trustProxy ? inProxyWeTrust(that) : false);
	}


	try {
	    if (this.init_with_ip) { // we only check IP addresses
		if (that.wildcard) 
		    return false;

		if (that.init_with_ip) {
		    return (this.addresses[0].equals(that.addresses[0]));
		} else {
		    if (that.addresses == null) {
			that.getIP();
		    }
		    for (i=0; i < that.addresses.length; i++) {
			if (this.addresses[0].equals(that.addresses[i]))
			    return true;
		    }
		}
		// since "this" was initialized with an IP address, we
		// don't check any other cases
		return false;
	    }

	    // check and see if we have any wildcards...
	    if (this.wildcard || that.wildcard) {
		// if they are both wildcards, return true iff
		// that's cname ends with this cname (i.e., *.sun.com
		// implies *.eng.sun.com)
		if (this.wildcard && that.wildcard)
		    return (that.cname.endsWith(this.cname));

		// a non-wildcard can't imply a wildcard
		if (that.wildcard)
		    return false;

		// this is a wildcard, lets see if that's cname ends with
		// it...
		if (that.cname == null) {
		    that.getCanonName();
		}
		return (that.cname.endsWith(this.cname));
	    }

	    // comapare IP addresses
	    if (this.addresses == null) {
		this.getIP();
	    }

	    if (that.addresses == null) {
		that.getIP();
	    }

	    for (j = 0; j < this.addresses.length; j++) {
		for (i=0; i < that.addresses.length; i++) {
		    if (this.addresses[j].equals(that.addresses[i]))
			return true;
		}
	    }

	    // XXX: if all else fails, compare hostnames?
	    // Do we really want this?
	    if (this.cname == null) {
		this.getCanonName();
	    }

	    if (that.cname == null) {
		that.getCanonName();
	    }

	    return (this.cname.equalsIgnoreCase(that.cname));

	} catch (UnknownHostException uhe) {
	    if (trustProxy)
		return inProxyWeTrust(that);
	}

	// make sure the first thing that is done here is to return
	// false. If not, uncomment the return false in the above catch.

	return false; 
    
private booleaninProxyWeTrust(java.net.SocketPermission that)

	// if we trust the proxy, we see if the original names/IPs passed
	// in were equal.

	String thisHost = hostname;
	String thatHost = that.hostname;

	if (thisHost == null) 
	    return false;
	else 
	    return thisHost.equalsIgnoreCase(thatHost);

    
private voidinit(java.lang.String host, int mask)
Initialize the SocketPermission object. We don't do any DNS lookups as this point, instead we hold off until the implies method is called.

	// Set the integer mask that represents the actions

	if ((mask & ALL) != mask) 
	    throw new IllegalArgumentException("invalid actions mask");

	// always OR in RESOLVE if we allow any of the others
	this.mask = mask | RESOLVE;

	// Parse the host name.  A name has up to three components, the
	// hostname, a port number, or two numbers representing a port
	// range.   "www.sun.com:8080-9090" is a valid host name. 
 
	// With IPv6 an address can be 2010:836B:4179::836B:4179 
	// An IPv6 address needs to be enclose in [] 
	// For ex: [2010:836B:4179::836B:4179]:8080-9090 
	// Refer to RFC 2732 for more information. 
	
	int rb = 0 ;
	int start = 0, end = 0;
	int sep = -1;
	String hostport = host;
	if (host.charAt(0) == '[") {
	    start = 1;
	    rb = host.indexOf(']");
	    if (rb != -1) {
		host = host.substring(start, rb);
	    } else {
		throw new 
		    IllegalArgumentException("invalid host/port: "+host);
	    }
	    sep = hostport.indexOf(':", rb+1);
	} else {
	    start = 0;
	    sep = host.indexOf(':", rb);
	    end = sep;
	    if (sep != -1) {
		host = host.substring(start, end);
	    }
	}
	
	if (sep != -1) {
	    String port = hostport.substring(sep+1);
	    try {
		portrange = parsePort(port);
	    } catch (Exception e) {
		throw new 
		    IllegalArgumentException("invalid port range: "+port);
	    }
	} else {
	    portrange = new int[] { PORT_MIN, PORT_MAX };
	}
	    
	hostname = host;

	// is this a domain wildcard specification
	if (host.lastIndexOf('*") > 0) {
	    throw new 
	       IllegalArgumentException("invalid host wildcard specification");
	} else if (host.startsWith("*")) {
	    wildcard = true;
	    if (host.equals("*")) {
		cname = "";
	    } else if (host.startsWith("*.")) {
		cname = host.substring(1).toLowerCase();
	    } else {
	      throw new 
	       IllegalArgumentException("invalid host wildcard specification");
	    }
	    return;
	} else {
	    if (host.length() > 0) {
	        // see if we are being initialized with an IP address.
	        char ch = host.charAt(0);
	        if (ch == ':" || Character.digit(ch, 16) != -1) {
		    byte ip[] = IPAddressUtil.textToNumericFormatV4(host);
		    if (ip == null) {
		        ip = IPAddressUtil.textToNumericFormatV6(host);
		    }
		    if (ip != null) {
		        try {
			    addresses = 
			        new InetAddress[]
				{InetAddress.getByAddress(ip) };
			    init_with_ip = true;
		        } catch (UnknownHostException uhe) {
			    // this shouldn't happen
			    invalid = true;
			}
		    }
		}
	    }
	}
    
public java.security.PermissionCollectionnewPermissionCollection()
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.

	return new SocketPermissionCollection();
    
private int[]parsePort(java.lang.String port)


	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<l) 
		throw new IllegalArgumentException("invalid port range");

	    return new int[] {l, h};
	}
    
private synchronized voidreadObject(java.io.ObjectInputStream s)
readObject is called to restore the state of the SocketPermission from a stream.

	// Read in the action, then initialize the rest
	s.defaultReadObject();
	init(getName(),getMask(actions));
    
private synchronized voidwriteObject(java.io.ObjectOutputStream s)
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.

	// 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();