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