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