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