1 /*
   2  * Copyright (c) 2013, 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.io.ObjectInputStream;
  29 import java.io.IOException;
  30 import java.util.List;
  31 import java.util.ArrayList;
  32 import java.util.Collections;
  33 import java.security.Permission;
  34 
  35 /**
  36  * Represents permission to access a resource or set of resources defined by a
  37  * given url, and for a given set of user-settable request methods
  38  * and request headers. The <i>name</i> of the permission is the url string.
  39  * The <i>actions</i> string is a concatenation of the request methods and headers.
  40  * The range of method and header names is not restricted by this class.
  41  * <p><b>The url</b><p>
  42  * The url string has the following expected structure.
  43  * <pre>
  44  *     scheme : // authority [ / path ]
  45  * </pre>
  46  * <i>scheme</i> will typically be http or https, but is not restricted by this
  47  * class.
  48  * <i>authority</i> is specified as:
  49  * <pre>
  50  *     authority = [ userinfo @ ] hostrange [ : portrange ]
  51  *     portrange = portnumber | -portnumber | portnumber-[portnumber] | *
  52  *     hostrange = ([*.] dnsname) | IPv4address | IPv6address
  53  * </pre>
  54  * <i>dnsname</i> is a standard DNS host or domain name, ie. one or more labels
  55  * separated by ".". <i>IPv4address</i> is a standard literal IPv4 address and
  56  * <i>IPv6address</i> is as defined in <a href="http://www.ietf.org/rfc/rfc2732.txt">
  57  * RFC 2732</a>. Literal IPv6 addresses must however, be enclosed in '[]' characters.
  58  * The <i>dnsname</i> specification can be preceded by "*." which means
  59  * the name will match any hostname whose right-most domain labels are the same as
  60  * this name. For example, "*.oracle.com" matches "foo.bar.oracle.com"
  61  * <p>
  62  * <i>portrange</i> is used to specify a port number, or a bounded or unbounded range of ports
  63  * that this permission applies to. If portrange is absent or invalid, then a default
  64  * port number is assumed if the scheme is {@code http} (default 80) or {@code https}
  65  * (default 443). No default is assumed for other schemes. A wildcard may be specified
  66  * which means all ports.
  67  * <p>
  68  * <i>userinfo</i> is optional. A userinfo component if present, is ignored when
  69  * creating a URLPermission, and has no effect on any other methods defined by this class.
  70  * <p>
  71  * The <i>path</i> component comprises a sequence of path segments,
  72  * separated by '/' characters. <i>path</i> may also be empty. The path is specified
  73  * in a similar way to the path in {@link java.io.FilePermission}. There are
  74  * three different ways as the following examples show:
  75  * <table border summary="URL examples">
  76  * <caption>URL Examples</caption>
  77  * <tr><th>Example url</th><th>Description</th></tr>
  78  * <tr><td style="white-space:nowrap;">http://www.oracle.com/a/b/c.html</td>
  79  *   <td>A url which identifies a specific (single) resource</td>
  80  * </tr>
  81  * <tr><td>http://www.oracle.com/a/b/*</td>
  82  *   <td>The '*' character refers to all resources in the same "directory" - in
  83  *       other words all resources with the same number of path components, and
  84  *       which only differ in the final path component, represented by the '*'.
  85  *   </td>
  86  * </tr>
  87  * <tr><td>http://www.oracle.com/a/b/-</td>
  88  *   <td>The '-' character refers to all resources recursively below the
  89  *       preceding path (eg. http://www.oracle.com/a/b/c/d/e.html matches this
  90  *       example).
  91  *   </td>
  92  * </tr>
  93  * </table>
  94  * <p>
  95  * The '*' and '-' may only be specified in the final segment of a path and must be
  96  * the only character in that segment. Any query or fragment components of the
  97  * url are ignored when constructing URLPermissions.
  98  * <p>
  99  * As a special case, urls of the form, "scheme:*" are accepted to
 100  * mean any url of the given scheme.
 101  * <p>
 102  * The <i>scheme</i> and <i>authority</i> components of the url string are handled
 103  * without regard to case. This means {@link #equals(Object)},
 104  * {@link #hashCode()} and {@link #implies(Permission)} are case insensitive with respect
 105  * to these components. If the <i>authority</i> contains a literal IP address,
 106  * then the address is normalized for comparison. The path component is case sensitive.
 107  * <p><b>The actions string</b><p>
 108  * The actions string of a URLPermission is a concatenation of the <i>method list</i>
 109  * and the <i>request headers list</i>. These are lists of the permitted request
 110  * methods and permitted request headers of the permission (respectively). The two lists
 111  * are separated by a colon ':' character and elements of each list are comma separated.
 112  * Some examples are:
 113  * <pre>
 114  *         "POST,GET,DELETE"
 115  *         "GET:X-Foo-Request,X-Bar-Request"
 116  *         "POST,GET:Header1,Header2"
 117  * </pre>
 118  * The first example specifies the methods: POST, GET and DELETE, but no request headers.
 119  * The second example specifies one request method and two headers. The third
 120  * example specifies two request methods, and two headers.
 121  * <p>
 122  * The colon separator need not be present if the request headers list is empty.
 123  * No white-space is permitted in the actions string. The action strings supplied to
 124  * the URLPermission constructors are case-insensitive and are normalized by converting
 125  * method names to upper-case and header names to the form defines in RFC2616 (lower case
 126  * with initial letter of each word capitalized). Either list can contain a wild-card '*'
 127  * character which signifies all request methods or headers respectively.
 128  * <p>
 129  * Note. Depending on the context of use, some request methods and headers may be permitted
 130  * at all times, and others may not be permitted at any time. For example, the
 131  * HTTP protocol handler might disallow certain headers such as Content-Length
 132  * from being set by application code, regardless of whether the security policy
 133  * in force, permits it.
 134  *
 135  * @since 1.8
 136  */
 137 public final class URLPermission extends Permission {
 138 
 139     private static final long serialVersionUID = -2702463814894478682L;
 140 
 141     private transient String scheme;
 142     private transient String ssp;                 // scheme specific part
 143     private transient String path;
 144     private transient List<String> methods;
 145     private transient List<String> requestHeaders;
 146     private transient Authority authority;
 147 
 148     // serialized field
 149     private String actions;
 150 
 151     /**
 152      * Creates a new URLPermission from a url string and which permits the given
 153      * request methods and user-settable request headers.
 154      * The name of the permission is the url string it was created with. Only the scheme,
 155      * authority and path components of the url are used internally. Any fragment or query
 156      * components are ignored. The permissions action string is as specified above.
 157      *
 158      * @param url the url string
 159      *
 160      * @param actions the actions string
 161      *
 162      * @exception IllegalArgumentException if url is invalid or if actions contains white-space.
 163      */
 164     public URLPermission(String url, String actions) {
 165         super(url);
 166         init(actions);
 167     }
 168 
 169     private void init(String actions) {
 170         parseURI(getName());
 171         int colon = actions.indexOf(':');
 172         if (actions.lastIndexOf(':') != colon) {
 173             throw new IllegalArgumentException("invalid actions string");
 174         }
 175 
 176         String methods, headers;
 177         if (colon == -1) {
 178             methods = actions;
 179             headers = "";
 180         } else {
 181             methods = actions.substring(0, colon);
 182             headers = actions.substring(colon+1);
 183         }
 184 
 185         List<String> l = normalizeMethods(methods);
 186         Collections.sort(l);
 187         this.methods = Collections.unmodifiableList(l);
 188 
 189         l = normalizeHeaders(headers);
 190         Collections.sort(l);
 191         this.requestHeaders = Collections.unmodifiableList(l);
 192 
 193         this.actions = actions();
 194     }
 195 
 196     /**
 197      * Creates a URLPermission with the given url string and unrestricted
 198      * methods and request headers by invoking the two argument
 199      * constructor as follows: URLPermission(url, "*:*")
 200      *
 201      * @param url the url string
 202      *
 203      * @throws    IllegalArgumentException if url does not result in a valid {@link URI}
 204      */
 205     public URLPermission(String url) {
 206         this(url, "*:*");
 207     }
 208 
 209     /**
 210      * Returns the normalized method list and request
 211      * header list, in the form:
 212      * <pre>
 213      *      "method-names : header-names"
 214      * </pre>
 215      * <p>
 216      * where method-names is the list of methods separated by commas
 217      * and header-names is the list of permitted headers separated by commas.
 218      * There is no white space in the returned String. If header-names is empty
 219      * then the colon separator will not be present.
 220      */
 221     public String getActions() {
 222         return actions;
 223     }
 224 
 225     /**
 226      * Checks if this URLPermission implies the given permission.
 227      * Specifically, the following checks are done as if in the
 228      * following sequence:
 229      * <ul>
 230      * <li>if 'p' is not an instance of URLPermission return false</li>
 231      * <li>if any of p's methods are not in this's method list, and if
 232      *     this's method list is not equal to "*", then return false.</li>
 233      * <li>if any of p's headers are not in this's request header list, and if
 234      *     this's request header list is not equal to "*", then return false.</li>
 235      * <li>if this's url scheme is not equal to p's url scheme return false</li>
 236      * <li>if the scheme specific part of this's url is '*' return true</li>
 237      * <li>if the set of hosts defined by p's url hostrange is not a subset of
 238      *     this's url hostrange then return false. For example, "*.foo.oracle.com"
 239      *     is a subset of "*.oracle.com". "foo.bar.oracle.com" is not
 240      *     a subset of "*.foo.oracle.com"</li>
 241      * <li>if the portrange defined by p's url is not a subset of the
 242      *     portrange defined by this's url then return false.
 243      * <li>if the path or paths specified by p's url are contained in the
 244      *     set of paths specified by this's url, then return true
 245      * <li>otherwise, return false</li>
 246      * </ul>
 247      * <p>Some examples of how paths are matched are shown below:
 248      * <table border summary="Path Matching examples">
 249      * <caption>Examples of Path Matching</caption>
 250      * <tr><th>this's path</th><th>p's path</th><th>match</th></tr>
 251      * <tr><td>/a/b</td><td>/a/b</td><td>yes</td></tr>
 252      * <tr><td>/a/b/*</td><td>/a/b/c</td><td>yes</td></tr>
 253      * <tr><td>/a/b/*</td><td>/a/b/c/d</td><td>no</td></tr>
 254      * <tr><td>/a/b/-</td><td>/a/b/c/d</td><td>yes</td></tr>
 255      * <tr><td>/a/b/-</td><td>/a/b/c/d/e</td><td>yes</td></tr>
 256      * <tr><td>/a/b/-</td><td>/a/b/c/*</td><td>yes</td></tr>
 257      * <tr><td>/a/b/*</td><td>/a/b/c/-</td><td>no</td></tr>
 258      * </table>
 259      */
 260     public boolean implies(Permission p) {
 261         if (! (p instanceof URLPermission)) {
 262             return false;
 263         }
 264 
 265         URLPermission that = (URLPermission)p;
 266 
 267         if (!this.methods.get(0).equals("*") &&
 268                 Collections.indexOfSubList(this.methods, that.methods) == -1) {
 269             return false;
 270         }
 271 
 272         if (this.requestHeaders.isEmpty() && !that.requestHeaders.isEmpty()) {
 273             return false;
 274         }
 275 
 276         if (!this.requestHeaders.isEmpty() &&
 277             !this.requestHeaders.get(0).equals("*") &&
 278              Collections.indexOfSubList(this.requestHeaders,
 279                                         that.requestHeaders) == -1) {
 280             return false;
 281         }
 282 
 283         if (!this.scheme.equals(that.scheme)) {
 284             return false;
 285         }
 286 
 287         if (this.ssp.equals("*")) {
 288             return true;
 289         }
 290 
 291         if (!this.authority.implies(that.authority)) {
 292             return false;
 293         }
 294 
 295         if (this.path == null) {
 296             return that.path == null;
 297         }
 298         if (that.path == null) {
 299             return false;
 300         }
 301 
 302         if (this.path.endsWith("/-")) {
 303             String thisprefix = this.path.substring(0, this.path.length() - 1);
 304             return that.path.startsWith(thisprefix);
 305             }
 306 
 307         if (this.path.endsWith("/*")) {
 308             String thisprefix = this.path.substring(0, this.path.length() - 1);
 309             if (!that.path.startsWith(thisprefix)) {
 310                 return false;
 311             }
 312             String thatsuffix = that.path.substring(thisprefix.length());
 313             // suffix must not contain '/' chars
 314             if (thatsuffix.indexOf('/') != -1) {
 315                 return false;
 316             }
 317             if (thatsuffix.equals("-")) {
 318                 return false;
 319             }
 320             return true;
 321         }
 322         return this.path.equals(that.path);
 323     }
 324 
 325 
 326     /**
 327      * Returns true if, this.getActions().equals(p.getActions())
 328      * and p's url equals this's url.  Returns false otherwise.
 329      */
 330     public boolean equals(Object p) {
 331         if (!(p instanceof URLPermission)) {
 332             return false;
 333         }
 334         URLPermission that = (URLPermission)p;
 335         if (!this.scheme.equals(that.scheme)) {
 336             return false;
 337         }
 338         if (!this.getActions().equals(that.getActions())) {
 339             return false;
 340         }
 341         if (!this.authority.equals(that.authority)) {
 342             return false;
 343         }
 344         if (this.path != null) {
 345             return this.path.equals(that.path);
 346         } else {
 347             return that.path == null;
 348         }
 349     }
 350 
 351     /**
 352      * Returns a hashcode calculated from the hashcode of the
 353      * actions String and the url string.
 354      */
 355     public int hashCode() {
 356         return getActions().hashCode()
 357             + scheme.hashCode()
 358             + authority.hashCode()
 359             + (path == null ? 0 : path.hashCode());
 360     }
 361 
 362 
 363     private List<String> normalizeMethods(String methods) {
 364         List<String> l = new ArrayList<>();
 365         StringBuilder b = new StringBuilder();
 366         for (int i=0; i<methods.length(); i++) {
 367             char c = methods.charAt(i);
 368             if (c == ',') {
 369                 String s = b.toString();
 370                 if (s.length() > 0)
 371                     l.add(s);
 372                 b = new StringBuilder();
 373             } else if (c == ' ' || c == '\t') {
 374                 throw new IllegalArgumentException("white space not allowed");
 375             } else {
 376                 if (c >= 'a' && c <= 'z') {
 377                     c += 'A' - 'a';
 378                 }
 379                 b.append(c);
 380             }
 381         }
 382         String s = b.toString();
 383         if (s.length() > 0)
 384             l.add(s);
 385         return l;
 386     }
 387 
 388     private List<String> normalizeHeaders(String headers) {
 389         List<String> l = new ArrayList<>();
 390         StringBuilder b = new StringBuilder();
 391         boolean capitalizeNext = true;
 392         for (int i=0; i<headers.length(); i++) {
 393             char c = headers.charAt(i);
 394             if (c >= 'a' && c <= 'z') {
 395                 if (capitalizeNext) {
 396                     c += 'A' - 'a';
 397                     capitalizeNext = false;
 398                 }
 399                 b.append(c);
 400             } else if (c == ' ' || c == '\t') {
 401                 throw new IllegalArgumentException("white space not allowed");
 402             } else if (c == '-') {
 403                     capitalizeNext = true;
 404                 b.append(c);
 405             } else if (c == ',') {
 406                 String s = b.toString();
 407                 if (s.length() > 0)
 408                     l.add(s);
 409                 b = new StringBuilder();
 410                 capitalizeNext = true;
 411             } else {
 412                 capitalizeNext = false;
 413                 b.append(c);
 414             }
 415         }
 416         String s = b.toString();
 417         if (s.length() > 0)
 418             l.add(s);
 419         return l;
 420     }
 421 
 422     private void parseURI(String url) {
 423         int len = url.length();
 424         int delim = url.indexOf(':');
 425         if (delim == -1 || delim + 1 == len) {
 426             throw new IllegalArgumentException("invalid URL string");
 427         }
 428         scheme = url.substring(0, delim).toLowerCase();
 429         this.ssp = url.substring(delim + 1);
 430 
 431         if (!ssp.startsWith("//")) {
 432             if (!ssp.equals("*")) {
 433                 throw new IllegalArgumentException("invalid URL string");
 434             }
 435             this.authority = new Authority(scheme, "*");
 436             return;
 437         }
 438         String authpath = ssp.substring(2);
 439 
 440         delim = authpath.indexOf('/');
 441         String auth;
 442         if (delim == -1) {
 443             this.path = "";
 444             auth = authpath;
 445         } else {
 446             auth = authpath.substring(0, delim);
 447             this.path = authpath.substring(delim);
 448         }
 449         this.authority = new Authority(scheme, auth.toLowerCase());
 450     }
 451 
 452     private String actions() {
 453         StringBuilder b = new StringBuilder();
 454         for (String s : methods) {
 455             b.append(s);
 456         }
 457         b.append(":");
 458         for (String s : requestHeaders) {
 459             b.append(s);
 460         }
 461         return b.toString();
 462     }
 463 
 464     /**
 465      * restore the state of this object from stream
 466      */
 467     private void readObject(ObjectInputStream s)
 468         throws IOException, ClassNotFoundException {
 469         ObjectInputStream.GetField fields = s.readFields();
 470         String actions = (String)fields.get("actions", null);
 471 
 472         init(actions);
 473     }
 474 
 475     static class Authority {
 476         HostPortrange p;
 477 
 478         Authority(String scheme, String authority) {
 479             int at = authority.indexOf('@');
 480             if (at == -1) {
 481                     p = new HostPortrange(scheme, authority);
 482             } else {
 483                     p = new HostPortrange(scheme, authority.substring(at+1));
 484             }
 485         }
 486 
 487         boolean implies(Authority other) {
 488             return impliesHostrange(other) && impliesPortrange(other);
 489         }
 490 
 491         private boolean impliesHostrange(Authority that) {
 492             String thishost = this.p.hostname();
 493             String thathost = that.p.hostname();
 494 
 495             if (p.wildcard() && thishost.equals("")) {
 496                 // this "*" implies all others
 497                 return true;
 498             }
 499             if (that.p.wildcard() && thathost.equals("")) {
 500                 // that "*" can only be implied by this "*"
 501                 return false;
 502             }
 503             if (thishost.equals(thathost)) {
 504                 // covers all cases of literal IP addresses and fixed
 505                 // domain names.
 506                 return true;
 507             }
 508             if (this.p.wildcard()) {
 509                 // this "*.foo.com" implies "bub.bar.foo.com"
 510                 return thathost.endsWith(thishost);
 511             }
 512             return false;
 513         }
 514 
 515         private boolean impliesPortrange(Authority that) {
 516             int[] thisrange = this.p.portrange();
 517             int[] thatrange = that.p.portrange();
 518             if (thisrange[0] == -1) {
 519                 /* port not specified non http/s URL */
 520                 return true;
 521             }
 522             return thisrange[0] <= thatrange[0] &&
 523                         thisrange[1] >= thatrange[1];
 524         }
 525 
 526         boolean equals(Authority that) {
 527             return this.p.equals(that.p);
 528         }
 529 
 530         public int hashCode() {
 531             return p.hashCode();
 532         }
 533     }
 534 }