1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host.fetch;
16
17 import static java.nio.charset.StandardCharsets.ISO_8859_1;
18 import static java.nio.charset.StandardCharsets.UTF_8;
19 import static org.htmlunit.BrowserVersionFeatures.XHR_PREFLIGHT_CORS;
20
21 import java.io.IOException;
22 import java.net.MalformedURLException;
23 import java.net.URL;
24 import java.util.HashSet;
25 import java.util.Locale;
26 import java.util.Map.Entry;
27 import java.util.Set;
28 import java.util.TreeMap;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.htmlunit.HttpHeader;
33 import org.htmlunit.HttpMethod;
34 import org.htmlunit.WebClient;
35 import org.htmlunit.WebRequest;
36 import org.htmlunit.WebRequest.HttpHint;
37 import org.htmlunit.WebResponse;
38 import org.htmlunit.WebWindow;
39 import org.htmlunit.html.HtmlPage;
40 import org.htmlunit.html.csp.ContentSecurityPolicy;
41 import org.htmlunit.util.NameValuePair;
42 import org.htmlunit.util.StringUtils;
43 import org.htmlunit.util.UrlUtils;
44
45
46
47
48
49
50
51
52
53
54 public final class CorsLoader {
55
56 private static final Log LOG = LogFactory.getLog(CorsLoader.class);
57
58
59 private static final Set<String> CORS_SAFELISTED_RESPONSE_HEADERS = Set.of(
60 "cache-control", "content-language", "content-length", "content-type",
61 "expires", "last-modified", "pragma");
62
63 private static final String ALLOW_ORIGIN_ALL = "*";
64
65 private static final int MAX_REDIRECTS = 20;
66
67
68
69
70 public enum CredentialsMode {
71
72 OMIT,
73
74 SAME_ORIGIN,
75
76 INCLUDE
77 }
78
79
80
81
82 public enum RequestMode {
83
84 CORS,
85
86 SAME_ORIGIN,
87
88 NO_CORS
89 }
90
91
92
93
94 public enum RedirectMode {
95
96 FOLLOW,
97
98 ERROR,
99
100 MANUAL
101 }
102
103
104
105
106
107
108
109
110
111
112
113 public record Result(WebResponse response, URL url, boolean redirected,
114 boolean corsTainting, boolean opaqueRedirect) {
115 }
116
117
118
119
120 public static final class NoPermittedHeaderException extends IOException {
121
122
123
124
125 public NoPermittedHeaderException(final String msg) {
126 super(msg);
127 }
128 }
129
130
131
132
133 public static final class RedirectException extends IOException {
134
135
136
137
138 public RedirectException(final String msg) {
139 super(msg);
140 }
141
142
143
144
145
146
147 public RedirectException(final String msg, final Throwable cause) {
148 super(msg, cause);
149 }
150 }
151
152 private final WebWindow webWindow_;
153 private final CredentialsMode credentialsMode_;
154 private final RedirectMode redirectMode_;
155 private final int timeout_;
156 private final RequestMode requestMode_;
157
158
159
160
161
162
163
164
165
166 public CorsLoader(final WebWindow webWindow, final CredentialsMode credentialsMode,
167 final RedirectMode redirectMode, final int timeout) {
168 this(webWindow, credentialsMode, redirectMode, timeout, RequestMode.CORS);
169 }
170
171
172
173
174
175
176
177
178
179
180 public CorsLoader(final WebWindow webWindow, final CredentialsMode credentialsMode,
181 final RedirectMode redirectMode, final int timeout, final RequestMode requestMode) {
182 webWindow_ = webWindow;
183 credentialsMode_ = credentialsMode;
184 redirectMode_ = redirectMode;
185 timeout_ = timeout;
186 requestMode_ = requestMode;
187 }
188
189 private boolean isIncludeCredentials() {
190 return credentialsMode_ == CredentialsMode.INCLUDE;
191 }
192
193
194
195
196
197
198
199
200 public void ensureConnectionAllowed(final URL url, final URL reportedUrl) throws IOException {
201 if (webWindow_ != null
202 && webWindow_.getEnclosedPage() instanceof HtmlPage page
203 && !ContentSecurityPolicy.allowsConnection(page, url, reportedUrl)) {
204 throw new IOException("Refused to connect to '" + url
205 + "' because it violates the Content Security Policy of the page.");
206 }
207 }
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231 public Result load(final WebRequest webRequest, final boolean sameOrigin) throws IOException {
232 final WebClient wc = webWindow_.getWebClient();
233 final URL pageUrl = webRequest.getRequestingUrl();
234 final String pageOrigin = serializeOrigin(pageUrl);
235
236 WebRequest request = webRequest;
237
238 boolean corsTainting = !sameOrigin;
239
240 boolean taintedOrigin = false;
241
242 for (int redirects = 0;; redirects++) {
243
244 request.addHint(HttpHint.DoNotFollowRedirects);
245 if (credentialsMode_ == CredentialsMode.OMIT
246 || corsTainting && credentialsMode_ == CredentialsMode.SAME_ORIGIN) {
247 request.addHint(HttpHint.BlockCookies);
248 }
249
250 final WebResponse response = wc.loadWebResponse(request);
251 final String originHeader = request.getAdditionalHeaders().get(HttpHeader.ORIGIN);
252 final URL currentUrl = request.getUrl();
253
254 URL nextUrl = wc.getOptions().isRedirectEnabled() ? getRedirectUrl(response, currentUrl) : null;
255
256 if (nextUrl != null && webWindow_.getEnclosedPage() instanceof HtmlPage page) {
257 nextUrl = ContentSecurityPolicy.upgradeInsecureRequest(page, nextUrl);
258 }
259
260
261
262 if (corsTainting && requestMode_ != RequestMode.NO_CORS && !isCorsAllowed(response, originHeader)) {
263 if (LOG.isDebugEnabled()) {
264 LOG.debug("No permitted \"Access-Control-Allow-Origin\" header for URL " + currentUrl);
265 }
266 throw new NoPermittedHeaderException("No permitted \"Access-Control-Allow-Origin\" header.");
267 }
268
269 if (nextUrl == null) {
270 return new Result(response, currentUrl, redirects > 0, corsTainting, false);
271 }
272
273 if (redirectMode_ == RedirectMode.ERROR) {
274 throw new RedirectException("Redirect for '" + currentUrl + "' with redirect mode 'error'.");
275 }
276 if (redirectMode_ == RedirectMode.MANUAL) {
277 return new Result(response, currentUrl, redirects > 0, corsTainting, true);
278 }
279
280 if (redirects >= MAX_REDIRECTS) {
281 throw new RedirectException("Too many redirects for " + webRequest.getUrl());
282 }
283
284 ensureConnectionAllowed(nextUrl, webRequest.getUrl());
285
286 final boolean crossOriginRedirect = !UrlUtils.isSameOrigin(currentUrl, nextUrl);
287 final boolean foreignTarget = !UrlUtils.isSameOrigin(pageUrl, nextUrl);
288 if (requestMode_ == RequestMode.SAME_ORIGIN && foreignTarget) {
289 throw new RedirectException("Redirect to another origin with request mode 'same-origin': "
290 + nextUrl);
291 }
292 if (requestMode_ == RequestMode.CORS && nextUrl.getUserInfo() != null
293 && (corsTainting || foreignTarget)) {
294 throw new RedirectException("Redirect to a URL with credentials is not allowed: " + currentUrl);
295 }
296
297 if (crossOriginRedirect && !UrlUtils.isSameOrigin(pageUrl, currentUrl)) {
298 taintedOrigin = true;
299 }
300 corsTainting = corsTainting || foreignTarget;
301
302 request = createRedirectRequest(request, response.getStatusCode(), nextUrl, crossOriginRedirect);
303 setOriginHeader(request, corsTainting && requestMode_ != RequestMode.NO_CORS, taintedOrigin, pageOrigin);
304
305 if (corsTainting && requestMode_ != RequestMode.NO_CORS && isPreflight(request)) {
306 final WebResponse preflightResponse = sendPreflight(request);
307 if (!preflightResponse.isSuccessOrUseProxyOrNotModified()
308 || !isPreflightAuthorized(request, preflightResponse)) {
309 throw new NoPermittedHeaderException("No permitted \"Access-Control-Allow-Origin\" header.");
310 }
311 }
312 }
313 }
314
315
316
317
318
319
320
321
322
323 private static URL getRedirectUrl(final WebResponse response, final URL currentUrl) throws IOException {
324 final int status = response.getStatusCode();
325 if (status != 301 && status != 302 && status != 303 && status != 307 && status != 308) {
326 return null;
327 }
328
329 String location = response.getResponseHeaderValue("Location");
330 if (location == null) {
331 return null;
332 }
333 location = new String(location.getBytes(ISO_8859_1), UTF_8);
334
335 final URL url;
336 try {
337 url = WebClient.expandUrl(currentUrl, location);
338 }
339 catch (final MalformedURLException e) {
340 throw new RedirectException("Invalid redirect location '" + location + "'", e);
341 }
342
343 final String protocol = url.getProtocol();
344 if (!"http".equals(protocol) && !"https".equals(protocol)) {
345 throw new RedirectException("Redirect to the unsupported scheme '" + protocol + "' is not allowed.");
346 }
347 return url;
348 }
349
350
351
352
353
354
355
356
357
358
359 private static WebRequest createRedirectRequest(final WebRequest request, final int status,
360 final URL url, final boolean crossOriginRedirect) {
361 final HttpMethod method = request.getHttpMethod();
362 final boolean toGet = ((status == 301 || status == 302) && method == HttpMethod.POST)
363 || (status == 303 && method != HttpMethod.GET && method != HttpMethod.HEAD);
364
365 final WebRequest next = new WebRequest(url, toGet ? HttpMethod.GET : method);
366 next.setCharset(request.getCharset());
367 next.setDefaultResponseContentCharset(request.getDefaultResponseContentCharset());
368 next.setFetchDestination(request.getFetchDestination());
369 next.setFetchModeOverride(request.getFetchModeOverride());
370 next.setRequestingUrl(request.getRequestingUrl());
371 next.setSiteForCookies(request.getSiteForCookies());
372 next.setTimeout(request.getTimeout());
373 next.setCacheMode(request.getCacheMode());
374 if (request.hasHint(HttpHint.IncludeCharsetInContentTypeHeader)) {
375 next.addHint(HttpHint.IncludeCharsetInContentTypeHeader);
376 }
377
378 for (final Entry<String, String> header : request.getAdditionalHeaders().entrySet()) {
379 next.setAdditionalHeader(header.getKey(), header.getValue());
380 }
381
382 if (toGet) {
383
384 next.removeAdditionalHeader(HttpHeader.CONTENT_TYPE);
385 next.removeAdditionalHeader("Content-Length");
386 next.removeAdditionalHeader("Content-Encoding");
387 next.removeAdditionalHeader("Content-Language");
388 next.removeAdditionalHeader("Content-Location");
389 }
390 else if (request.getRequestBody() != null) {
391 next.setRequestBody(request.getRequestBody());
392 next.setEncodingType(request.getEncodingType());
393 }
394 else if (!request.getRequestParameters().isEmpty()) {
395 next.setRequestParameters(request.getRequestParameters());
396 }
397
398 if (crossOriginRedirect) {
399
400 next.removeAdditionalHeader("Authorization");
401 }
402 else {
403 next.setCredentials(request.getCredentials());
404 }
405 return next;
406 }
407
408
409
410
411 private static void setOriginHeader(final WebRequest request, final boolean corsTainting,
412 final boolean taintedOrigin, final String pageOrigin) {
413 final HttpMethod method = request.getHttpMethod();
414 if (corsTainting || (method != HttpMethod.GET && method != HttpMethod.HEAD)) {
415 request.setAdditionalHeader(HttpHeader.ORIGIN, taintedOrigin ? "null" : pageOrigin);
416 }
417 else {
418 request.removeAdditionalHeader(HttpHeader.ORIGIN);
419 }
420 }
421
422
423
424
425
426
427
428 public static String serializeOrigin(final URL url) {
429 final StringBuilder origin = new StringBuilder().append(url.getProtocol()).append("://")
430 .append(url.getHost());
431 if (url.getPort() != -1) {
432 origin.append(':').append(url.getPort());
433 }
434 return origin.toString();
435 }
436
437
438
439
440
441
442
443
444 public boolean isCorsAllowed(final WebResponse response, final String origin) {
445 String value = response.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);
446 final boolean allowed = origin != null && origin.equals(value);
447 if (isIncludeCredentials()) {
448
449 value = response.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS);
450 return allowed && Boolean.parseBoolean(value);
451 }
452 return allowed || ALLOW_ORIGIN_ALL.equals(value);
453 }
454
455
456
457
458
459
460
461
462 public WebResponse sendPreflight(final WebRequest request) throws IOException {
463 final WebRequest preflightRequest = new WebRequest(request.getUrl(), HttpMethod.OPTIONS);
464 preflightRequest.setEncodingType(null);
465
466
467 preflightRequest.addHint(HttpHint.BlockCookies);
468
469
470 final String originHeaderValue = request.getAdditionalHeaders().get(HttpHeader.ORIGIN);
471 preflightRequest.setAdditionalHeader(HttpHeader.ORIGIN, originHeaderValue);
472
473
474 preflightRequest.setAdditionalHeader(
475 HttpHeader.ACCESS_CONTROL_REQUEST_METHOD,
476 request.getHttpMethod().name());
477
478
479 final StringBuilder builder = new StringBuilder();
480 for (final Entry<String, String> header
481 : new TreeMap<>(request.getAdditionalHeaders()).entrySet()) {
482 final String name = StringUtils.toRootLowerCase(header.getKey());
483 if (isPreflightHeader(name, header.getValue())) {
484 if (builder.length() != 0) {
485 builder.append(',');
486 }
487 builder.append(name);
488 }
489 }
490 preflightRequest.setAdditionalHeader(HttpHeader.ACCESS_CONTROL_REQUEST_HEADERS, builder.toString());
491 if (timeout_ > 0) {
492 preflightRequest.setTimeout(timeout_);
493 }
494
495 final WebClient wc = webWindow_.getWebClient();
496 if (wc.getBrowserVersion().hasFeature(XHR_PREFLIGHT_CORS)) {
497
498 preflightRequest.setAdditionalHeader(HttpHeader.SEC_FETCH_MODE, "cors");
499 }
500
501 if (webWindow_.getEnclosedPage() instanceof HtmlPage containingPage) {
502 preflightRequest.setRefererHeader(containingPage.getUrl());
503 preflightRequest.setReferrerPolicy(containingPage.getReferrerPolicy());
504 }
505
506
507 return wc.loadWebResponse(preflightRequest);
508 }
509
510
511
512
513
514
515
516 public static boolean isPreflight(final WebRequest request) {
517 final HttpMethod method = request.getHttpMethod();
518 if (method != HttpMethod.GET && method != HttpMethod.HEAD && method != HttpMethod.POST) {
519 return true;
520 }
521 for (final Entry<String, String> header : request.getAdditionalHeaders().entrySet()) {
522 if (isPreflightHeader(header.getKey().toLowerCase(Locale.ROOT), header.getValue())) {
523 return true;
524 }
525 }
526 return false;
527 }
528
529
530
531
532
533
534
535
536 public boolean isPreflightAuthorized(final WebRequest request, final WebResponse preflightResponse) {
537
538
539 if (!isCorsAllowed(preflightResponse, request.getAdditionalHeaders().get(HttpHeader.ORIGIN))) {
540 return false;
541 }
542
543
544 final boolean wildcard = !isIncludeCredentials();
545
546 final HttpMethod method = request.getHttpMethod();
547 if (method != HttpMethod.GET && method != HttpMethod.HEAD && method != HttpMethod.POST
548 && !isPreflightMethodAllowed(method.name(), preflightResponse, wildcard)) {
549 return false;
550 }
551
552
553
554 final HashSet<String> accessControlValues = new HashSet<>();
555 for (final NameValuePair pair : preflightResponse.getResponseHeaders()) {
556 if (HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS.equalsIgnoreCase(pair.getName())) {
557 String value = pair.getValue();
558 if (value != null) {
559 if (wildcard && ALLOW_ORIGIN_ALL.equals(value)) {
560
561 return true;
562 }
563 value = StringUtils.toRootLowerCase(value);
564 final String[] values = StringUtils.splitAtComma(value);
565 for (String part : values) {
566 part = part.trim();
567 if (!StringUtils.isEmptyOrNull(part)) {
568 accessControlValues.add(part);
569 }
570 }
571 }
572 }
573 }
574
575 for (final Entry<String, String> header : request.getAdditionalHeaders().entrySet()) {
576 final String key = StringUtils.toRootLowerCase(header.getKey());
577 if (isPreflightHeader(key, header.getValue())
578 && !accessControlValues.contains(key)) {
579 return false;
580 }
581 }
582 return true;
583 }
584
585
586
587
588
589
590
591
592
593
594 private static boolean isPreflightMethodAllowed(final String method, final WebResponse preflightResponse,
595 final boolean wildcard) {
596 for (final NameValuePair pair : preflightResponse.getResponseHeaders()) {
597 if (HttpHeader.ACCESS_CONTROL_ALLOW_METHODS.equalsIgnoreCase(pair.getName())
598 && pair.getValue() != null) {
599 for (final String part : StringUtils.splitAtComma(pair.getValue())) {
600 final String allowed = part.trim();
601 if (method.equals(allowed) || (wildcard && ALLOW_ORIGIN_ALL.equals(allowed))) {
602 return true;
603 }
604 }
605 }
606 }
607 return false;
608 }
609
610
611
612
613
614
615
616
617
618
619
620 private static boolean isPreflightHeader(final String name, final String value) {
621 if (HttpHeader.REFERER_LC.equals(name)
622 || "accept-encoding".equals(name)
623 || HttpHeader.ORIGIN_LC.equals(name)) {
624 return false;
625 }
626 return !Headers.isCorsSafelistedRequestHeader(name, value);
627 }
628
629
630
631
632
633
634
635
636 public static boolean isForbiddenResponseHeader(final String name) {
637 return "set-cookie".equalsIgnoreCase(name) || "set-cookie2".equalsIgnoreCase(name);
638 }
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653 public static boolean isExposedResponseHeader(final WebResponse response, final String name,
654 final boolean corsTainting, final boolean includeCredentials) {
655 if (isForbiddenResponseHeader(name)) {
656 return false;
657 }
658 if (!corsTainting) {
659 return true;
660 }
661
662 if (name == null) {
663 return false;
664 }
665 final String nameLC = name.toLowerCase(Locale.ROOT);
666 if (CORS_SAFELISTED_RESPONSE_HEADERS.contains(nameLC)) {
667 return true;
668 }
669
670 for (final NameValuePair header : response.getResponseHeaders()) {
671 if (HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS.equalsIgnoreCase(header.getName())) {
672 for (final String token : StringUtils.splitAtComma(header.getValue())) {
673 final String exposed = token.trim();
674
675 if (exposed.equalsIgnoreCase(name) || ("*".equals(exposed) && !includeCredentials)) {
676 return true;
677 }
678 }
679 }
680 }
681 return false;
682 }
683 }