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>
  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(
 174                 "Invalid actions string: \"" + actions + "\"");
 175         }
 176 
 177         String methods, headers;
 178         if (colon == -1) {
 179             methods = actions;
 180             headers = "";
 181         } else {
 182             methods = actions.substring(0, colon);
 183             headers = actions.substring(colon+1);
 184         }
 185 
 186         List<String> l = normalizeMethods(methods);
 187         Collections.sort(l);
 188         this.methods = Collections.unmodifiableList(l);
 189 
 190         l = normalizeHeaders(headers);
 191         Collections.sort(l);
 192         this.requestHeaders = Collections.unmodifiableList(l);
 193 
 194         this.actions = actions();
 195     }
 196 
 197     /**
 198      * Creates a URLPermission with the given url string and unrestricted
 199      * methods and request headers by invoking the two argument
 200      * constructor as follows: URLPermission(url, "*:*")
 201      *
 202      * @param url the url string
 203      *
 204      * @throws    IllegalArgumentException if url does not result in a valid {@link URI}
 205      */
 206     public URLPermission(String url) {
 207         this(url, "*:*");
 208     }
 209 
 210     /**
 211      * Returns the normalized method list and request
 212      * header list, in the form:
 213      * <pre>
 214      *      "method-names : header-names"
 215      * </pre>
 216      * <p>
 217      * where method-names is the list of methods separated by commas
 218      * and header-names is the list of permitted headers separated by commas.
 219      * There is no white space in the returned String. If header-names is empty
 220      * then the colon separator may not be present.
 221      */
 222     public String getActions() {
 223         return actions;
 224     }
 225 
 226     /**
 227      * Checks if this URLPermission implies the given permission.
 228      * Specifically, the following checks are done as if in the
 229      * following sequence:
 230      * <ul>
 231      * <li>if 'p' is not an instance of URLPermission return false</li>
 232      * <li>if any of p's methods are not in this's method list, and if
 233      *     this's method list is not equal to "*", then return false.</li>
 234      * <li>if any of p's headers are not in this's request header list, and if
 235      *     this's request header list is not equal to "*", then return false.</li>
 236      * <li>if this's url scheme is not equal to p's url scheme return false</li>
 237      * <li>if the scheme specific part of this's url is '*' return true</li>
 238      * <li>if the set of hosts defined by p's url hostrange is not a subset of
 239      *     this's url hostrange then return false. For example, "*.foo.oracle.com"
 240      *     is a subset of "*.oracle.com". "foo.bar.oracle.com" is not
 241      *     a subset of "*.foo.oracle.com"</li>
 242      * <li>if the portrange defined by p's url is not a subset of the
 243      *     portrange defined by this's url then return false.
 244      * <li>if the path or paths specified by p's url are contained in the
 245      *     set of paths specified by this's url, then return true
 246      * <li>otherwise, return false</li>
 247      * </ul>
 248      * <p>Some examples of how paths are matched are shown below:
 249      * <table border>
 250      * <caption>Examples of Path Matching</caption>
 251      * <tr><th>this's path</th><th>p's path</th><th>match</th></tr>
 252      * <tr><td>/a/b</td><td>/a/b</td><td>yes</td></tr>
 253      * <tr><td>/a/b/*</td><td>/a/b/c</td><td>yes</td></tr>
 254      * <tr><td>/a/b/*</td><td>/a/b/c/d</td><td>no</td></tr>
 255      * <tr><td>/a/b/-</td><td>/a/b/c/d</td><td>yes</td></tr>
 256      * <tr><td>/a/b/-</td><td>/a/b/c/d/e</td><td>yes</td></tr>
 257      * <tr><td>/a/b/-</td><td>/a/b/c/*</td><td>yes</td></tr>
 258      * <tr><td>/a/b/*</td><td>/a/b/c/-</td><td>no</td></tr>
 259      * </table>
 260      */
 261     public boolean implies(Permission p) {
 262         if (! (p instanceof URLPermission)) {
 263             return false;
 264         }
 265 
 266         URLPermission that = (URLPermission)p;
 267 
 268         if (this.methods.isEmpty() && !that.methods.isEmpty()) {
 269             return false;
 270         }
 271 
 272         if (!this.methods.isEmpty() &&
 273             !this.methods.get(0).equals("*") &&
 274             Collections.indexOfSubList(this.methods,
 275                                        that.methods) == -1) {
 276             return false;
 277         }
 278 
 279         if (this.requestHeaders.isEmpty() && !that.requestHeaders.isEmpty()) {
 280             return false;
 281         }
 282 
 283         if (!this.requestHeaders.isEmpty() &&
 284             !this.requestHeaders.get(0).equals("*") &&
 285              Collections.indexOfSubList(this.requestHeaders,
 286                                         that.requestHeaders) == -1) {
 287             return false;
 288         }
 289 
 290         if (!this.scheme.equals(that.scheme)) {
 291             return false;
 292         }
 293 
 294         if (this.ssp.equals("*")) {
 295             return true;
 296         }
 297 
 298         if (!this.authority.implies(that.authority)) {
 299             return false;
 300         }
 301 
 302         if (this.path == null) {
 303             return that.path == null;
 304         }
 305         if (that.path == null) {
 306             return false;
 307         }
 308 
 309         if (this.path.endsWith("/-")) {
 310             String thisprefix = this.path.substring(0, this.path.length() - 1);
 311             return that.path.startsWith(thisprefix);
 312             }
 313 
 314         if (this.path.endsWith("/*")) {
 315             String thisprefix = this.path.substring(0, this.path.length() - 1);
 316             if (!that.path.startsWith(thisprefix)) {
 317                 return false;
 318             }
 319             String thatsuffix = that.path.substring(thisprefix.length());
 320             // suffix must not contain '/' chars
 321             if (thatsuffix.indexOf('/') != -1) {
 322                 return false;
 323             }
 324             if (thatsuffix.equals("-")) {
 325                 return false;
 326             }
 327             return true;
 328         }
 329         return this.path.equals(that.path);
 330     }
 331 
 332 
 333     /**
 334      * Returns true if, this.getActions().equals(p.getActions())
 335      * and p's url equals this's url.  Returns false otherwise.
 336      */
 337     public boolean equals(Object p) {
 338         if (!(p instanceof URLPermission)) {
 339             return false;
 340         }
 341         URLPermission that = (URLPermission)p;
 342         if (!this.scheme.equals(that.scheme)) {
 343             return false;
 344         }
 345         if (!this.getActions().equals(that.getActions())) {
 346             return false;
 347         }
 348         if (!this.authority.equals(that.authority)) {
 349             return false;
 350         }
 351         if (this.path != null) {
 352             return this.path.equals(that.path);
 353         } else {
 354             return that.path == null;
 355         }
 356     }
 357 
 358     /**
 359      * Returns a hashcode calculated from the hashcode of the
 360      * actions String and the url string.
 361      */
 362     public int hashCode() {
 363         return getActions().hashCode()
 364             + scheme.hashCode()
 365             + authority.hashCode()
 366             + (path == null ? 0 : path.hashCode());
 367     }
 368 
 369 
 370     private List<String> normalizeMethods(String methods) {
 371         List<String> l = new ArrayList<>();
 372         StringBuilder b = new StringBuilder();
 373         for (int i=0; i<methods.length(); i++) {
 374             char c = methods.charAt(i);
 375             if (c == ',') {
 376                 String s = b.toString();
 377                 if (s.length() > 0)
 378                     l.add(s);
 379                 b = new StringBuilder();
 380             } else if (c == ' ' || c == '\t') {
 381                 throw new IllegalArgumentException(
 382                     "White space not allowed in methods: \"" + methods + "\"");
 383             } else {
 384                 if (c >= 'a' && c <= 'z') {
 385                     c += 'A' - 'a';
 386                 }
 387                 b.append(c);
 388             }
 389         }
 390         String s = b.toString();
 391         if (s.length() > 0)
 392             l.add(s);
 393         return l;
 394     }
 395 
 396     private List<String> normalizeHeaders(String headers) {
 397         List<String> l = new ArrayList<>();
 398         StringBuilder b = new StringBuilder();
 399         boolean capitalizeNext = true;
 400         for (int i=0; i<headers.length(); i++) {
 401             char c = headers.charAt(i);
 402             if (c >= 'a' && c <= 'z') {
 403                 if (capitalizeNext) {
 404                     c += 'A' - 'a';
 405                     capitalizeNext = false;
 406                 }
 407                 b.append(c);
 408             } else if (c == ' ' || c == '\t') {
 409                 throw new IllegalArgumentException(
 410                     "White space not allowed in headers: \"" + headers + "\"");
 411             } else if (c == '-') {
 412                     capitalizeNext = true;
 413                 b.append(c);
 414             } else if (c == ',') {
 415                 String s = b.toString();
 416                 if (s.length() > 0)
 417                     l.add(s);
 418                 b = new StringBuilder();
 419                 capitalizeNext = true;
 420             } else {
 421                 capitalizeNext = false;
 422                 b.append(c);
 423             }
 424         }
 425         String s = b.toString();
 426         if (s.length() > 0)
 427             l.add(s);
 428         return l;
 429     }
 430 
 431     private void parseURI(String url) {
 432         int len = url.length();
 433         int delim = url.indexOf(':');
 434         if (delim == -1 || delim + 1 == len) {
 435             throw new IllegalArgumentException(
 436                 "Invalid URL string: \"" + url + "\"");
 437         }
 438         scheme = url.substring(0, delim).toLowerCase();
 439         this.ssp = url.substring(delim + 1);
 440 
 441         if (!ssp.startsWith("//")) {
 442             if (!ssp.equals("*")) {
 443                 throw new IllegalArgumentException(
 444                     "Invalid URL string: \"" + url + "\"");
 445             }
 446             this.authority = new Authority(scheme, "*");
 447             return;
 448         }
 449         String authpath = ssp.substring(2);
 450 
 451         delim = authpath.indexOf('/');
 452         String auth;
 453         if (delim == -1) {
 454             this.path = "";
 455             auth = authpath;
 456         } else {
 457             auth = authpath.substring(0, delim);
 458             this.path = authpath.substring(delim);
 459         }
 460         this.authority = new Authority(scheme, auth.toLowerCase());
 461     }
 462 
 463     private String actions() {
 464         // The colon separator is optional when the request headers list is
 465         // empty.This implementation chooses to include it even when the request
 466         // headers list is empty.
 467         return String.join(",", methods) + ":" + String.join(",", requestHeaders);
 468     }
 469 
 470     /**
 471      * restore the state of this object from stream
 472      */
 473     private void readObject(ObjectInputStream s)
 474         throws IOException, ClassNotFoundException {
 475         ObjectInputStream.GetField fields = s.readFields();
 476         String actions = (String)fields.get("actions", null);
 477 
 478         init(actions);
 479     }
 480 
 481     static class Authority {
 482         HostPortrange p;
 483 
 484         Authority(String scheme, String authority) {
 485             int at = authority.indexOf('@');
 486             if (at == -1) {
 487                     p = new HostPortrange(scheme, authority);
 488             } else {
 489                     p = new HostPortrange(scheme, authority.substring(at+1));
 490             }
 491         }
 492 
 493         boolean implies(Authority other) {
 494             return impliesHostrange(other) && impliesPortrange(other);
 495         }
 496 
 497         private boolean impliesHostrange(Authority that) {
 498             String thishost = this.p.hostname();
 499             String thathost = that.p.hostname();
 500 
 501             if (p.wildcard() && thishost.equals("")) {
 502                 // this "*" implies all others
 503                 return true;
 504             }
 505             if (that.p.wildcard() && thathost.equals("")) {
 506                 // that "*" can only be implied by this "*"
 507                 return false;
 508             }
 509             if (thishost.equals(thathost)) {
 510                 // covers all cases of literal IP addresses and fixed
 511                 // domain names.
 512                 return true;
 513             }
 514             if (this.p.wildcard()) {
 515                 // this "*.foo.com" implies "bub.bar.foo.com"
 516                 return thathost.endsWith(thishost);
 517             }
 518             return false;
 519         }
 520 
 521         private boolean impliesPortrange(Authority that) {
 522             int[] thisrange = this.p.portrange();
 523             int[] thatrange = that.p.portrange();
 524             if (thisrange[0] == -1) {
 525                 /* port not specified non http/s URL */
 526                 return true;
 527             }
 528             return thisrange[0] <= thatrange[0] &&
 529                         thisrange[1] >= thatrange[1];
 530         }
 531 
 532         boolean equals(Authority that) {
 533             return this.p.equals(that.p);
 534         }
 535 
 536         public int hashCode() {
 537             return p.hashCode();
 538         }
 539     }
 540 }