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