1 /*
   2  * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.net;
  27 
  28 import java.util.Enumeration;
  29 import java.util.Vector;
  30 import java.util.List;
  31 import java.util.ArrayList;
  32 import java.util.Collections;
  33 import java.util.StringTokenizer;
  34 import java.net.InetAddress;
  35 import java.security.Permission;
  36 import java.security.PermissionCollection;
  37 import java.io.Serializable;
  38 import java.io.ObjectStreamField;
  39 import java.io.ObjectOutputStream;
  40 import java.io.ObjectInputStream;
  41 import java.io.IOException;
  42 import sun.net.util.IPAddressUtil;
  43 import sun.net.RegisteredDomain;
  44 import sun.security.util.SecurityConstants;
  45 import sun.security.util.Debug;
  46 
  47 
  48 /**
  49  * This class represents access to a network via sockets.
  50  * A SocketPermission consists of a
  51  * host specification and a set of "actions" specifying ways to
  52  * connect to that host. The host is specified as
  53  * <pre>
  54  *    host = (hostname | IPv4address | iPv6reference) [:portrange]
  55  *    portrange = portnumber | -portnumber | portnumber-[portnumber]
  56  * </pre>
  57  * The host is expressed as a DNS name, as a numerical IP address,
  58  * or as "localhost" (for the local machine).
  59  * The wildcard "*" may be included once in a DNS name host
  60  * specification. If it is included, it must be in the leftmost
  61  * position, as in "*.sun.com".
  62  * <p>
  63  * The format of the IPv6reference should follow that specified in <a
  64  * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format
  65  * for Literal IPv6 Addresses in URLs</i></a>:
  66  * <pre>
  67  *    ipv6reference = "[" IPv6address "]"
  68  *</pre>
  69  * For example, you can construct a SocketPermission instance
  70  * as the following:
  71  * <pre>
  72  *    String hostAddress = inetaddress.getHostAddress();
  73  *    if (inetaddress instanceof Inet6Address) {
  74  *        sp = new SocketPermission("[" + hostAddress + "]:" + port, action);
  75  *    } else {
  76  *        sp = new SocketPermission(hostAddress + ":" + port, action);
  77  *    }
  78  * </pre>
  79  * or
  80  * <pre>
  81  *    String host = url.getHost();
  82  *    sp = new SocketPermission(host + ":" + port, action);
  83  * </pre>
  84  * <p>
  85  * The <A HREF="Inet6Address.html#lform">full uncompressed form</A> of
  86  * an IPv6 literal address is also valid.
  87  * <p>
  88  * The port or portrange is optional. A port specification of the
  89  * form "N-", where <i>N</i> is a port number, signifies all ports
  90  * numbered <i>N</i> and above, while a specification of the
  91  * form "-N" indicates all ports numbered <i>N</i> and below.
  92  * <p>
  93  * The possible ways to connect to the host are
  94  * <pre>
  95  * accept
  96  * connect
  97  * listen
  98  * resolve
  99  * </pre>
 100  * The "listen" action is only meaningful when used with "localhost".
 101  * The "resolve" action is implied when any of the other actions are present.
 102  * The action "resolve" refers to host/ip name service lookups.
 103  * <P>
 104  * The actions string is converted to lowercase before processing.
 105  * <p>As an example of the creation and meaning of SocketPermissions,
 106  * note that if the following permission:
 107  *
 108  * <pre>
 109  *   p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept");
 110  * </pre>
 111  *
 112  * is granted to some code, it allows that code to connect to port 7777 on
 113  * <code>puffin.eng.sun.com</code>, and to accept connections on that port.
 114  *
 115  * <p>Similarly, if the following permission:
 116  *
 117  * <pre>
 118  *   p2 = new SocketPermission("localhost:1024-", "accept,connect,listen");
 119  * </pre>
 120  *
 121  * is granted to some code, it allows that code to
 122  * accept connections on, connect to, or listen on any port between
 123  * 1024 and 65535 on the local host.
 124  *
 125  * <p>Note: Granting code permission to accept or make connections to remote
 126  * hosts may be dangerous because malevolent code can then more easily
 127  * transfer and share confidential data among parties who may not
 128  * otherwise have access to the data.
 129  *
 130  * @see java.security.Permissions
 131  * @see SocketPermission
 132  *
 133  *
 134  * @author Marianne Mueller
 135  * @author Roland Schemers
 136  *
 137  * @serial exclude
 138  */
 139 
 140 public final class SocketPermission extends Permission
 141     implements java.io.Serializable
 142 {
 143     private static final long serialVersionUID = -7204263841984476862L;
 144 
 145     /**
 146      * Connect to host:port
 147      */
 148     private final static int CONNECT    = 0x1;
 149 
 150     /**
 151      * Listen on host:port
 152      */
 153     private final static int LISTEN     = 0x2;
 154 
 155     /**
 156      * Accept a connection from host:port
 157      */
 158     private final static int ACCEPT     = 0x4;
 159 
 160     /**
 161      * Resolve DNS queries
 162      */
 163     private final static int RESOLVE    = 0x8;
 164 
 165     /**
 166      * No actions
 167      */
 168     private final static int NONE               = 0x0;
 169 
 170     /**
 171      * All actions
 172      */
 173     private final static int ALL        = CONNECT|LISTEN|ACCEPT|RESOLVE;
 174 
 175     // various port constants
 176     private static final int PORT_MIN = 0;
 177     private static final int PORT_MAX = 65535;
 178     private static final int PRIV_PORT_MAX = 1023;
 179 
 180     // the actions mask
 181     private transient int mask;
 182 
 183     /**
 184      * the actions string.
 185      *
 186      * @serial
 187      */
 188 
 189     private String actions; // Left null as long as possible, then
 190                             // created and re-used in the getAction function.
 191 
 192     // hostname part as it is passed
 193     private transient String hostname;
 194 
 195     // the canonical name of the host
 196     // in the case of "*.foo.com", cname is ".foo.com".
 197 
 198     private transient String cname;
 199 
 200     // all the IP addresses of the host
 201     private transient InetAddress[] addresses;
 202 
 203     // true if the hostname is a wildcard (e.g. "*.sun.com")
 204     private transient boolean wildcard;
 205 
 206     // true if we were initialized with a single numeric IP address
 207     private transient boolean init_with_ip;
 208 
 209     // true if this SocketPermission represents an invalid/unknown host
 210     // used for implies when the delayed lookup has already failed
 211     private transient boolean invalid;
 212 
 213     // port range on host
 214     private transient int[] portrange;
 215 
 216     private transient boolean defaultDeny = false;
 217 
 218     // true if this SocketPermission represents a hostname
 219     // that failed our reverse mapping heuristic test
 220     private transient boolean untrusted;
 221     private transient boolean trusted;
 222 
 223     // true if the sun.net.trustNameService system property is set
 224     private static boolean trustNameService;
 225 
 226     private static Debug debug = null;
 227     private static boolean debugInit = false;
 228 
 229     static {
 230         Boolean tmp = java.security.AccessController.doPrivileged(
 231                 new sun.security.action.GetBooleanAction("sun.net.trustNameService"));
 232         trustNameService = tmp.booleanValue();
 233     }
 234 
 235     private static synchronized Debug getDebug() {
 236         if (!debugInit) {
 237             debug = Debug.getInstance("access");
 238             debugInit = true;
 239         }
 240         return debug;
 241     }
 242 
 243     /**
 244      * Creates a new SocketPermission object with the specified actions.
 245      * The host is expressed as a DNS name, or as a numerical IP address.
 246      * Optionally, a port or a portrange may be supplied (separated
 247      * from the DNS name or IP address by a colon).
 248      * <p>
 249      * To specify the local machine, use "localhost" as the <i>host</i>.
 250      * Also note: An empty <i>host</i> String ("") is equivalent to "localhost".
 251      * <p>
 252      * The <i>actions</i> parameter contains a comma-separated list of the
 253      * actions granted for the specified host (and port(s)). Possible actions are
 254      * "connect", "listen", "accept", "resolve", or
 255      * any combination of those. "resolve" is automatically added
 256      * when any of the other three are specified.
 257      * <p>
 258      * Examples of SocketPermission instantiation are the following:
 259      * <pre>
 260      *    nr = new SocketPermission("www.catalog.com", "connect");
 261      *    nr = new SocketPermission("www.sun.com:80", "connect");
 262      *    nr = new SocketPermission("*.sun.com", "connect");
 263      *    nr = new SocketPermission("*.edu", "resolve");
 264      *    nr = new SocketPermission("204.160.241.0", "connect");
 265      *    nr = new SocketPermission("localhost:1024-65535", "listen");
 266      *    nr = new SocketPermission("204.160.241.0:1024-65535", "connect");
 267      * </pre>
 268      *
 269      * @param host the hostname or IPaddress of the computer, optionally
 270      * including a colon followed by a port or port range.
 271      * @param action the action string.
 272      */
 273     public SocketPermission(String host, String action) {
 274         super(getHost(host));
 275         // name initialized to getHost(host); NPE detected in getHost()
 276         init(getName(), getMask(action));
 277     }
 278 
 279 
 280     SocketPermission(String host, int mask) {
 281         super(getHost(host));
 282         // name initialized to getHost(host); NPE detected in getHost()
 283         init(getName(), mask);
 284     }
 285 
 286     private void setDeny() {
 287         defaultDeny = true;
 288     }
 289 
 290     private static String getHost(String host) {
 291         if (host.equals("")) {
 292             return "localhost";
 293         } else {
 294             /* IPv6 literal address used in this context should follow
 295              * the format specified in RFC 2732;
 296              * if not, we try to solve the unambiguous case
 297              */
 298             int ind;
 299             if (host.charAt(0) != '[') {
 300                 if ((ind = host.indexOf(':')) != host.lastIndexOf(':')) {
 301                     /* More than one ":", meaning IPv6 address is not
 302                      * in RFC 2732 format;
 303                      * We will rectify user errors for all unambiguious cases
 304                      */
 305                     StringTokenizer st = new StringTokenizer(host, ":");
 306                     int tokens = st.countTokens();
 307                     if (tokens == 9) {
 308                         // IPv6 address followed by port
 309                         ind = host.lastIndexOf(':');
 310                         host = "[" + host.substring(0, ind) + "]" +
 311                             host.substring(ind);
 312                     } else if (tokens == 8 && host.indexOf("::") == -1) {
 313                         // IPv6 address only, not followed by port
 314                         host = "[" + host + "]";
 315                     } else {
 316                         // could be ambiguous
 317                         throw new IllegalArgumentException("Ambiguous"+
 318                                                            " hostport part");
 319                     }
 320                 }
 321             }
 322             return host;
 323         }
 324     }
 325 
 326     private int[] parsePort(String port)
 327         throws Exception
 328     {
 329 
 330         if (port == null || port.equals("") || port.equals("*")) {
 331             return new int[] {PORT_MIN, PORT_MAX};
 332         }
 333 
 334         int dash = port.indexOf('-');
 335 
 336         if (dash == -1) {
 337             int p = Integer.parseInt(port);
 338             return new int[] {p, p};
 339         } else {
 340             String low = port.substring(0, dash);
 341             String high = port.substring(dash+1);
 342             int l,h;
 343 
 344             if (low.equals("")) {
 345                 l = PORT_MIN;
 346             } else {
 347                 l = Integer.parseInt(low);
 348             }
 349 
 350             if (high.equals("")) {
 351                 h = PORT_MAX;
 352             } else {
 353                 h = Integer.parseInt(high);
 354             }
 355             if (l < 0 || h < 0 || h<l)
 356                 throw new IllegalArgumentException("invalid port range");
 357 
 358             return new int[] {l, h};
 359         }
 360     }
 361 
 362     /**
 363      * Initialize the SocketPermission object. We don't do any DNS lookups
 364      * as this point, instead we hold off until the implies method is
 365      * called.
 366      */
 367     private void init(String host, int mask) {
 368         // Set the integer mask that represents the actions
 369 
 370         if ((mask & ALL) != mask)
 371             throw new IllegalArgumentException("invalid actions mask");
 372 
 373         // always OR in RESOLVE if we allow any of the others
 374         this.mask = mask | RESOLVE;
 375 
 376         // Parse the host name.  A name has up to three components, the
 377         // hostname, a port number, or two numbers representing a port
 378         // range.   "www.sun.com:8080-9090" is a valid host name.
 379 
 380         // With IPv6 an address can be 2010:836B:4179::836B:4179
 381         // An IPv6 address needs to be enclose in []
 382         // For ex: [2010:836B:4179::836B:4179]:8080-9090
 383         // Refer to RFC 2732 for more information.
 384 
 385         int rb = 0 ;
 386         int start = 0, end = 0;
 387         int sep = -1;
 388         String hostport = host;
 389         if (host.charAt(0) == '[') {
 390             start = 1;
 391             rb = host.indexOf(']');
 392             if (rb != -1) {
 393                 host = host.substring(start, rb);
 394             } else {
 395                 throw new
 396                     IllegalArgumentException("invalid host/port: "+host);
 397             }
 398             sep = hostport.indexOf(':', rb+1);
 399         } else {
 400             start = 0;
 401             sep = host.indexOf(':', rb);
 402             end = sep;
 403             if (sep != -1) {
 404                 host = host.substring(start, end);
 405             }
 406         }
 407 
 408         if (sep != -1) {
 409             String port = hostport.substring(sep+1);
 410             try {
 411                 portrange = parsePort(port);
 412             } catch (Exception e) {
 413                 throw new
 414                     IllegalArgumentException("invalid port range: "+port);
 415             }
 416         } else {
 417             portrange = new int[] { PORT_MIN, PORT_MAX };
 418         }
 419 
 420         hostname = host;
 421 
 422         // is this a domain wildcard specification
 423         if (host.lastIndexOf('*') > 0) {
 424             throw new
 425                IllegalArgumentException("invalid host wildcard specification");
 426         } else if (host.startsWith("*")) {
 427             wildcard = true;
 428             if (host.equals("*")) {
 429                 cname = "";
 430             } else if (host.startsWith("*.")) {
 431                 cname = host.substring(1).toLowerCase();
 432             } else {
 433               throw new
 434                IllegalArgumentException("invalid host wildcard specification");
 435             }
 436             return;
 437         } else {
 438             if (host.length() > 0) {
 439                 // see if we are being initialized with an IP address.
 440                 char ch = host.charAt(0);
 441                 if (ch == ':' || Character.digit(ch, 16) != -1) {
 442                     byte ip[] = IPAddressUtil.textToNumericFormatV4(host);
 443                     if (ip == null) {
 444                         ip = IPAddressUtil.textToNumericFormatV6(host);
 445                     }
 446                     if (ip != null) {
 447                         try {
 448                             addresses =
 449                                 new InetAddress[]
 450                                 {InetAddress.getByAddress(ip) };
 451                             init_with_ip = true;
 452                         } catch (UnknownHostException uhe) {
 453                             // this shouldn't happen
 454                             invalid = true;
 455                         }
 456                     }
 457                 }
 458             }
 459         }
 460     }
 461 
 462     /**
 463      * Convert an action string to an integer actions mask.
 464      *
 465      * @param action the action string
 466      * @return the action mask
 467      */
 468     private static int getMask(String action) {
 469 
 470         if (action == null) {
 471             throw new NullPointerException("action can't be null");
 472         }
 473 
 474         if (action.equals("")) {
 475             throw new IllegalArgumentException("action can't be empty");
 476         }
 477 
 478         int mask = NONE;
 479 
 480         // Use object identity comparison against known-interned strings for
 481         // performance benefit (these values are used heavily within the JDK).
 482         if (action == SecurityConstants.SOCKET_RESOLVE_ACTION) {
 483             return RESOLVE;
 484         } else if (action == SecurityConstants.SOCKET_CONNECT_ACTION) {
 485             return CONNECT;
 486         } else if (action == SecurityConstants.SOCKET_LISTEN_ACTION) {
 487             return LISTEN;
 488         } else if (action == SecurityConstants.SOCKET_ACCEPT_ACTION) {
 489             return ACCEPT;
 490         } else if (action == SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION) {
 491             return CONNECT|ACCEPT;
 492         }
 493 
 494         char[] a = action.toCharArray();
 495 
 496         int i = a.length - 1;
 497         if (i < 0)
 498             return mask;
 499 
 500         while (i != -1) {
 501             char c;
 502 
 503             // skip whitespace
 504             while ((i!=-1) && ((c = a[i]) == ' ' ||
 505                                c == '\r' ||
 506                                c == '\n' ||
 507                                c == '\f' ||
 508                                c == '\t'))
 509                 i--;
 510 
 511             // check for the known strings
 512             int matchlen;
 513 
 514             if (i >= 6 && (a[i-6] == 'c' || a[i-6] == 'C') &&
 515                           (a[i-5] == 'o' || a[i-5] == 'O') &&
 516                           (a[i-4] == 'n' || a[i-4] == 'N') &&
 517                           (a[i-3] == 'n' || a[i-3] == 'N') &&
 518                           (a[i-2] == 'e' || a[i-2] == 'E') &&
 519                           (a[i-1] == 'c' || a[i-1] == 'C') &&
 520                           (a[i] == 't' || a[i] == 'T'))
 521             {
 522                 matchlen = 7;
 523                 mask |= CONNECT;
 524 
 525             } else if (i >= 6 && (a[i-6] == 'r' || a[i-6] == 'R') &&
 526                                  (a[i-5] == 'e' || a[i-5] == 'E') &&
 527                                  (a[i-4] == 's' || a[i-4] == 'S') &&
 528                                  (a[i-3] == 'o' || a[i-3] == 'O') &&
 529                                  (a[i-2] == 'l' || a[i-2] == 'L') &&
 530                                  (a[i-1] == 'v' || a[i-1] == 'V') &&
 531                                  (a[i] == 'e' || a[i] == 'E'))
 532             {
 533                 matchlen = 7;
 534                 mask |= RESOLVE;
 535 
 536             } else if (i >= 5 && (a[i-5] == 'l' || a[i-5] == 'L') &&
 537                                  (a[i-4] == 'i' || a[i-4] == 'I') &&
 538                                  (a[i-3] == 's' || a[i-3] == 'S') &&
 539                                  (a[i-2] == 't' || a[i-2] == 'T') &&
 540                                  (a[i-1] == 'e' || a[i-1] == 'E') &&
 541                                  (a[i] == 'n' || a[i] == 'N'))
 542             {
 543                 matchlen = 6;
 544                 mask |= LISTEN;
 545 
 546             } else if (i >= 5 && (a[i-5] == 'a' || a[i-5] == 'A') &&
 547                                  (a[i-4] == 'c' || a[i-4] == 'C') &&
 548                                  (a[i-3] == 'c' || a[i-3] == 'C') &&
 549                                  (a[i-2] == 'e' || a[i-2] == 'E') &&
 550                                  (a[i-1] == 'p' || a[i-1] == 'P') &&
 551                                  (a[i] == 't' || a[i] == 'T'))
 552             {
 553                 matchlen = 6;
 554                 mask |= ACCEPT;
 555 
 556             } else {
 557                 // parse error
 558                 throw new IllegalArgumentException(
 559                         "invalid permission: " + action);
 560             }
 561 
 562             // make sure we didn't just match the tail of a word
 563             // like "ackbarfaccept".  Also, skip to the comma.
 564             boolean seencomma = false;
 565             while (i >= matchlen && !seencomma) {
 566                 switch(a[i-matchlen]) {
 567                 case ',':
 568                     seencomma = true;
 569                     break;
 570                 case ' ': case '\r': case '\n':
 571                 case '\f': case '\t':
 572                     break;
 573                 default:
 574                     throw new IllegalArgumentException(
 575                             "invalid permission: " + action);
 576                 }
 577                 i--;
 578             }
 579 
 580             // point i at the location of the comma minus one (or -1).
 581             i -= matchlen;
 582         }
 583 
 584         return mask;
 585     }
 586 
 587     private boolean isUntrusted()
 588         throws UnknownHostException
 589     {
 590         if (trusted) return false;
 591         if (invalid || untrusted) return true;
 592         try {
 593             if (!trustNameService && (defaultDeny ||
 594                 sun.net.www.URLConnection.isProxiedHost(hostname))) {
 595                 if (this.cname == null) {
 596                     this.getCanonName();
 597                 }
 598                 if (!match(cname, hostname)) {
 599                     // Last chance
 600                     if (!authorized(hostname, addresses[0].getAddress())) {
 601                         untrusted = true;
 602                         Debug debug = getDebug();
 603                         if (debug != null && Debug.isOn("failure")) {
 604                             debug.println("socket access restriction: proxied host " + "(" + addresses[0] + ")" + " does not match " + cname + " from reverse lookup");
 605                         }
 606                         return true;
 607                     }
 608                 }
 609                 trusted = true;
 610             }
 611         } catch (UnknownHostException uhe) {
 612             invalid = true;
 613             throw uhe;
 614         }
 615         return false;
 616     }
 617 
 618     /**
 619      * attempt to get the fully qualified domain name
 620      *
 621      */
 622     void getCanonName()
 623         throws UnknownHostException
 624     {
 625         if (cname != null || invalid || untrusted) return;
 626 
 627         // attempt to get the canonical name
 628 
 629         try {
 630             // first get the IP addresses if we don't have them yet
 631             // this is because we need the IP address to then get
 632             // FQDN.
 633             if (addresses == null) {
 634                 getIP();
 635             }
 636 
 637             // we have to do this check, otherwise we might not
 638             // get the fully qualified domain name
 639             if (init_with_ip) {
 640                 cname = addresses[0].getHostName(false).toLowerCase();
 641             } else {
 642              cname = InetAddress.getByName(addresses[0].getHostAddress()).
 643                                               getHostName(false).toLowerCase();
 644             }
 645         } catch (UnknownHostException uhe) {
 646             invalid = true;
 647             throw uhe;
 648         }
 649     }
 650 
 651     private transient String cdomain, hdomain;
 652 
 653     private boolean match(String cname, String hname) {
 654         String a = cname.toLowerCase();
 655         String b = hname.toLowerCase();
 656         if (a.startsWith(b)  &&
 657             ((a.length() == b.length()) || (a.charAt(b.length()) == '.')))
 658             return true;
 659         if (cdomain == null) {
 660             cdomain = RegisteredDomain.getRegisteredDomain(a);
 661         }
 662         if (hdomain == null) {
 663             hdomain = RegisteredDomain.getRegisteredDomain(b);
 664         }
 665 
 666         return cdomain.length() != 0 && hdomain.length() != 0
 667                         && cdomain.equals(hdomain);
 668     }
 669 
 670     private boolean authorized(String cname, byte[] addr) {
 671         if (addr.length == 4)
 672             return authorizedIPv4(cname, addr);
 673         else if (addr.length == 16)
 674             return authorizedIPv6(cname, addr);
 675         else
 676             return false;
 677     }
 678 
 679     private boolean authorizedIPv4(String cname, byte[] addr) {
 680         String authHost = "";
 681         InetAddress auth;
 682 
 683         try {
 684             authHost = "auth." +
 685                         (addr[3] & 0xff) + "." + (addr[2] & 0xff) + "." +
 686                         (addr[1] & 0xff) + "." + (addr[0] & 0xff) +
 687                         ".in-addr.arpa";
 688             // Following check seems unnecessary
 689             // auth = InetAddress.getAllByName0(authHost, false)[0];
 690             authHost = hostname + '.' + authHost;
 691             auth = InetAddress.getAllByName0(authHost, false)[0];
 692             if (auth.equals(InetAddress.getByAddress(addr))) {
 693                 return true;
 694             }
 695             Debug debug = getDebug();
 696             if (debug != null && Debug.isOn("failure")) {
 697                 debug.println("socket access restriction: IP address of " + auth + " != " + InetAddress.getByAddress(addr));
 698             }
 699         } catch (UnknownHostException uhe) {
 700             Debug debug = getDebug();
 701             if (debug != null && Debug.isOn("failure")) {
 702                 debug.println("socket access restriction: forward lookup failed for " + authHost);
 703             }
 704         }
 705         return false;
 706     }
 707 
 708     private boolean authorizedIPv6(String cname, byte[] addr) {
 709         String authHost = "";
 710         InetAddress auth;
 711 
 712         try {
 713             StringBuffer sb = new StringBuffer(39);
 714 
 715             for (int i = 15; i >= 0; i--) {
 716                 sb.append(Integer.toHexString(((addr[i]) & 0x0f)));
 717                 sb.append('.');
 718                 sb.append(Integer.toHexString(((addr[i] >> 4) & 0x0f)));
 719                 sb.append('.');
 720             }
 721             authHost = "auth." + sb.toString() + "IP6.ARPA";
 722             //auth = InetAddress.getAllByName0(authHost, false)[0];
 723             authHost = hostname + '.' + authHost;
 724             auth = InetAddress.getAllByName0(authHost, false)[0];
 725             if (auth.equals(InetAddress.getByAddress(addr)))
 726                 return true;
 727             Debug debug = getDebug();
 728             if (debug != null && Debug.isOn("failure")) {
 729                 debug.println("socket access restriction: IP address of " + auth + " != " + InetAddress.getByAddress(addr));
 730             }
 731         } catch (UnknownHostException uhe) {
 732             Debug debug = getDebug();
 733             if (debug != null && Debug.isOn("failure")) {
 734                 debug.println("socket access restriction: forward lookup failed for " + authHost);
 735             }
 736         }
 737         return false;
 738     }
 739 
 740 
 741     /**
 742      * get IP addresses. Sets invalid to true if we can't get them.
 743      *
 744      */
 745     void getIP()
 746         throws UnknownHostException
 747     {
 748         if (addresses != null || wildcard || invalid) return;
 749 
 750         try {
 751             // now get all the IP addresses
 752             String host;
 753             if (getName().charAt(0) == '[') {
 754                 // Literal IPv6 address
 755                 host = getName().substring(1, getName().indexOf(']'));
 756             } else {
 757                 int i = getName().indexOf(":");
 758                 if (i == -1)
 759                     host = getName();
 760                 else {
 761                     host = getName().substring(0,i);
 762                 }
 763             }
 764 
 765             addresses =
 766                 new InetAddress[] {InetAddress.getAllByName0(host, false)[0]};
 767 
 768         } catch (UnknownHostException uhe) {
 769             invalid = true;
 770             throw uhe;
 771         }  catch (IndexOutOfBoundsException iobe) {
 772             invalid = true;
 773             throw new UnknownHostException(getName());
 774         }
 775     }
 776 
 777     /**
 778      * Checks if this socket permission object "implies" the
 779      * specified permission.
 780      * <P>
 781      * More specifically, this method first ensures that all of the following
 782      * are true (and returns false if any of them are not):<p>
 783      * <ul>
 784      * <li> <i>p</i> is an instanceof SocketPermission,<p>
 785      * <li> <i>p</i>'s actions are a proper subset of this
 786      * object's actions, and<p>
 787      * <li> <i>p</i>'s port range is included in this port range. Note:
 788      * port range is ignored when p only contains the action, 'resolve'.<p>
 789      * </ul>
 790      *
 791      * Then <code>implies</code> checks each of the following, in order,
 792      * and for each returns true if the stated condition is true:<p>
 793      * <ul>
 794      * <li> If this object was initialized with a single IP address and one of <i>p</i>'s
 795      * IP addresses is equal to this object's IP address.<p>
 796      * <li>If this object is a wildcard domain (such as *.sun.com), and
 797      * <i>p</i>'s canonical name (the name without any preceding *)
 798      * ends with this object's canonical host name. For example, *.sun.com
 799      * implies *.eng.sun.com..<p>
 800      * <li>If this object was not initialized with a single IP address, and one of this
 801      * object's IP addresses equals one of <i>p</i>'s IP addresses.<p>
 802      * <li>If this canonical name equals <i>p</i>'s canonical name.<p>
 803      * </ul>
 804      *
 805      * If none of the above are true, <code>implies</code> returns false.
 806      * @param p the permission to check against.
 807      *
 808      * @return true if the specified permission is implied by this object,
 809      * false if not.
 810      */
 811     public boolean implies(Permission p) {
 812         int i,j;
 813 
 814         if (!(p instanceof SocketPermission))
 815             return false;
 816 
 817         if (p == this)
 818             return true;
 819 
 820         SocketPermission that = (SocketPermission) p;
 821 
 822         return ((this.mask & that.mask) == that.mask) &&
 823                                         impliesIgnoreMask(that);
 824     }
 825 
 826     /**
 827      * Checks if the incoming Permission's action are a proper subset of
 828      * the this object's actions.
 829      * <P>
 830      * Check, in the following order:
 831      * <ul>
 832      * <li> Checks that "p" is an instanceof a SocketPermission
 833      * <li> Checks that "p"'s actions are a proper subset of the
 834      * current object's actions.
 835      * <li> Checks that "p"'s port range is included in this port range
 836      * <li> If this object was initialized with an IP address, checks that
 837      *      one of "p"'s IP addresses is equal to this object's IP address.
 838      * <li> If either object is a wildcard domain (i.e., "*.sun.com"),
 839      *      attempt to match based on the wildcard.
 840      * <li> If this object was not initialized with an IP address, attempt
 841      *      to find a match based on the IP addresses in both objects.
 842      * <li> Attempt to match on the canonical hostnames of both objects.
 843      * </ul>
 844      * @param that the incoming permission request
 845      *
 846      * @return true if "permission" is a proper subset of the current object,
 847      * false if not.
 848      */
 849     boolean impliesIgnoreMask(SocketPermission that) {
 850         int i,j;
 851 
 852         if ((that.mask & RESOLVE) != that.mask) {
 853             // check port range
 854             if ((that.portrange[0] < this.portrange[0]) ||
 855                     (that.portrange[1] > this.portrange[1])) {
 856                     return false;
 857             }
 858         }
 859 
 860         // allow a "*" wildcard to always match anything
 861         if (this.wildcard && "".equals(this.cname))
 862             return true;
 863 
 864         // return if either one of these NetPerm objects are invalid...
 865         if (this.invalid || that.invalid) {
 866             return compareHostnames(that);
 867         }
 868 
 869         try {
 870             if (this.init_with_ip) { // we only check IP addresses
 871                 if (that.wildcard)
 872                     return false;
 873 
 874                 if (that.init_with_ip) {
 875                     return (this.addresses[0].equals(that.addresses[0]));
 876                 } else {
 877                     if (that.addresses == null) {
 878                         that.getIP();
 879                     }
 880                     for (i=0; i < that.addresses.length; i++) {
 881                         if (this.addresses[0].equals(that.addresses[i]))
 882                             return true;
 883                     }
 884                 }
 885                 // since "this" was initialized with an IP address, we
 886                 // don't check any other cases
 887                 return false;
 888             }
 889 
 890             // check and see if we have any wildcards...
 891             if (this.wildcard || that.wildcard) {
 892                 // if they are both wildcards, return true iff
 893                 // that's cname ends with this cname (i.e., *.sun.com
 894                 // implies *.eng.sun.com)
 895                 if (this.wildcard && that.wildcard)
 896                     return (that.cname.endsWith(this.cname));
 897 
 898                 // a non-wildcard can't imply a wildcard
 899                 if (that.wildcard)
 900                     return false;
 901 
 902                 // this is a wildcard, lets see if that's cname ends with
 903                 // it...
 904                 if (that.cname == null) {
 905                     that.getCanonName();
 906                 }
 907                 return (that.cname.endsWith(this.cname));
 908             }
 909 
 910             // comapare IP addresses
 911             if (this.addresses == null) {
 912                 this.getIP();
 913             }
 914 
 915             if (that.addresses == null) {
 916                 that.getIP();
 917             }
 918 
 919             if (!(that.init_with_ip && this.isUntrusted())) {
 920                 for (j = 0; j < this.addresses.length; j++) {
 921                     for (i=0; i < that.addresses.length; i++) {
 922                         if (this.addresses[j].equals(that.addresses[i]))
 923                             return true;
 924                     }
 925                 }
 926 
 927                 // XXX: if all else fails, compare hostnames?
 928                 // Do we really want this?
 929                 if (this.cname == null) {
 930                     this.getCanonName();
 931                 }
 932 
 933                 if (that.cname == null) {
 934                     that.getCanonName();
 935                 }
 936 
 937                 return (this.cname.equalsIgnoreCase(that.cname));
 938             }
 939 
 940         } catch (UnknownHostException uhe) {
 941             return compareHostnames(that);
 942         }
 943 
 944         // make sure the first thing that is done here is to return
 945         // false. If not, uncomment the return false in the above catch.
 946 
 947         return false;
 948     }
 949 
 950     private boolean compareHostnames(SocketPermission that) {
 951         // we see if the original names/IPs passed in were equal.
 952 
 953         String thisHost = hostname;
 954         String thatHost = that.hostname;
 955 
 956         if (thisHost == null) {
 957             return false;
 958         } else if (this.wildcard) {
 959             final int cnameLength = this.cname.length();
 960             return thatHost.regionMatches(true,
 961                                           (thatHost.length() - cnameLength),
 962                                           this.cname, 0, cnameLength);
 963         } else {
 964             return thisHost.equalsIgnoreCase(thatHost);
 965         }
 966     }
 967 
 968     /**
 969      * Checks two SocketPermission objects for equality.
 970      * <P>
 971      * @param obj the object to test for equality with this object.
 972      *
 973      * @return true if <i>obj</i> is a SocketPermission, and has the
 974      *  same hostname, port range, and actions as this
 975      *  SocketPermission object. However, port range will be ignored
 976      *  in the comparison if <i>obj</i> only contains the action, 'resolve'.
 977      */
 978     public boolean equals(Object obj) {
 979         if (obj == this)
 980             return true;
 981 
 982         if (! (obj instanceof SocketPermission))
 983             return false;
 984 
 985         SocketPermission that = (SocketPermission) obj;
 986 
 987         //this is (overly?) complex!!!
 988 
 989         // check the mask first
 990         if (this.mask != that.mask) return false;
 991 
 992         if ((that.mask & RESOLVE) != that.mask) {
 993             // now check the port range...
 994             if ((this.portrange[0] != that.portrange[0]) ||
 995                 (this.portrange[1] != that.portrange[1])) {
 996                 return false;
 997             }
 998         }
 999 
1000         // short cut. This catches:
1001         //  "crypto" equal to "crypto", or
1002         // "1.2.3.4" equal to "1.2.3.4.", or
1003         //  "*.edu" equal to "*.edu", but it
1004         //  does not catch "crypto" equal to
1005         // "crypto.eng.sun.com".
1006 
1007         if (this.getName().equalsIgnoreCase(that.getName())) {
1008             return true;
1009         }
1010 
1011         // we now attempt to get the Canonical (FQDN) name and
1012         // compare that. If this fails, about all we can do is return
1013         // false.
1014 
1015         try {
1016             this.getCanonName();
1017             that.getCanonName();
1018         } catch (UnknownHostException uhe) {
1019             return false;
1020         }
1021 
1022         if (this.invalid || that.invalid)
1023             return false;
1024 
1025         if (this.cname != null) {
1026             return this.cname.equalsIgnoreCase(that.cname);
1027         }
1028 
1029         return false;
1030     }
1031 
1032     /**
1033      * Returns the hash code value for this object.
1034      *
1035      * @return a hash code value for this object.
1036      */
1037 
1038     public int hashCode() {
1039         /*
1040          * If this SocketPermission was initialized with an IP address
1041          * or a wildcard, use getName().hashCode(), otherwise use
1042          * the hashCode() of the host name returned from
1043          * java.net.InetAddress.getHostName method.
1044          */
1045 
1046         if (init_with_ip || wildcard) {
1047             return this.getName().hashCode();
1048         }
1049 
1050         try {
1051             getCanonName();
1052         } catch (UnknownHostException uhe) {
1053 
1054         }
1055 
1056         if (invalid || cname == null)
1057             return this.getName().hashCode();
1058         else
1059             return this.cname.hashCode();
1060     }
1061 
1062     /**
1063      * Return the current action mask.
1064      *
1065      * @return the actions mask.
1066      */
1067 
1068     int getMask() {
1069         return mask;
1070     }
1071 
1072     /**
1073      * Returns the "canonical string representation" of the actions in the
1074      * specified mask.
1075      * Always returns present actions in the following order:
1076      * connect, listen, accept, resolve.
1077      *
1078      * @param mask a specific integer action mask to translate into a string
1079      * @return the canonical string representation of the actions
1080      */
1081     private static String getActions(int mask)
1082     {
1083         StringBuilder sb = new StringBuilder();
1084         boolean comma = false;
1085 
1086         if ((mask & CONNECT) == CONNECT) {
1087             comma = true;
1088             sb.append("connect");
1089         }
1090 
1091         if ((mask & LISTEN) == LISTEN) {
1092             if (comma) sb.append(',');
1093             else comma = true;
1094             sb.append("listen");
1095         }
1096 
1097         if ((mask & ACCEPT) == ACCEPT) {
1098             if (comma) sb.append(',');
1099             else comma = true;
1100             sb.append("accept");
1101         }
1102 
1103 
1104         if ((mask & RESOLVE) == RESOLVE) {
1105             if (comma) sb.append(',');
1106             else comma = true;
1107             sb.append("resolve");
1108         }
1109 
1110         return sb.toString();
1111     }
1112 
1113     /**
1114      * Returns the canonical string representation of the actions.
1115      * Always returns present actions in the following order:
1116      * connect, listen, accept, resolve.
1117      *
1118      * @return the canonical string representation of the actions.
1119      */
1120     public String getActions()
1121     {
1122         if (actions == null)
1123             actions = getActions(this.mask);
1124 
1125         return actions;
1126     }
1127 
1128     /**
1129      * Returns a new PermissionCollection object for storing SocketPermission
1130      * objects.
1131      * <p>
1132      * SocketPermission objects must be stored in a manner that allows them
1133      * to be inserted into the collection in any order, but that also enables the
1134      * PermissionCollection <code>implies</code>
1135      * method to be implemented in an efficient (and consistent) manner.
1136      *
1137      * @return a new PermissionCollection object suitable for storing SocketPermissions.
1138      */
1139 
1140     public PermissionCollection newPermissionCollection() {
1141         return new SocketPermissionCollection();
1142     }
1143 
1144     /**
1145      * WriteObject is called to save the state of the SocketPermission
1146      * to a stream. The actions are serialized, and the superclass
1147      * takes care of the name.
1148      */
1149     private synchronized void writeObject(java.io.ObjectOutputStream s)
1150         throws IOException
1151     {
1152         // Write out the actions. The superclass takes care of the name
1153         // call getActions to make sure actions field is initialized
1154         if (actions == null)
1155             getActions();
1156         s.defaultWriteObject();
1157     }
1158 
1159     /**
1160      * readObject is called to restore the state of the SocketPermission from
1161      * a stream.
1162      */
1163     private synchronized void readObject(java.io.ObjectInputStream s)
1164          throws IOException, ClassNotFoundException
1165     {
1166         // Read in the action, then initialize the rest
1167         s.defaultReadObject();
1168         init(getName(),getMask(actions));
1169     }
1170 
1171     /*
1172     public String toString()
1173     {
1174         StringBuffer s = new StringBuffer(super.toString() + "\n" +
1175             "cname = " + cname + "\n" +
1176             "wildcard = " + wildcard + "\n" +
1177             "invalid = " + invalid + "\n" +
1178             "portrange = " + portrange[0] + "," + portrange[1] + "\n");
1179         if (addresses != null) for (int i=0; i<addresses.length; i++) {
1180             s.append( addresses[i].getHostAddress());
1181             s.append("\n");
1182         } else {
1183             s.append("(no addresses)\n");
1184         }
1185 
1186         return s.toString();
1187     }
1188 
1189     public static void main(String args[]) throws Exception {
1190         SocketPermission this_ = new SocketPermission(args[0], "connect");
1191         SocketPermission that_ = new SocketPermission(args[1], "connect");
1192         System.out.println("-----\n");
1193         System.out.println("this.implies(that) = " + this_.implies(that_));
1194         System.out.println("-----\n");
1195         System.out.println("this = "+this_);
1196         System.out.println("-----\n");
1197         System.out.println("that = "+that_);
1198         System.out.println("-----\n");
1199 
1200         SocketPermissionCollection nps = new SocketPermissionCollection();
1201         nps.add(this_);
1202         nps.add(new SocketPermission("www-leland.stanford.edu","connect"));
1203         nps.add(new SocketPermission("www-sun.com","connect"));
1204         System.out.println("nps.implies(that) = " + nps.implies(that_));
1205         System.out.println("-----\n");
1206     }
1207     */
1208 }
1209 
1210 /**
1211 
1212 if (init'd with IP, key is IP as string)
1213 if wildcard, its the wild card
1214 else its the cname?
1215 
1216  *
1217  * @see java.security.Permission
1218  * @see java.security.Permissions
1219  * @see java.security.PermissionCollection
1220  *
1221  *
1222  * @author Roland Schemers
1223  *
1224  * @serial include
1225  */
1226 
1227 final class SocketPermissionCollection extends PermissionCollection
1228     implements Serializable
1229 {
1230     // Not serialized; see serialization section at end of class
1231     private transient List<SocketPermission> perms;
1232 
1233     /**
1234      * Create an empty SocketPermissions object.
1235      *
1236      */
1237 
1238     public SocketPermissionCollection() {
1239         perms = new ArrayList<SocketPermission>();
1240     }
1241 
1242     /**
1243      * Adds a permission to the SocketPermissions. The key for the hash is
1244      * the name in the case of wildcards, or all the IP addresses.
1245      *
1246      * @param permission the Permission object to add.
1247      *
1248      * @exception IllegalArgumentException - if the permission is not a
1249      *                                       SocketPermission
1250      *
1251      * @exception SecurityException - if this SocketPermissionCollection object
1252      *                                has been marked readonly
1253      */
1254     public void add(Permission permission) {
1255         if (! (permission instanceof SocketPermission))
1256             throw new IllegalArgumentException("invalid permission: "+
1257                                                permission);
1258         if (isReadOnly())
1259             throw new SecurityException(
1260                 "attempt to add a Permission to a readonly PermissionCollection");
1261 
1262         // optimization to ensure perms most likely to be tested
1263         // show up early (4301064)
1264         synchronized (this) {
1265             perms.add(0, (SocketPermission)permission);
1266         }
1267     }
1268 
1269     /**
1270      * Check and see if this collection of permissions implies the permissions
1271      * expressed in "permission".
1272      *
1273      * @param permission the Permission object to compare
1274      *
1275      * @return true if "permission" is a proper subset of a permission in
1276      * the collection, false if not.
1277      */
1278 
1279     public boolean implies(Permission permission)
1280     {
1281         if (! (permission instanceof SocketPermission))
1282                 return false;
1283 
1284         SocketPermission np = (SocketPermission) permission;
1285 
1286         int desired = np.getMask();
1287         int effective = 0;
1288         int needed = desired;
1289 
1290         synchronized (this) {
1291             int len = perms.size();
1292             //System.out.println("implies "+np);
1293             for (int i = 0; i < len; i++) {
1294                 SocketPermission x = perms.get(i);
1295                 //System.out.println("  trying "+x);
1296                 if (((needed & x.getMask()) != 0) && x.impliesIgnoreMask(np)) {
1297                     effective |=  x.getMask();
1298                     if ((effective & desired) == desired)
1299                         return true;
1300                     needed = (desired ^ effective);
1301                 }
1302             }
1303         }
1304         return false;
1305     }
1306 
1307     /**
1308      * Returns an enumeration of all the SocketPermission objects in the
1309      * container.
1310      *
1311      * @return an enumeration of all the SocketPermission objects.
1312      */
1313 
1314     @SuppressWarnings("unchecked")
1315     public Enumeration<Permission> elements() {
1316         // Convert Iterator into Enumeration
1317         synchronized (this) {
1318             return Collections.enumeration((List<Permission>)(List)perms);
1319         }
1320     }
1321 
1322     private static final long serialVersionUID = 2787186408602843674L;
1323 
1324     // Need to maintain serialization interoperability with earlier releases,
1325     // which had the serializable field:
1326 
1327     //
1328     // The SocketPermissions for this set.
1329     // @serial
1330     //
1331     // private Vector permissions;
1332 
1333     /**
1334      * @serialField permissions java.util.Vector
1335      *     A list of the SocketPermissions for this set.
1336      */
1337     private static final ObjectStreamField[] serialPersistentFields = {
1338         new ObjectStreamField("permissions", Vector.class),
1339     };
1340 
1341     /**
1342      * @serialData "permissions" field (a Vector containing the SocketPermissions).
1343      */
1344     /*
1345      * Writes the contents of the perms field out as a Vector for
1346      * serialization compatibility with earlier releases.
1347      */
1348     private void writeObject(ObjectOutputStream out) throws IOException {
1349         // Don't call out.defaultWriteObject()
1350 
1351         // Write out Vector
1352         Vector<SocketPermission> permissions = new Vector<>(perms.size());
1353 
1354         synchronized (this) {
1355             permissions.addAll(perms);
1356         }
1357 
1358         ObjectOutputStream.PutField pfields = out.putFields();
1359         pfields.put("permissions", permissions);
1360         out.writeFields();
1361     }
1362 
1363     /*
1364      * Reads in a Vector of SocketPermissions and saves them in the perms field.
1365      */
1366     private void readObject(ObjectInputStream in)
1367         throws IOException, ClassNotFoundException
1368     {
1369         // Don't call in.defaultReadObject()
1370 
1371         // Read in serialized fields
1372         ObjectInputStream.GetField gfields = in.readFields();
1373 
1374         // Get the one we want
1375         @SuppressWarnings("unchecked")
1376         Vector<SocketPermission> permissions = (Vector<SocketPermission>)gfields.get("permissions", null);
1377         perms = new ArrayList<SocketPermission>(permissions.size());
1378         perms.addAll(permissions);
1379     }
1380 }