1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.html.csp;
16
17 import static java.nio.charset.StandardCharsets.UTF_8;
18 import static org.htmlunit.BrowserVersionFeatures.CSP_META_SINGLE_POLICY;
19 import static org.htmlunit.BrowserVersionFeatures.CSP_CONNECT_REDIRECT_VIOLATION_DELAYED;
20 import static org.htmlunit.BrowserVersionFeatures.CSP_NONCE_HIDING_ENFORCED_ONLY;
21 import static org.htmlunit.BrowserVersionFeatures.CSP_NONCE_TRIMMED;
22 import static org.htmlunit.BrowserVersionFeatures.CSP_REPORT_FIREFOX_FORMAT;
23 import static org.htmlunit.BrowserVersionFeatures.CSP_UPGRADE_INSECURE_REQUESTS_MATCHES_HTTPS;
24 import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
25
26 import java.io.IOException;
27 import java.io.Serializable;
28 import java.net.MalformedURLException;
29 import java.net.URL;
30 import java.util.ArrayList;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Locale;
34 import java.util.Optional;
35 import java.util.Set;
36 import java.util.function.Predicate;
37
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40 import org.htmlunit.HttpHeader;
41 import org.htmlunit.HttpMethod;
42 import org.htmlunit.SgmlPage;
43 import org.htmlunit.TopLevelWindow;
44 import org.htmlunit.WebClient;
45 import org.htmlunit.WebRequest;
46 import org.htmlunit.WebResponse;
47 import org.htmlunit.WebWindow;
48 import org.htmlunit.corejs.javascript.Context;
49 import org.htmlunit.corejs.javascript.EvaluatorException;
50 import org.htmlunit.corejs.javascript.ScriptStackElement;
51 import org.htmlunit.csp.FetchDirectiveKind;
52 import org.htmlunit.csp.Policy;
53 import org.htmlunit.csp.directive.ReportUriDirective;
54 import org.htmlunit.csp.directive.SandboxDirective;
55 import org.htmlunit.csp.directive.SourceExpressionDirective;
56 import org.htmlunit.csp.url.GUID;
57 import org.htmlunit.csp.url.URI;
58 import org.htmlunit.csp.url.URLWithScheme;
59 import org.htmlunit.html.DomAttr;
60 import org.htmlunit.html.DomElement;
61 import org.htmlunit.html.DomNode;
62 import org.htmlunit.html.FrameWindow;
63 import org.htmlunit.html.HtmlPage;
64 import org.htmlunit.javascript.AbstractJavaScriptEngine;
65 import org.htmlunit.javascript.JavaScriptEngine;
66 import org.htmlunit.javascript.host.event.EventTarget;
67 import org.htmlunit.javascript.host.event.SecurityPolicyViolationEvent;
68 import org.htmlunit.util.NameValuePair;
69 import org.htmlunit.util.StringUtils;
70 import org.htmlunit.util.UrlUtils;
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86 public final class ContentSecurityPolicy implements Serializable {
87
88 private static final Log LOG = LogFactory.getLog(ContentSecurityPolicy.class);
89
90
91 public static final String HEADER_REPORT_ONLY = "Content-Security-Policy-Report-Only";
92
93
94 private static final int SAMPLE_LENGTH = 40;
95
96 private static final String BLOCKED_INLINE = "inline";
97 private static final String BLOCKED_EVAL = "eval";
98 private static final String FORM_ACTION = "form-action";
99 private static final String BASE_URI = "base-uri";
100 private static final String REPORT_CONTENT_TYPE = "application/csp-report";
101
102
103 private static final ThreadLocal<List<Runnable>> PENDING_VIOLATIONS = new ThreadLocal<>();
104
105 private final List<String> enforced_ = new ArrayList<>();
106 private final List<String> reportOnly_ = new ArrayList<>();
107 private final List<String> meta_ = new ArrayList<>();
108 private boolean metaSinglePolicy_;
109
110 private URL selfUrl_;
111
112 private transient List<Policy> enforcedPolicies_;
113 private transient List<Policy> reportOnlyPolicies_;
114
115
116
117
118 private ContentSecurityPolicy() {
119 super();
120 }
121
122
123
124
125
126
127
128 public static ContentSecurityPolicy fromResponse(final WebResponse webResponse) {
129 if (webResponse == null) {
130 return null;
131 }
132
133 ContentSecurityPolicy result = null;
134 for (final NameValuePair header : webResponse.getResponseHeaders()) {
135 final String value = header.getValue();
136 if (StringUtils.isBlank(value)) {
137 continue;
138 }
139
140 if (HttpHeader.CONTENT_SECURIRY_POLICY.equalsIgnoreCase(header.getName())) {
141 if (result == null) {
142 result = new ContentSecurityPolicy();
143 }
144 result.enforced_.add(value);
145 }
146 else if (HEADER_REPORT_ONLY.equalsIgnoreCase(header.getName())) {
147 if (result == null) {
148 result = new ContentSecurityPolicy();
149 }
150 result.reportOnly_.add(value);
151 }
152 }
153 return result;
154 }
155
156
157
158
159
160
161
162
163
164
165
166
167
168 public static ContentSecurityPolicy inherit(final URL url, final WebWindow window) {
169 if (url == null || window == null) {
170 return null;
171 }
172 final String protocol = url.getProtocol();
173 if (!"about".equals(protocol) && !"data".equals(protocol) && !"blob".equals(protocol)) {
174 return null;
175 }
176
177 WebWindow creator = null;
178 if (window instanceof FrameWindow) {
179 creator = window.getParentWindow();
180 }
181 else if (window instanceof TopLevelWindow topLevelWindow) {
182 creator = topLevelWindow.getOpener();
183 }
184 if (creator == null || creator == window
185 || !(creator.getEnclosedPage() instanceof HtmlPage creatorPage)) {
186 return null;
187 }
188
189 final ContentSecurityPolicy creatorCsp = creatorPage.getContentSecurityPolicy();
190 if (creatorCsp == null) {
191 return null;
192 }
193
194 final ContentSecurityPolicy result = new ContentSecurityPolicy();
195 result.enforced_.addAll(creatorCsp.enforced_);
196 result.reportOnly_.addAll(creatorCsp.reportOnly_);
197 result.meta_.addAll(creatorCsp.meta_);
198 result.metaSinglePolicy_ = creatorCsp.metaSinglePolicy_;
199 result.selfUrl_ = selfUrl(creatorPage);
200 return result;
201 }
202
203
204
205
206
207
208
209
210
211
212 public static void addMetaPolicy(final HtmlPage page, final String serializedPolicy) {
213 if (StringUtils.isBlank(serializedPolicy)) {
214 return;
215 }
216
217 ContentSecurityPolicy csp = page.getContentSecurityPolicy();
218 if (csp == null) {
219 csp = new ContentSecurityPolicy();
220 page.setContentSecurityPolicy(csp);
221 }
222 csp.meta_.add(serializedPolicy);
223 csp.metaSinglePolicy_ = page.getWebClient().getBrowserVersion().hasFeature(CSP_META_SINGLE_POLICY);
224 csp.enforcedPolicies_ = null;
225 }
226
227
228
229
230
231
232
233
234
235 public static boolean allowsInlineScript(final HtmlPage page, final DomElement element, final String source) {
236 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
237 if (csp == null) {
238 return true;
239 }
240
241 final Optional<String> nonce = nonce(element);
242 final Optional<Boolean> parserInserted = Optional.of(isParserInserted(element));
243 final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcElem, BLOCKED_INLINE, source,
244 element, documentUrl(page), element.getStartLineNumber(), element.getStartColumnNumber());
245 return csp.check(page, violation,
246 policy -> policy.allowsInlineScript(nonce, Optional.of(source), parserInserted));
247 }
248
249
250
251
252
253
254
255
256
257 public static boolean allowsExternalScript(final HtmlPage page, final DomElement element, final URL url) {
258 return allowsExternalScript(page, element, url, url);
259 }
260
261
262
263
264
265
266
267
268
269
270 public static boolean allowsExternalScript(final HtmlPage page, final DomElement element, final URL url,
271 final URL reportedUrl) {
272 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
273 if (csp == null) {
274 return true;
275 }
276
277 final Optional<String> nonce = nonce(element);
278 final String integrityAttrib = element.getAttributeDirect("integrity");
279 final Optional<String> integrity = ATTRIBUTE_NOT_DEFINED == integrityAttrib
280 ? Optional.empty() : Optional.of(integrityAttrib);
281 final Optional<URLWithScheme> scriptUrl = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
282 final Optional<Boolean> parserInserted = Optional.of(isParserInserted(element));
283 final Optional<URI> origin = origin(page);
284 final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcElem, blockedUri(reportedUrl), null,
285 null, "", 0, 0);
286 final boolean redirected = isRedirect(url, reportedUrl);
287 return csp.check(page, violation,
288 policy -> policy.allowsExternalScript(nonce, integrity, scriptUrl, parserInserted, origin,
289 redirected));
290 }
291
292
293
294
295
296
297
298
299
300 public static boolean allowsScriptAsAttribute(final HtmlPage page, final DomElement element,
301 final String source) {
302 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
303 if (csp == null) {
304 return true;
305 }
306
307 final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcAttr, BLOCKED_INLINE, source,
308 element, "", 0, 0);
309 final boolean allowed = csp.check(page, violation,
310 policy -> policy.allowsScriptAsAttribute(Optional.of(source)));
311 firePendingViolationsIfNoScriptRunning(page);
312 return allowed;
313 }
314
315
316
317
318
319
320
321
322
323 public static boolean allowsJavaScriptUrl(final HtmlPage page, final DomElement element,
324 final String source) {
325 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
326 if (csp == null) {
327 return true;
328 }
329
330 final Optional<URI> origin = origin(page);
331 final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcElem, BLOCKED_INLINE, source,
332 element, "", 0, 0);
333 final boolean allowed = csp.check(page, violation,
334 policy -> policy.allowsJavascriptUrlNavigation(Optional.of(source), origin));
335 firePendingViolationsIfNoScriptRunning(page);
336 return allowed;
337 }
338
339
340
341
342
343
344
345
346
347
348 public static boolean allowsConnection(final HtmlPage page, final URL url, final URL reportedUrl) {
349 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
350 if (csp == null) {
351 return true;
352 }
353
354 final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
355 final Optional<URI> origin = origin(page);
356 final Violation violation = new Violation(FetchDirectiveKind.ConnectSrc, blockedUri(reportedUrl), null,
357 null, "", 0, 0);
358
359 final boolean redirected = isRedirect(url, reportedUrl);
360 final boolean allowed = csp.check(page, violation,
361 policy -> policy.allowsConnection(target, origin, false, redirected));
362
363
364
365 if (!redirected
366 || !page.getWebClient().getBrowserVersion().hasFeature(CSP_CONNECT_REDIRECT_VIOLATION_DELAYED)) {
367 firePendingViolationsIfNoScriptRunning(page);
368 }
369 return allowed;
370 }
371
372
373
374
375
376
377
378
379
380 public static boolean allowsInlineStyle(final HtmlPage page, final DomElement element, final String source) {
381 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
382 if (csp == null) {
383 return true;
384 }
385
386 final Optional<String> nonce = nonce(element);
387 final Violation violation = inlineViolation(page, FetchDirectiveKind.StyleSrcElem, source, element);
388 final boolean allowed = csp.check(page, violation,
389 policy -> policy.allowsInlineStyle(nonce, Optional.of(source)));
390 firePendingViolationsIfNoScriptRunning(page);
391 return allowed;
392 }
393
394
395
396
397
398
399
400
401
402
403
404 public static boolean allowsStyleAttribute(final HtmlPage page, final DomElement element,
405 final String source) {
406 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
407 if (csp == null) {
408 return true;
409 }
410
411 final Violation violation = inlineViolation(page, FetchDirectiveKind.StyleSrcAttr, source, element);
412 final boolean allowed = csp.check(page, violation,
413 policy -> policy.allowsStyleAsAttribute(Optional.of(source)));
414 firePendingViolationsIfNoScriptRunning(page);
415 return allowed;
416 }
417
418
419
420
421
422
423
424
425
426 public static boolean allowsExternalStyle(final HtmlPage page, final DomElement element, final URL url) {
427 return allowsExternalStyle(page, element, url, url);
428 }
429
430
431
432
433
434
435
436
437
438
439 public static boolean allowsExternalStyle(final HtmlPage page, final DomElement element, final URL url,
440 final URL reportedUrl) {
441 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
442 if (csp == null) {
443 return true;
444 }
445
446 final Optional<String> nonce = element == null ? Optional.empty() : nonce(element);
447 final Optional<URLWithScheme> styleUrl = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
448 final Optional<URI> origin = origin(page);
449 final Violation violation = new Violation(FetchDirectiveKind.StyleSrcElem, blockedUri(reportedUrl), null,
450 null, "", 0, 0);
451 final boolean redirected = isRedirect(url, reportedUrl);
452 final boolean allowed = csp.check(page, violation,
453 policy -> policy.allowsExternalStyle(nonce, styleUrl, origin, redirected));
454 firePendingViolationsIfNoScriptRunning(page);
455 return allowed;
456 }
457
458
459
460
461
462
463
464
465
466
467
468 public static boolean allowsFrame(final HtmlPage page, final URL url) {
469 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
470 if (csp == null) {
471 return true;
472 }
473
474 final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
475 final Optional<URI> origin = origin(page);
476 final Violation violation = new Violation(FetchDirectiveKind.FrameSrc, navigationBlockedUri(page, url),
477 null, null, "", 0, 0);
478 final boolean allowed = csp.check(page, violation, policy -> policy.allowsFrame(target, origin));
479 firePendingViolationsIfNoScriptRunning(page);
480 return allowed;
481 }
482
483
484
485
486
487
488
489
490
491
492 public static boolean allowsObject(final DomElement element, final String src) {
493 final HtmlPage page = element.getHtmlPageOrNull();
494 if (page == null || page.getContentSecurityPolicy() == null
495 || ATTRIBUTE_NOT_DEFINED == src || StringUtils.isBlank(src)) {
496 return true;
497 }
498
499 final URL url;
500 try {
501 url = page.getFullyQualifiedUrl(src);
502 }
503 catch (final MalformedURLException e) {
504 return true;
505 }
506
507 final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
508 final Optional<URI> origin = origin(page);
509 final Violation violation = new Violation(FetchDirectiveKind.ObjectSrc, objectBlockedUri(page, url), null,
510 null, "", 0, 0);
511 final boolean allowed = page.getContentSecurityPolicy()
512 .check(page, violation, policy -> policy.allowsObject(target, origin));
513 firePendingViolationsIfNoScriptRunning(page);
514 return allowed;
515 }
516
517
518
519
520
521
522
523
524
525
526 public static boolean allowsMedia(final DomElement element, final String src) {
527 final HtmlPage page = element.getHtmlPageOrNull();
528 if (page == null || page.getContentSecurityPolicy() == null
529 || ATTRIBUTE_NOT_DEFINED == src || StringUtils.isBlank(src)) {
530 return true;
531 }
532
533 final URL url;
534 try {
535 url = upgradeInsecureRequest(page, page.getFullyQualifiedUrl(src));
536 }
537 catch (final MalformedURLException e) {
538 return true;
539 }
540
541 final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
542 final Optional<URI> origin = origin(page);
543 final Violation violation = new Violation(FetchDirectiveKind.MediaSrc, blockedUri(url), null,
544 null, "", 0, 0);
545 final boolean allowed = page.getContentSecurityPolicy()
546 .check(page, violation, policy -> policy.allowsMedia(target, origin));
547 firePendingViolationsIfNoScriptRunning(page);
548 return allowed;
549 }
550
551
552
553
554
555
556
557
558 public static boolean allowsImage(final HtmlPage page, final URL url) {
559 return allowsImage(page, url, url);
560 }
561
562
563
564
565
566
567
568
569
570 public static boolean allowsImage(final HtmlPage page, final URL url, final URL reportedUrl) {
571 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
572 if (csp == null) {
573 return true;
574 }
575
576 final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
577 final Optional<URI> origin = origin(page);
578 final Violation violation = new Violation(FetchDirectiveKind.ImgSrc, blockedUri(reportedUrl), null,
579 null, "", 0, 0);
580 final boolean redirected = isRedirect(url, reportedUrl);
581 final boolean allowed = csp.check(page, violation,
582 policy -> policy.allowsImage(target, origin, redirected));
583 firePendingViolationsIfNoScriptRunning(page);
584 return allowed;
585 }
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601 public static URL upgradeInsecureRequest(final HtmlPage page, final URL url) {
602 if (url == null || !isUpgradable(url) || !upgradesInsecureRequests(page)) {
603 return url;
604 }
605 return upgrade(url);
606 }
607
608
609
610
611
612
613
614
615
616
617 public static URL upgradeInsecureNavigation(final HtmlPage page, final URL url) {
618 if (url == null || !isUpgradable(url)) {
619 return url;
620 }
621
622 HtmlPage current = page;
623 while (current != null) {
624 final ContentSecurityPolicy csp = current.getContentSecurityPolicy();
625 if (csp != null && csp.hasUpgradeInsecureRequests()) {
626 final URL pageUrl = current.getUrl();
627 if (pageUrl != null && pageUrl.getHost().equalsIgnoreCase(url.getHost())
628 && effectivePort(pageUrl) == effectivePort(url)) {
629 return upgrade(url);
630 }
631 }
632 current = parentPage(current);
633 }
634 return url;
635 }
636
637
638
639
640
641
642 private static URL matchingUrl(final HtmlPage page, final URL url) {
643 if (page.getWebClient().getBrowserVersion().hasFeature(CSP_UPGRADE_INSECURE_REQUESTS_MATCHES_HTTPS)) {
644 final String protocol = url.getProtocol();
645 if (("http".equals(protocol) || "ws".equals(protocol)) && upgradesInsecureRequests(page)) {
646 try {
647 return UrlUtils.getUrlWithNewProtocol(url, "http".equals(protocol) ? "https" : "wss");
648 }
649 catch (final MalformedURLException e) {
650 return url;
651 }
652 }
653 }
654 return url;
655 }
656
657
658
659
660
661
662
663
664 public static void upgradeInsecureRedirects(final HtmlPage page, final WebRequest request) {
665 if (upgradesInsecureRequests(page)) {
666 request.setRedirectUrlMapper(url -> upgradeInsecureRequest(page, url));
667 }
668 }
669
670
671
672
673
674
675
676 public static void upgradeInsecureNavigationRedirects(final HtmlPage page, final WebRequest request) {
677 if (upgradesInsecureRequests(page)) {
678 request.setRedirectUrlMapper(url -> upgradeInsecureNavigation(page, url));
679 }
680 }
681
682 private static boolean upgradesInsecureRequests(final HtmlPage page) {
683 HtmlPage current = page;
684 while (current != null) {
685 final ContentSecurityPolicy csp = current.getContentSecurityPolicy();
686 if (csp != null && csp.hasUpgradeInsecureRequests()) {
687 return true;
688 }
689 current = parentPage(current);
690 }
691 return false;
692 }
693
694
695
696
697 private boolean hasUpgradeInsecureRequests() {
698 for (final Policy policy : getEnforcedPolicies()) {
699 if (policy.upgradeInsecureRequests()) {
700 return true;
701 }
702 }
703 return false;
704 }
705
706 private static HtmlPage parentPage(final HtmlPage page) {
707 final WebWindow window = page.getEnclosingWindow();
708 if (window instanceof FrameWindow frameWindow) {
709 return frameWindow.getEnclosingPage();
710 }
711 return null;
712 }
713
714 private static boolean isUpgradable(final URL url) {
715 final String protocol = url.getProtocol();
716 if (!"http".equals(protocol) && !"ws".equals(protocol)) {
717 return false;
718 }
719 return !UrlUtils.isLocalhostOrLoopback(url.getHost());
720 }
721
722 private static int effectivePort(final URL url) {
723 final int port = url.getPort();
724 return port == -1 ? url.getDefaultPort() : port;
725 }
726
727 private static URL upgrade(final URL url) {
728 final String protocol = "ws".equals(url.getProtocol()) ? "wss" : "https";
729 try {
730 URL upgraded = UrlUtils.getUrlWithNewProtocol(url, protocol);
731 if (url.getPort() == 80) {
732 upgraded = UrlUtils.getUrlWithNewPort(upgraded, -1);
733 }
734 return upgraded;
735 }
736 catch (final MalformedURLException e) {
737 return url;
738 }
739 }
740
741
742
743
744
745
746
747
748
749 public static boolean allowsWorker(final HtmlPage page, final URL url) {
750 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
751 if (csp == null) {
752 return true;
753 }
754
755 final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
756 final Optional<URI> origin = origin(page);
757 final Violation violation = new Violation(FetchDirectiveKind.WorkerSrc, blockedUri(url), null,
758 null, "", 0, 0);
759 final boolean allowed = csp.check(page, violation, policy -> policy.allowsWorker(target, origin));
760 firePendingViolationsIfNoScriptRunning(page);
761 return allowed;
762 }
763
764
765
766
767
768
769
770
771
772 public static boolean allowsBaseUri(final HtmlPage page, final URL url) {
773 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
774 if (csp == null) {
775 return true;
776 }
777
778 final URLWithScheme target = toUrlWithScheme(url);
779 final Optional<URI> origin = origin(page);
780 final Violation violation = new Violation(BASE_URI, withoutRef(url), null, null, "", 0, 0);
781 final boolean allowed = csp.check(page, violation,
782 policy -> policy.baseUri()
783 .map(directive -> Policy.doesUrlMatchSourceListInOrigin(target, directive, origin))
784 .orElse(true));
785 firePendingViolationsIfNoScriptRunning(page);
786 return allowed;
787 }
788
789
790
791
792
793
794
795
796
797
798
799 public static boolean allowsFormAction(final HtmlPage page, final URL url, final URL reportedUrl) {
800 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
801 if (csp == null) {
802 return true;
803 }
804
805 final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
806 final Optional<URI> origin = origin(page);
807 final Violation violation = new Violation(FORM_ACTION, blockedUri(reportedUrl), null, null, "", 0, 0);
808 final boolean redirected = isRedirect(url, reportedUrl);
809 final boolean allowed = csp.check(page, violation,
810 policy -> policy.allowsFormAction(target, origin, redirected));
811 firePendingViolationsIfNoScriptRunning(page);
812 return allowed;
813 }
814
815
816
817
818
819
820
821
822
823 public static boolean allowsEval(final HtmlPage page, final String source, final int lineNumber) {
824 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
825 if (csp == null) {
826 return true;
827 }
828
829 final Violation violation = new Violation(FetchDirectiveKind.ScriptSrc, BLOCKED_EVAL, source,
830 null, documentUrl(page), lineNumber, 0);
831 final boolean allowed = csp.check(page, violation, Policy::allowsEval);
832 firePendingViolationsIfNoScriptRunning(page);
833 return allowed;
834 }
835
836
837
838
839
840
841 public static void firePendingViolations() {
842 final List<Runnable> pending = PENDING_VIOLATIONS.get();
843 if (pending == null) {
844 return;
845 }
846
847
848 while (!pending.isEmpty()) {
849 pending.remove(0).run();
850 }
851 PENDING_VIOLATIONS.remove();
852 }
853
854
855
856
857
858 private static void firePendingViolationsIfNoScriptRunning(final HtmlPage page) {
859 final AbstractJavaScriptEngine<?> engine = page.getWebClient().getJavaScriptEngine();
860 if (engine == null || !engine.isScriptRunning()) {
861 firePendingViolations();
862 }
863 }
864
865 private boolean check(final HtmlPage page, final Violation violation, final Predicate<Policy> check) {
866 boolean allowed = true;
867 for (final Policy policy : getEnforcedPolicies()) {
868 if (!check.test(policy)) {
869 allowed = false;
870 report(page, policy, violation, SecurityPolicyViolationEvent.DISPOSITION_ENFORCE);
871 }
872 }
873 for (final Policy policy : getReportOnlyPolicies()) {
874 if (!check.test(policy)) {
875 report(page, policy, violation, SecurityPolicyViolationEvent.DISPOSITION_REPORT);
876 }
877 }
878 return allowed;
879 }
880
881
882
883
884
885 private static void report(final HtmlPage page, final Policy policy, final Violation violation,
886 final String disposition) {
887 final FetchDirectiveKind directive = violation.directive_;
888 final String effectiveDirective = violation.effectiveDirective_;
889 final String blockedUri = violation.blockedUri_;
890 final String source = violation.source_;
891 final DomElement element = violation.target_;
892 if (LOG.isWarnEnabled()) {
893 LOG.warn((SecurityPolicyViolationEvent.DISPOSITION_REPORT.equals(disposition) ? "[Report Only] " : "")
894 + "Content-Security-Policy violation: '" + effectiveDirective
895 + "' blocked '" + blockedUri + "' in '" + page.getUrl() + "' (policy '" + policy + "').");
896 }
897
898 String sample = "";
899 if (source != null && directive != null) {
900 final SourceExpressionDirective governing =
901 policy.getGoverningDirectiveForEffectiveDirective(directive).orElse(null);
902 if (governing != null && governing.reportSample()) {
903 sample = source.length() > SAMPLE_LENGTH ? source.substring(0, SAMPLE_LENGTH) : source;
904 }
905 }
906
907 final DomNode target = element != null && element.isAttachedToPage() ? element : page;
908 final int lineNumber = Math.max(0, violation.lineNumber_);
909 final int columnNumber = Math.max(0, violation.columnNumber_);
910 final String documentUrl = documentUrl(page);
911 final String sourceFile = violation.sourceFile_;
912 final String originalPolicy = policy.toString();
913 final int statusCode = page.getWebResponse() == null ? 0 : page.getWebResponse().getStatusCode();
914 final String finalSample = sample;
915
916 final ContentSecurityPolicyViolationListener listener =
917 page.getWebClient().getContentSecurityPolicyViolationListener();
918 if (listener != null) {
919 listener.violation(page, new ContentSecurityPolicyViolation(documentUrl, blockedUri,
920 effectiveDirective, originalPolicy, sourceFile, finalSample, lineNumber, columnNumber,
921 statusCode, SecurityPolicyViolationEvent.DISPOSITION_REPORT.equals(disposition)));
922 }
923
924
925
926 final ReportUriDirective reportUri = policy.deliveredViaMeta() || policy.reportTo().isPresent()
927 ? null : policy.reportUri().orElse(null);
928 if (reportUri != null && !reportUri.getUris().isEmpty()) {
929 final String report;
930 if (page.getWebClient().getBrowserVersion().hasFeature(CSP_REPORT_FIREFOX_FORMAT)) {
931 report = "{\"csp-report\":{"
932 + jsonMember("blocked-uri", blockedUri) + ","
933 + "\"column-number\":" + Math.max(1, columnNumber) + ","
934 + jsonMember("disposition", disposition) + ","
935 + jsonMember("document-uri", documentUrl) + ","
936 + jsonMember("effective-directive", effectiveDirective) + ","
937 + (lineNumber > 0 ? "\"line-number\":" + lineNumber + "," : "")
938 + jsonMember("original-policy", absoluteReportUris(page, originalPolicy, reportUri)) + ","
939 + jsonMember("referrer", "") + ","
940 + (StringUtils.isEmptyOrNull(finalSample) ? "" : jsonMember("script-sample", finalSample) + ",")
941 + (StringUtils.isEmptyOrNull(sourceFile) ? "" : jsonMember("source-file", sourceFile) + ",")
942 + "\"status-code\":" + statusCode + ","
943 + jsonMember("violated-directive", effectiveDirective)
944 + "}}";
945 }
946 else {
947 report = "{\"csp-report\":{"
948 + jsonMember("document-uri", documentUrl) + ","
949 + jsonMember("referrer", "") + ","
950 + jsonMember("violated-directive", effectiveDirective) + ","
951 + jsonMember("effective-directive", effectiveDirective) + ","
952 + jsonMember("original-policy", originalPolicy) + ","
953 + jsonMember("disposition", disposition) + ","
954 + jsonMember("blocked-uri", blockedUri) + ","
955 + (lineNumber > 0 ? "\"line-number\":" + lineNumber + "," : "")
956 + (columnNumber > 0 ? "\"column-number\":" + columnNumber + "," : "")
957 + (StringUtils.isEmptyOrNull(sourceFile) ? "" : jsonMember("source-file", sourceFile) + ",")
958 + "\"status-code\":" + statusCode + ","
959 + jsonMember("script-sample", finalSample)
960 + "}}";
961 }
962 final List<String> uris = new ArrayList<>(reportUri.getUris());
963 addPending(() -> sendReports(page, uris, report));
964 }
965
966 final WebWindow window = page.getEnclosingWindow();
967 if (window == null || !page.getWebClient().isJavaScriptEnabled()
968 || window.getScriptableObject() == null) {
969 return;
970 }
971
972 final Runnable fireEvent = () -> {
973 final SecurityPolicyViolationEvent event = new SecurityPolicyViolationEvent(target);
974 event.setDocumentURI(documentUrl);
975 event.setBlockedURI(blockedUri);
976 event.setEffectiveDirective(effectiveDirective);
977 event.setViolatedDirective(effectiveDirective);
978 event.setOriginalPolicy(originalPolicy);
979 event.setSourceFile(sourceFile);
980 event.setSample(finalSample);
981 event.setDisposition(disposition);
982 event.setStatusCode(statusCode);
983 event.setLineNumber(lineNumber);
984 event.setColumnNumber(columnNumber);
985
986 final EventTarget jsTarget = target.getScriptableObject();
987 ((JavaScriptEngine) page.getWebClient().getJavaScriptEngine())
988 .callSecured(cx -> jsTarget.fireEvent(event), page);
989 };
990
991
992
993
994 addPending(fireEvent);
995 }
996
997 private static void addPending(final Runnable runnable) {
998 List<Runnable> pending = PENDING_VIOLATIONS.get();
999 if (pending == null) {
1000 pending = new ArrayList<>();
1001 PENDING_VIOLATIONS.set(pending);
1002 }
1003 pending.add(runnable);
1004 }
1005
1006
1007
1008
1009
1010
1011 private static void sendReports(final HtmlPage page, final List<String> uris, final String report) {
1012 final WebClient webClient = page.getWebClient();
1013 if (!webClient.getOptions().isContentSecurityPolicyReportsEnabled()) {
1014 return;
1015 }
1016 for (final String uri : uris) {
1017 try {
1018 final URL url = page.getFullyQualifiedUrl(uri);
1019 final WebRequest request = new WebRequest(url, HttpMethod.POST);
1020 request.setAdditionalHeader(HttpHeader.CONTENT_TYPE, REPORT_CONTENT_TYPE);
1021 request.setCharset(UTF_8);
1022 request.setRequestBody(report);
1023 request.setFetchDestination(WebRequest.FetchDestination.REPORT);
1024 request.setFetchModeOverride(WebRequest.FetchMode.NO_CORS);
1025 request.setRequestingUrl(page.getUrl());
1026 request.setSiteForCookies(page.getSiteForCookiesUrl());
1027 webClient.loadWebResponse(request);
1028 }
1029 catch (final IOException | RuntimeException e) {
1030 if (LOG.isInfoEnabled()) {
1031 LOG.info("Sending the Content-Security-Policy violation report to '" + uri + "' failed", e);
1032 }
1033 }
1034 }
1035 }
1036
1037
1038
1039
1040 private static String absoluteReportUris(final HtmlPage page, final String policy,
1041 final ReportUriDirective reportUri) {
1042 final StringBuilder uris = new StringBuilder("report-uri");
1043 for (final String uri : reportUri.getUris()) {
1044 String absolute = uri;
1045 try {
1046 absolute = page.getFullyQualifiedUrl(uri).toExternalForm();
1047 }
1048 catch (final MalformedURLException e) {
1049
1050 }
1051 uris.append(' ').append(absolute);
1052 }
1053
1054 final String[] parts = policy.split(";", -1);
1055 for (int i = 0; i < parts.length; i++) {
1056 final String trimmed = parts[i].trim();
1057 if (trimmed.toLowerCase(Locale.ROOT).startsWith("report-uri")) {
1058 final String leading = parts[i].substring(0, parts[i].indexOf(trimmed));
1059 parts[i] = leading + uris;
1060 }
1061 }
1062 return String.join(";", parts);
1063 }
1064
1065 private static String jsonMember(final String name, final String value) {
1066 final StringBuilder json = new StringBuilder();
1067 json.append('"').append(name).append("\":\"");
1068 if (value != null) {
1069 for (int i = 0; i < value.length(); i++) {
1070 final char c = value.charAt(i);
1071 switch (c) {
1072 case '"':
1073 json.append("\\\"");
1074 break;
1075 case '\\':
1076 json.append("\\\\");
1077 break;
1078 case '\n':
1079 json.append("\\n");
1080 break;
1081 case '\r':
1082 json.append("\\r");
1083 break;
1084 case '\t':
1085 json.append("\\t");
1086 break;
1087 default:
1088 if (c < 0x20) {
1089 json.append(String.format("\\u%04x", (int) c));
1090 }
1091 else {
1092 json.append(c);
1093 }
1094 }
1095 }
1096 }
1097 return json.append('"').toString();
1098 }
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110 public Set<String> getSandboxTokens() {
1111 Set<String> tokens = null;
1112 for (final Policy policy : getEnforcedPolicies()) {
1113 final SandboxDirective sandbox = policy.deliveredViaMeta() ? null : policy.sandbox().orElse(null);
1114 if (sandbox != null) {
1115 final Set<String> policyTokens = new HashSet<>();
1116 for (final String value : sandbox.getValues()) {
1117 policyTokens.add(value.toLowerCase(Locale.ROOT));
1118 }
1119 if (tokens == null) {
1120 tokens = policyTokens;
1121 }
1122 else {
1123 tokens.retainAll(policyTokens);
1124 }
1125 }
1126 }
1127 return tokens;
1128 }
1129
1130 private List<Policy> getEnforcedPolicies() {
1131 if (enforcedPolicies_ == null) {
1132 final List<Policy> policies = parse(enforced_);
1133 final Policy.MetaCommaHandling commaHandling = metaSinglePolicy_
1134 ? Policy.MetaCommaHandling.SINGLE_POLICY : Policy.MetaCommaHandling.SPLIT;
1135 for (final String serialized : meta_) {
1136 policies.addAll(Policy.parseSerializedCSPList(serialized,
1137 Policy.PolicyListErrorConsumer.ignored, commaHandling).getPolicies());
1138 }
1139 enforcedPolicies_ = policies;
1140 }
1141 return enforcedPolicies_;
1142 }
1143
1144 private List<Policy> getReportOnlyPolicies() {
1145 if (reportOnlyPolicies_ == null) {
1146 reportOnlyPolicies_ = parse(reportOnly_);
1147 }
1148 return reportOnlyPolicies_;
1149 }
1150
1151 private static List<Policy> parse(final List<String> serializedPolicies) {
1152 final List<Policy> policies = new ArrayList<>();
1153 for (final String serialized : serializedPolicies) {
1154 policies.addAll(Policy.parseSerializedCSPList(serialized,
1155 Policy.PolicyListErrorConsumer.ignored).getPolicies());
1156 }
1157 return policies;
1158 }
1159
1160
1161
1162
1163
1164
1165 private static Violation inlineViolation(final HtmlPage page, final FetchDirectiveKind directive,
1166 final String source, final DomElement element) {
1167 if (Context.getCurrentContext() != null) {
1168 final ScriptStackElement[] stack = new EvaluatorException("csp").getScriptStack();
1169 if (stack.length > 0) {
1170 return new Violation(directive, BLOCKED_INLINE, source, element,
1171 stack[0].fileName, Math.max(0, stack[0].lineNumber), 0);
1172 }
1173 }
1174 return new Violation(directive, BLOCKED_INLINE, source, element,
1175 documentUrl(page), element.getStartLineNumber(), element.getStartColumnNumber());
1176 }
1177
1178
1179
1180
1181
1182 private static Optional<String> nonce(final DomElement element) {
1183 String nonce = element.getNonce();
1184 final SgmlPage page = element.getPage();
1185 if (page != null && page.getWebClient().getBrowserVersion().hasFeature(CSP_NONCE_TRIMMED)) {
1186 nonce = nonce.trim();
1187 }
1188 if (nonce.isEmpty() || !isNonceable(element)) {
1189 return Optional.empty();
1190 }
1191 return Optional.of(nonce);
1192 }
1193
1194
1195
1196
1197
1198 private static boolean isNonceable(final DomElement element) {
1199 for (final DomAttr attr : element.getAttributesMap().values()) {
1200 if (containsScriptOrStyle(attr.getName()) || containsScriptOrStyle(attr.getValue())) {
1201 return false;
1202 }
1203 }
1204 return true;
1205 }
1206
1207 private static boolean containsScriptOrStyle(final String value) {
1208 final String lower = value.toLowerCase(Locale.ROOT);
1209 return lower.contains("<script") || lower.contains("<style");
1210 }
1211
1212
1213
1214
1215
1216
1217
1218
1219 public static void hideNonceIfNeeded(final DomElement element) {
1220 final HtmlPage page = element.getHtmlPageOrNull();
1221 if (page == null) {
1222 return;
1223 }
1224 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
1225 if (csp == null) {
1226 return;
1227 }
1228 if (csp.enforced_.isEmpty()
1229 && (csp.reportOnly_.isEmpty()
1230 || page.getWebClient().getBrowserVersion().hasFeature(CSP_NONCE_HIDING_ENFORCED_ONLY))) {
1231 return;
1232 }
1233
1234 final String nonce = element.getAttributeDirect(DomElement.NONCE_ATTRIBUTE);
1235 if (ATTRIBUTE_NOT_DEFINED == nonce || nonce.isEmpty()) {
1236 return;
1237 }
1238 element.hideNonce();
1239 }
1240
1241
1242
1243
1244
1245 private static boolean isParserInserted(final DomElement element) {
1246 return element.getStartLineNumber() != -1;
1247 }
1248
1249 private static String documentUrl(final HtmlPage page) {
1250 return withoutRef(page.getUrl());
1251 }
1252
1253 private static String withoutRef(final URL url) {
1254 final String externalForm = url.toExternalForm();
1255 final int hashPos = externalForm.indexOf('#');
1256 if (hashPos == -1) {
1257 return externalForm;
1258 }
1259 return externalForm.substring(0, hashPos);
1260 }
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282 static URLWithScheme toUrlWithScheme(final URL url) {
1283 final String scheme = url.getProtocol().toLowerCase(Locale.ROOT);
1284 final String host = url.getHost();
1285 if (host == null || host.isEmpty()) {
1286 final String externalForm = url.toExternalForm();
1287 return new GUID(scheme, externalForm.substring(externalForm.indexOf(':') + 1));
1288 }
1289
1290 int port = url.getPort();
1291 if (port == -1) {
1292 port = URI.defaultPortForProtocol(scheme);
1293 }
1294 return new URI(scheme, host.toLowerCase(Locale.ROOT), port, url.getPath());
1295 }
1296
1297
1298
1299
1300
1301
1302 private static boolean isRedirect(final URL url, final URL reportedUrl) {
1303 return !url.toExternalForm().equals(reportedUrl.toExternalForm());
1304 }
1305
1306
1307
1308
1309
1310 private static String blockedUri(final URL url) {
1311 final String host = url.getHost();
1312 if (host == null || host.isEmpty()) {
1313 return url.getProtocol();
1314 }
1315 return withoutRef(url);
1316 }
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326 private static String navigationBlockedUri(final HtmlPage page, final URL url) {
1327 final String host = url.getHost();
1328 if (host == null || host.isEmpty()) {
1329 return "";
1330 }
1331 if (UrlUtils.isSameOrigin(selfUrl(page), url)) {
1332 return withoutRef(url);
1333 }
1334
1335 final String protocol = url.getProtocol();
1336 final int port = url.getPort();
1337 if (port == -1 || port == url.getDefaultPort()) {
1338 return protocol + "://" + host;
1339 }
1340 return protocol + "://" + host + ":" + port;
1341 }
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351 private static String objectBlockedUri(final HtmlPage page, final URL url) {
1352 final String host = url.getHost();
1353 if (host == null || host.isEmpty()) {
1354 return url.getProtocol();
1355 }
1356 return navigationBlockedUri(page, url);
1357 }
1358
1359 private static Optional<URI> origin(final HtmlPage page) {
1360 return URI.parseURI(selfUrl(page).toExternalForm());
1361 }
1362
1363
1364
1365
1366 private static URL selfUrl(final HtmlPage page) {
1367 final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
1368 if (csp != null && csp.selfUrl_ != null) {
1369 return csp.selfUrl_;
1370 }
1371 return page.getUrl();
1372 }
1373
1374
1375
1376
1377 private static final class Violation {
1378 private final FetchDirectiveKind directive_;
1379 private final String effectiveDirective_;
1380 private final String blockedUri_;
1381 private final String source_;
1382 private final DomElement target_;
1383 private final String sourceFile_;
1384 private final int lineNumber_;
1385 private final int columnNumber_;
1386
1387 Violation(final FetchDirectiveKind directive, final String blockedUri, final String source,
1388 final DomElement target, final String sourceFile, final int lineNumber, final int columnNumber) {
1389 directive_ = directive;
1390 effectiveDirective_ = directive.getRepr();
1391 blockedUri_ = blockedUri;
1392 source_ = source;
1393 target_ = target;
1394 sourceFile_ = sourceFile;
1395 lineNumber_ = lineNumber;
1396 columnNumber_ = columnNumber;
1397 }
1398
1399
1400
1401
1402 Violation(final String effectiveDirective, final String blockedUri, final String source,
1403 final DomElement target, final String sourceFile, final int lineNumber, final int columnNumber) {
1404 directive_ = null;
1405 effectiveDirective_ = effectiveDirective;
1406 blockedUri_ = blockedUri;
1407 source_ = source;
1408 target_ = target;
1409 sourceFile_ = sourceFile;
1410 lineNumber_ = lineNumber;
1411 columnNumber_ = columnNumber;
1412 }
1413 }
1414 }