-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPolicy.java
More file actions
1599 lines (1484 loc) · 68.8 KB
/
Policy.java
File metadata and controls
1599 lines (1484 loc) · 68.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2023-2026 Ronald Brill.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.htmlunit.csp;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import org.htmlunit.csp.directive.FrameAncestorsDirective;
import org.htmlunit.csp.directive.HostSourceDirective;
import org.htmlunit.csp.directive.PluginTypesDirective;
import org.htmlunit.csp.directive.ReportUriDirective;
import org.htmlunit.csp.directive.RequireTrustedTypesForDirective;
import org.htmlunit.csp.directive.SandboxDirective;
import org.htmlunit.csp.directive.SourceExpressionDirective;
import org.htmlunit.csp.directive.TrustedTypesDirective;
import org.htmlunit.csp.url.GUID;
import org.htmlunit.csp.url.URI;
import org.htmlunit.csp.url.URLWithScheme;
import org.htmlunit.csp.value.Hash;
import org.htmlunit.csp.value.Host;
import org.htmlunit.csp.value.MediaType;
import org.htmlunit.csp.value.RFC7230Token;
import org.htmlunit.csp.value.Scheme;
/**
* Represents a single parsed Content Security Policy.
* <p>
* A {@code Policy} is created by parsing a serialized CSP string via
* {@link #parseSerializedCSP(String, PolicyErrorConsumer)} or by parsing a comma-separated
* list of policies via {@link #parseSerializedCSPList(String, PolicyListErrorConsumer)}.
* </p>
* <p>
* The class preserves the original case, order, duplicate directives, unrecognized directives,
* and unrecognized values to support round-tripping. Whitespace and empty directives/policies
* are not preserved.
* </p>
* <p>
* High-level query methods such as {@link #allowsExternalScript} and {@link #allowsInlineScript}
* implement the matching algorithms defined in the
* <a href="https://w3c.github.io/webappsec-csp/">CSP specification</a>.
* </p>
*
* @see <a href="https://w3c.github.io/webappsec-csp/">W3C Content Security Policy Level 3</a>
*/
public final class Policy {
// Things we don't preserve:
// - Whitespace
// - Empty directives or policies (as in `; ;` or `, ,`)
// Things we do preserve:
// - Source-expression lists being genuinely empty vs consisting of 'none'
// - Case (as in lowercase vs uppercase)
// - Order
// - Duplicate directives
// - Unrecognized directives
// - Values in directives which forbid them
// - Duplicate values
// - Unrecognized values
private final List<NamedDirective> directives_ = new ArrayList<>();
private boolean blockAllMixedContent_;
private SourceExpressionDirective baseUri_;
private SourceExpressionDirective formAction_;
private FrameAncestorsDirective frameAncestors_;
private SourceExpressionDirective navigateTo_;
private PluginTypesDirective pluginTypes_;
private TrustedTypesDirective trustedTypes_;
private RequireTrustedTypesForDirective requireTrustedTypesFor_;
private FetchDirectiveKind prefetchSrc_;
private RFC7230Token reportTo_;
private ReportUriDirective reportUri_;
private SandboxDirective sandbox_;
private boolean upgradeInsecureRequests_;
private final EnumMap<FetchDirectiveKind, SourceExpressionDirective> fetchDirectives_
= new EnumMap<>(FetchDirectiveKind.class);
private Policy() {
// pass
}
/**
* Parses a serialized CSP list (comma-separated policies) into a {@link PolicyList}.
* <p>
* Implements the
* <a href="https://w3c.github.io/webappsec-csp/#parse-serialized-policy-list">parse a
* serialized CSP list</a> algorithm. The input must be an ASCII string. Empty policies
* (those that contain no directives) are omitted from the resulting list.
* </p>
*
* @param serialized the comma-separated serialized CSP list to parse
* @param policyListErrorConsumer a consumer that receives any errors or warnings
* encountered during parsing
* @return the parsed {@link PolicyList}
* @throws IllegalArgumentException if {@code serialized} contains non-ASCII characters
*/
public static PolicyList parseSerializedCSPList(final String serialized,
final PolicyListErrorConsumer policyListErrorConsumer) {
// "A serialized CSP list is an ASCII string"
enforceAscii(serialized);
final List<Policy> policies = new ArrayList<>();
// java's lambdas are dumb
final int[] index = {0};
final PolicyErrorConsumer policyErrorConsumer =
(Severity severity, String message, int directiveIndex, int valueIndex) ->
policyListErrorConsumer.add(severity, message, index[0], directiveIndex, valueIndex);
// https://infra.spec.whatwg.org/#split-on-commas
for (final String token : serialized.split(",")) {
final Policy policy = parseSerializedCSP(token, policyErrorConsumer);
if (policy.directives_.isEmpty()) {
++index[0];
continue;
}
policies.add(policy);
++index[0];
}
return new PolicyList(policies);
}
/**
* Parses a single serialized CSP string into a {@link Policy}.
* <p>
* Implements the
* <a href="https://w3c.github.io/webappsec-csp/#parse-serialized-policy">parse a
* serialized CSP</a> algorithm. The input must be an ASCII string and must not
* contain commas; for comma-separated CSP lists use
* {@link #parseSerializedCSPList(String, PolicyListErrorConsumer)}.
* </p>
*
* @param serialized the serialized CSP string to parse (must not contain commas)
* @param policyErrorConsumer a consumer that receives any errors or warnings
* encountered during parsing
* @return the parsed {@link Policy}
* @throws IllegalArgumentException if {@code serialized} contains non-ASCII characters
* or contains a comma
*/
public static Policy parseSerializedCSP(final String serialized, final PolicyErrorConsumer policyErrorConsumer) {
// "A serialized CSP is an ASCII string", and browsers do in fact reject CSPs which contain non-ASCII characters
enforceAscii(serialized);
if (serialized.contains(",")) {
// This is not quite per spec, but
throw new IllegalArgumentException(
"Serialized CSPs cannot contain commas - you may have wanted parseSerializedCSPList");
}
// java's lambdas are dumb
final int[] index = {0};
final Directive.DirectiveErrorConsumer directiveErrorConsumer =
(Severity severity, String message, int valueIndex) ->
policyErrorConsumer.add(severity, message, index[0], valueIndex);
final Policy policy = new Policy();
// https://infra.spec.whatwg.org/#strictly-split
for (final String token : serialized.split(";")) {
final String trimmedLeadingAndTrailingWhitespace = Utils.trimAsciiWhitespace(token);
if (trimmedLeadingAndTrailingWhitespace.isEmpty()) {
++index[0];
continue;
}
final String directiveName = Utils.extractLeadingToken(trimmedLeadingAndTrailingWhitespace);
// Note: we do not lowercase directive names or
// skip duplicates during parsing, to allow round-tripping even invalid policies
final String remainingToken = trimmedLeadingAndTrailingWhitespace.substring(directiveName.length());
final List<String> directiveValues = Utils.splitOnAsciiWhitespace(remainingToken);
policy.add(directiveName, directiveValues, directiveErrorConsumer);
++index[0];
}
return policy;
}
// We do not provide a generic method for updating an existing directive in-place.
// Just remove the existing one and add it back.
private Directive add(final String name, final List<String> values,
final Directive.DirectiveErrorConsumer directiveErrorConsumer) {
enforceAscii(name);
// the parser will never hit these errors by construction, but use of the manipulation APIs can
if (Directive.containsNonDirectiveCharacter(name)) {
throw new IllegalArgumentException("directive names must not contain whitespace, ',', or ';'");
}
if (name.isEmpty()) {
throw new IllegalArgumentException("directive names must not be empty");
}
boolean wasDupe = false;
final Directive newDirective;
final String lowercaseDirectiveName = name.toLowerCase(Locale.ROOT);
switch (lowercaseDirectiveName) {
case "base-uri":
// https://w3c.github.io/webappsec-csp/#directive-base-uri
final SourceExpressionDirective baseUriDirective
= new SourceExpressionDirective(values, directiveErrorConsumer);
if (baseUri_ == null) {
baseUri_ = baseUriDirective;
}
else {
wasDupe = true;
}
newDirective = baseUriDirective;
break;
case "block-all-mixed-content":
// https://www.w3.org/TR/mixed-content/#strict-opt-in
if (blockAllMixedContent_) {
wasDupe = true;
}
else {
if (!values.isEmpty()) {
directiveErrorConsumer.add(Severity.Error,
"The block-all-mixed-content directive does not support values", 0);
}
blockAllMixedContent_ = true;
}
newDirective = new Directive(values);
break;
case "form-action":
// https://w3c.github.io/webappsec-csp/#directive-form-action
final SourceExpressionDirective formActionDirective
= new SourceExpressionDirective(values, directiveErrorConsumer);
if (formAction_ == null) {
formAction_ = formActionDirective;
}
else {
wasDupe = true;
}
newDirective = formActionDirective;
break;
case "frame-ancestors":
// https://w3c.github.io/webappsec-csp/#directive-frame-ancestors
// TODO contemplate warning for paths, which are always ignored: frame-ancestors only matches
// against origins: https://w3c.github.io/webappsec-csp/#frame-ancestors-navigation-response
final FrameAncestorsDirective frameAncestorsDirective
= new FrameAncestorsDirective(values, directiveErrorConsumer);
if (frameAncestors_ == null) {
frameAncestors_ = frameAncestorsDirective;
}
else {
wasDupe = true;
}
newDirective = frameAncestorsDirective;
break;
case "navigate-to":
// https://w3c.github.io/webappsec-csp/#directive-navigate-to
// For some ungodly reason "navigate-to" is a list of source expressions while "frame-ancestors" is not
// There is no logic here
final SourceExpressionDirective navigateToDirective
= new SourceExpressionDirective(values, directiveErrorConsumer);
if (navigateTo_ == null) {
navigateTo_ = navigateToDirective;
}
else {
wasDupe = true;
}
newDirective = navigateToDirective;
break;
case "plugin-types":
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/plugin-types
directiveErrorConsumer.add(Severity.Warning, "The plugin-types directive has been deprecated", -1);
final PluginTypesDirective pluginTypesDirective
= new PluginTypesDirective(values, directiveErrorConsumer);
if (pluginTypes_ == null) {
pluginTypes_ = pluginTypesDirective;
}
else {
wasDupe = true;
}
newDirective = pluginTypesDirective;
break;
case "report-to":
// https://w3c.github.io/webappsec-csp/#directive-report-to
if (reportTo_ == null) {
if (values.isEmpty()) {
directiveErrorConsumer.add(Severity.Error, "The report-to directive requires a value", -1);
}
else if (values.size() == 1) {
final String token = values.get(0);
final Optional<RFC7230Token> matched = RFC7230Token.parseRFC7230Token(token);
if (matched.isPresent()) {
reportTo_ = matched.get();
}
else {
directiveErrorConsumer.add(Severity.Error,
"Expecting RFC 7230 token but found \"" + token + "\"", 0);
}
}
else {
directiveErrorConsumer.add(Severity.Error,
"The report-to directive requires exactly one value (found " + values.size() + ")", 1);
}
}
else {
wasDupe = true;
}
newDirective = new Directive(values);
break;
case "referrer":
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/referrer
directiveErrorConsumer.add(Severity.Warning,
"The referrer directive has been deprecated in favor of the Referrer-Policy header",
-1);
// We don't currently handle it further than this.
newDirective = new Directive(Collections.emptyList());
break;
case "report-uri":
// https://w3c.github.io/webappsec-csp/#directive-report-uri
directiveErrorConsumer.add(Severity.Warning,
"The report-uri directive has been deprecated in favor of the new report-to directive", -1);
final ReportUriDirective reportUriDirective = new ReportUriDirective(values, directiveErrorConsumer);
if (reportUri_ == null) {
reportUri_ = reportUriDirective;
}
else {
wasDupe = true;
}
newDirective = reportUriDirective;
break;
case "sandbox":
// https://w3c.github.io/webappsec-csp/#directive-sandbox
final SandboxDirective sandboxDirective = new SandboxDirective(values, directiveErrorConsumer);
if (sandbox_ == null) {
sandbox_ = sandboxDirective;
}
else {
wasDupe = true;
}
newDirective = sandboxDirective;
break;
case "trusted-types":
// https://w3c.github.io/trusted-types/dist/spec/#trusted-types-csp-directive
final TrustedTypesDirective trustedTypesDirective =
new TrustedTypesDirective(values, directiveErrorConsumer);
if (trustedTypes_ == null) {
trustedTypes_ = trustedTypesDirective;
}
else {
wasDupe = true;
}
newDirective = trustedTypesDirective;
break;
case "require-trusted-types-for":
// https://w3c.github.io/trusted-types/dist/spec/#require-trusted-types-for-csp-directive
final RequireTrustedTypesForDirective requireTrustedTypesForDirective =
new RequireTrustedTypesForDirective(values, directiveErrorConsumer);
if (requireTrustedTypesFor_ == null) {
requireTrustedTypesFor_ = requireTrustedTypesForDirective;
}
else {
wasDupe = true;
}
newDirective = requireTrustedTypesForDirective;
break;
case "upgrade-insecure-requests":
// https://www.w3.org/TR/upgrade-insecure-requests/#delivery
if (upgradeInsecureRequests_) {
wasDupe = true;
}
else {
if (!values.isEmpty()) {
directiveErrorConsumer.add(Severity.Error,
"The upgrade-insecure-requests directive does not support values", 0);
}
upgradeInsecureRequests_ = true;
}
newDirective = new Directive(values);
break;
default:
if (!Directive.IS_DIRECTIVE_NAME.test(name)) {
directiveErrorConsumer.add(Severity.Error,
"Directive name " + name
+ " contains characters outside the range ALPHA / DIGIT / \"-\"", -1);
newDirective = new Directive(values);
break;
}
final FetchDirectiveKind fetchDirectiveKind = FetchDirectiveKind.fromString(lowercaseDirectiveName);
if (fetchDirectiveKind != null) {
if (FetchDirectiveKind.PrefetchSrc == fetchDirectiveKind) {
directiveErrorConsumer.add(Severity.Warning,
"The prefetch-src directive has been deprecated", -1);
}
final SourceExpressionDirective thisDirective
= new SourceExpressionDirective(values, directiveErrorConsumer);
if (fetchDirectives_.containsKey(fetchDirectiveKind)) {
wasDupe = true;
}
else {
fetchDirectives_.put(fetchDirectiveKind, thisDirective);
}
newDirective = thisDirective;
break;
}
directiveErrorConsumer.add(Severity.Warning, "Unrecognized directive " + lowercaseDirectiveName, -1);
newDirective = new Directive(values);
break;
}
directives_.add(new NamedDirective(name, newDirective));
if (wasDupe) {
directiveErrorConsumer.add(Severity.Warning, "Duplicate directive " + lowercaseDirectiveName, -1);
}
return newDirective;
}
/**
* Serializes this policy back to its string representation.
* <p>
* Directives are separated by {@code "; "}. The original case, order, and values
* (including duplicates and unrecognized entries) are preserved.
* </p>
*
* @return the serialized CSP string
*/
@Override
public String toString() {
final StringBuilder out = new StringBuilder();
boolean first = true;
for (final NamedDirective directive : directives_) {
if (!first) {
out.append("; "); // The whitespace is not strictly necessary but is probably valuable
}
first = false;
out.append(directive.name_);
for (final String value : directive.directive_.getValues()) {
out.append(' ').append(value);
}
}
return out.toString();
}
// Accessors
/**
* Returns the parsed {@code base-uri} directive, if present.
*
* @return an {@link Optional} containing the {@link SourceExpressionDirective} for
* {@code base-uri}, or empty if the directive was not specified
* @see <a href="https://w3c.github.io/webappsec-csp/#directive-base-uri">base-uri directive</a>
*/
public Optional<SourceExpressionDirective> baseUri() {
return Optional.ofNullable(baseUri_);
}
/**
* Returns whether the {@code block-all-mixed-content} directive is present.
*
* @return {@code true} if the policy contains the {@code block-all-mixed-content} directive
* @see <a href="https://www.w3.org/TR/mixed-content/#strict-opt-in">block-all-mixed-content</a>
*/
public boolean blockAllMixedContent() {
return blockAllMixedContent_;
}
/**
* Returns the parsed {@code form-action} directive, if present.
*
* @return an {@link Optional} containing the {@link SourceExpressionDirective} for
* {@code form-action}, or empty if the directive was not specified
* @see <a href="https://w3c.github.io/webappsec-csp/#directive-form-action">form-action directive</a>
*/
public Optional<SourceExpressionDirective> formAction() {
return Optional.ofNullable(formAction_);
}
/**
* Returns the parsed {@code frame-ancestors} directive, if present.
*
* @return an {@link Optional} containing the {@link FrameAncestorsDirective},
* or empty if the directive was not specified
* @see <a href="https://w3c.github.io/webappsec-csp/#directive-frame-ancestors">frame-ancestors directive</a>
*/
public Optional<FrameAncestorsDirective> frameAncestors() {
return Optional.ofNullable(frameAncestors_);
}
/**
* Returns the parsed {@code navigate-to} directive, if present.
*
* @return an {@link Optional} containing the {@link SourceExpressionDirective} for
* {@code navigate-to}, or empty if the directive was not specified
* @see <a href="https://w3c.github.io/webappsec-csp/#directive-navigate-to">navigate-to directive</a>
*/
public Optional<SourceExpressionDirective> navigateTo() {
return Optional.ofNullable(navigateTo_);
}
/**
* Returns the parsed {@code plugin-types} directive, if present.
* <p>Note: the {@code plugin-types} directive has been deprecated.</p>
*
* @return an {@link Optional} containing the {@link PluginTypesDirective},
* or empty if the directive was not specified
*/
public Optional<PluginTypesDirective> pluginTypes() {
return Optional.ofNullable(pluginTypes_);
}
/**
* Returns the {@code prefetch-src} fetch directive kind, if present.
* <p>Note: the {@code prefetch-src} directive has been deprecated. The actual parsed
* directive data is available via {@link #getFetchDirective(FetchDirectiveKind)} with
* {@link FetchDirectiveKind#PrefetchSrc}.</p>
*
* @return an {@link Optional} containing the {@link FetchDirectiveKind} for
* {@code prefetch-src}, or empty if not present
*/
public Optional<FetchDirectiveKind> prefetchSrc() {
return Optional.ofNullable(prefetchSrc_);
}
/**
* Returns the parsed {@code report-to} directive value, if present.
*
* @return an {@link Optional} containing the {@link RFC7230Token} representing the
* report-to group name, or empty if the directive was not specified
* @see <a href="https://w3c.github.io/webappsec-csp/#directive-report-to">report-to directive</a>
*/
public Optional<RFC7230Token> reportTo() {
return Optional.ofNullable(reportTo_);
}
/**
* Returns the parsed {@code report-uri} directive, if present.
* <p>Note: the {@code report-uri} directive has been deprecated in favor of
* {@code report-to}.</p>
*
* @return an {@link Optional} containing the {@link ReportUriDirective},
* or empty if the directive was not specified
* @see <a href="https://w3c.github.io/webappsec-csp/#directive-report-uri">report-uri directive</a>
*/
public Optional<ReportUriDirective> reportUri() {
return Optional.ofNullable(reportUri_);
}
/**
* Returns the parsed {@code sandbox} directive, if present.
*
* @return an {@link Optional} containing the {@link SandboxDirective},
* or empty if the directive was not specified
* @see <a href="https://w3c.github.io/webappsec-csp/#directive-sandbox">sandbox directive</a>
*/
public Optional<SandboxDirective> sandbox() {
return Optional.ofNullable(sandbox_);
}
/**
* Returns the parsed {@code trusted-types} directive, if present.
*
* @return an {@link Optional} containing the {@link TrustedTypesDirective},
* or empty if the directive was not specified
* @see <a href="https://w3c.github.io/trusted-types/dist/spec/#trusted-types-csp-directive">
* trusted-types directive</a>
*/
public Optional<TrustedTypesDirective> trustedTypes() {
return Optional.ofNullable(trustedTypes_);
}
/**
* Indicates if wildcard policy names are permitted in the trusted-types directive.
* When true, any policy name is allowed, which may reduce security.
*
* @return true if wildcard policy names (*) are permitted, false if not present or not permitted
*/
public boolean allowsWildcardPolicyNames() {
return trustedTypes_ != null && trustedTypes_.allowsWildcardPolicyNames();
}
/**
* Returns the parsed {@code require-trusted-types-for} directive, if present.
*
* @return an {@link Optional} containing the {@link RequireTrustedTypesForDirective},
* or empty if the directive was not specified
* @see <a href="https://w3c.github.io/trusted-types/dist/spec/#require-trusted-types-for-csp-directive">
* require-trusted-types-for directive</a>
*/
public Optional<RequireTrustedTypesForDirective> requireTrustedTypesFor() {
return Optional.ofNullable(requireTrustedTypesFor_);
}
/**
* Returns whether the {@code upgrade-insecure-requests} directive is present.
*
* @return {@code true} if the policy contains the {@code upgrade-insecure-requests} directive
* @see <a href="https://www.w3.org/TR/upgrade-insecure-requests/#delivery">
* upgrade-insecure-requests</a>
*/
public boolean upgradeInsecureRequests() {
return upgradeInsecureRequests_;
}
/**
* Returns the parsed fetch directive of the specified kind, if present.
* <p>
* Fetch directives include {@code default-src}, {@code script-src}, {@code style-src},
* {@code img-src}, {@code font-src}, {@code connect-src}, {@code media-src},
* {@code object-src}, {@code frame-src}, {@code child-src}, {@code worker-src},
* {@code manifest-src}, and their {@code -elem} / {@code -attr} variants.
* </p>
*
* @param kind the {@link FetchDirectiveKind} to look up
* @return an {@link Optional} containing the {@link SourceExpressionDirective} for the
* requested fetch directive, or empty if not present
*/
public Optional<SourceExpressionDirective> getFetchDirective(final FetchDirectiveKind kind) {
return Optional.ofNullable(fetchDirectives_.get(kind));
}
// High-level querying
/**
* Determines whether this policy allows loading an external script.
* <p>
* For each argument, if the value provided is {@link Optional#empty()}, this method
* returns {@code true} only if there is no value for the {@code Optional.of()} case
* of that parameter which would cause it to return {@code false}.
* </p>
* <p>
* Take care with {@code integrity}: a script can be allowed by CSP but blocked by
* <a href="https://www.w3.org/TR/SRI/">Subresource Integrity</a> if its integrity is wrong.
* Also note that "the URL" is somewhat fuzzy because of redirects.
* </p>
*
* @param nonce the nonce attribute value of the script element, if any
* @param integrity the integrity attribute value (SRI metadata), if any
* @param scriptUrl the URL of the external script, if known
* @param parserInserted whether the script element is parser-inserted;
* {@link Optional#empty()} if unknown
* @param origin the origin of the protected resource, if known
* @return {@code true} if this policy allows the external script
* @see <a href="https://w3c.github.io/webappsec-csp/#script-pre-request">
* script-pre-request check</a>
* @see <a href="https://w3c.github.io/webappsec-csp/#script-post-request">
* script-post-request check</a>
*/
public boolean allowsExternalScript(
final Optional<String> nonce,
final Optional<String> integrity,
final Optional<? extends URLWithScheme> scriptUrl,
final Optional<Boolean> parserInserted,
final Optional<? extends URLWithScheme> origin) {
if (sandbox_ != null && !sandbox_.allowScripts()) {
return false;
}
// Effective directive is "script-src-elem" per
// https://w3c.github.io/webappsec-csp/#effective-directive-for-a-request
final SourceExpressionDirective directive =
getGoverningDirectiveForEffectiveDirective(FetchDirectiveKind.ScriptSrcElem).orElse(null);
if (directive == null) {
return true;
}
if (nonce.isPresent()) {
final String actualNonce = nonce.get();
if (actualNonce.length() > 0
&& directive.getNonces().stream().anyMatch(n -> n.base64ValuePart().equals(actualNonce))) {
return true;
}
}
if (integrity.isPresent() && !directive.getHashes().isEmpty()) {
final String integritySources = integrity.get();
boolean bypassDueToIntegrityMatch = true;
boolean atLeastOneValidIntegrity = false;
// https://www.w3.org/TR/SRI/#parse-metadata
for (final String source : Utils.splitOnAsciiWhitespace(integritySources)) {
final Optional<Hash> parsedIntegritySource = Hash.parseHash("'" + source + "'");
if (parsedIntegritySource.isEmpty()) {
continue;
}
if (!directive.getHashes().contains(parsedIntegritySource.get())) {
bypassDueToIntegrityMatch = false;
break;
}
atLeastOneValidIntegrity = true;
}
if (atLeastOneValidIntegrity && bypassDueToIntegrityMatch) {
return true;
}
}
if (directive.strictDynamic()) {
// if not the parameter is not supplied, we have to assume the worst case
return !parserInserted.orElse(true);
}
return scriptUrl.filter(urlWithScheme ->
doesUrlMatchSourceListInOrigin(urlWithScheme, directive, origin)).isPresent();
}
/**
* Determines whether this policy allows an inline {@code <script>} element.
*
* @param nonce the nonce attribute value of the script element, if any
* @param source the text content of the inline script, if known (used for hash matching)
* @param parserInserted whether the script element is parser-inserted;
* {@link Optional#empty()} if unknown
* @return {@code true} if this policy allows the inline script
* @see <a href="https://w3c.github.io/webappsec-csp/#should-block-inline">
* should block inline check</a>
*/
public boolean allowsInlineScript(final Optional<String> nonce,
final Optional<String> source, final Optional<Boolean> parserInserted) {
if (sandbox_ != null && !sandbox_.allowScripts()) {
return false;
}
return doesElementMatchSourceListForTypeAndSource(InlineType.Script, nonce, source, parserInserted);
}
/**
* Determines whether this policy allows a script provided as an inline event handler
* attribute (e.g. {@code onclick}).
*
* @param source the text content of the event handler attribute, if known
* (used for hash matching with {@code 'unsafe-hashes'})
* @return {@code true} if this policy allows the script attribute
* @see <a href="https://w3c.github.io/webappsec-csp/#should-block-inline">
* should block inline check (script-src-attr)</a>
*/
public boolean allowsScriptAsAttribute(final Optional<String> source) {
if (sandbox_ != null && !sandbox_.allowScripts()) {
return false;
}
return doesElementMatchSourceListForTypeAndSource(
InlineType.ScriptAttribute, Optional.empty(), source, Optional.empty());
}
/**
* Determines whether this policy allows the use of {@code eval()} and similar
* string-to-code mechanisms.
* <p>
* The governing directive is {@code script-src} if present, otherwise {@code default-src}.
* Returns {@code true} if no governing directive is present or if the governing directive
* includes {@code 'unsafe-eval'}.
* </p>
*
* @return {@code true} if this policy allows eval
* @see <a href="https://w3c.github.io/webappsec-csp/#can-compile-strings">
* can compile strings check</a>
*/
public boolean allowsEval() {
// This is done in prose, not in a table
final FetchDirectiveKind governingDirective =
fetchDirectives_
.containsKey(FetchDirectiveKind.ScriptSrc)
? FetchDirectiveKind.ScriptSrc : FetchDirectiveKind.DefaultSrc;
final SourceExpressionDirective sourceList = fetchDirectives_.get(governingDirective);
return sourceList == null || sourceList.unsafeEval();
}
/**
* Determines whether this policy allows a navigation to the given URL.
* <p>
* This checks the {@code navigate-to} directive. If the directive is not present,
* navigation is allowed. This does <em>not</em> handle {@code javascript:} URL
* navigation; use {@link #allowsJavascriptUrlNavigation} for that.
* </p>
* <p>
* It is nonsensical to provide {@code redirectedTo} if {@code redirected} is
* {@code Optional.of(false)}.
* </p>
*
* @param to the initial navigation target URL, if known
* @param redirected whether the navigation is a redirect; {@link Optional#empty()} if unknown
* @param redirectedTo the final URL after redirect, if known
* @param origin the origin of the protected resource, if known
* @return {@code true} if this policy allows the navigation
* @see <a href="https://w3c.github.io/webappsec-csp/#navigate-to-pre-navigate">
* navigate-to pre-navigate check</a>
*/
public boolean allowsNavigation(
final Optional<? extends URLWithScheme> to,
final Optional<Boolean> redirected,
final Optional<? extends URLWithScheme> redirectedTo,
final Optional<? extends URLWithScheme> origin) {
if (navigateTo_ == null) {
return true;
}
if (navigateTo_.unsafeAllowRedirects()) {
// if unsafe-allow-redirects is present, check `to` in non-redirect or maybe-non-redirect cases
if (!redirected.orElse(false)) {
if (to.isEmpty()) {
return false;
}
if (!doesUrlMatchSourceListInOrigin(to.get(), navigateTo_, origin)) {
return false;
}
}
// if unsafe-allow-redirects is present, check `redirectedTo` in redirect or maybe-redirect cases
if (redirected.orElse(true)) {
if (redirectedTo.isEmpty()) {
return false;
}
if (!doesUrlMatchSourceListInOrigin(redirectedTo.get(), navigateTo_, origin)) {
return false;
}
}
}
else {
// if unsafe-allow-redirects is absent, always and only check `to`
if (to.isEmpty()) {
return false;
}
if (!doesUrlMatchSourceListInOrigin(to.get(), navigateTo_, origin)) {
return false;
}
}
return true;
}
/**
* Determines whether this policy allows a form submission to the given URL.
* <p>
* This checks the {@code form-action} directive first; if absent, falls back to
* the {@code navigate-to} directive via {@link #allowsNavigation}. If the sandbox
* directive is present and does not include {@code allow-forms}, form submission
* is blocked.
* </p>
*
* @param to the form action target URL, if known
* @param redirected whether the form submission results in a redirect;
* {@link Optional#empty()} if unknown
* @param redirectedTo the final URL after redirect, if known
* @param origin the origin of the protected resource, if known
* @return {@code true} if this policy allows the form action
* @see <a href="https://w3c.github.io/webappsec-csp/#navigate-to-pre-navigate">
* navigate-to pre-navigate check</a>
*/
public boolean allowsFormAction(
final Optional<? extends URLWithScheme> to,
final Optional<Boolean> redirected,
final Optional<? extends URLWithScheme> redirectedTo,
final Optional<? extends URLWithScheme> origin) {
if (sandbox_ != null && !sandbox_.allowForms()) {
return false;
}
if (formAction_ != null) {
if (to.isEmpty()) {
return false;
}
if (!doesUrlMatchSourceListInOrigin(to.get(), formAction_, origin)) {
return false;
}
return true;
}
// this isn't implemented like other fallbacks because
// it isn't one: form-action does not respect unsafe-allow-redirects
return allowsNavigation(to, redirected, redirectedTo, origin);
}
/**
* Determines whether this policy allows a {@code javascript:} URL navigation.
* <p>
* The hashes (for {@code 'unsafe-hashes'}) are expected to include the
* {@code javascript:} prefix per the specification.
* </p>
*
* @param source the JavaScript source code after the {@code javascript:} prefix, if known
* @param origin the origin of the protected resource, if known
* @return {@code true} if this policy allows the {@code javascript:} URL navigation
*/
public boolean allowsJavascriptUrlNavigation(
final Optional<String> source,
final Optional<? extends URLWithScheme> origin) {
return allowsNavigation(
Optional.of(
new GUID("javascript", source.orElse(""))),
Optional.of(false), Optional.empty(), origin)
&&
doesElementMatchSourceListForTypeAndSource(
InlineType.Navigation, Optional.empty(),
source.map(s -> "javascript:" + s), Optional.of(false));
}
/**
* Determines whether this policy allows loading an external stylesheet.
* <p>
* The effective directive is {@code style-src-elem} per the
* <a href="https://w3c.github.io/webappsec-csp/#effective-directive-for-a-request">
* effective directive for a request</a> algorithm. Integrity is not checked for
* stylesheets per <a href="https://github.com/w3c/webappsec-csp/issues/430">
* w3c/webappsec-csp#430</a>.
* </p>
*
* @param nonce the nonce attribute value of the link element, if any
* @param styleUrl the URL of the external stylesheet, if known
* @param origin the origin of the protected resource, if known
* @return {@code true} if this policy allows the external style
*/
public boolean allowsExternalStyle(
final Optional<String> nonce,
final Optional<? extends URLWithScheme> styleUrl,
final Optional<? extends URLWithScheme> origin) {
// Effective directive is "style-src-elem" per
// https://w3c.github.io/webappsec-csp/#effective-directive-for-a-request
final SourceExpressionDirective directive
= getGoverningDirectiveForEffectiveDirective(FetchDirectiveKind.StyleSrcElem).orElse(null);
if (directive == null) {
return true;
}
if (nonce.isPresent()) {
final String actualNonce = nonce.get();
if (actualNonce.length() > 0
&& directive.getNonces().stream().anyMatch(n -> n.base64ValuePart().equals(actualNonce))) {
return true;
}
}
// integrity is not used: https://github.com/w3c/webappsec-csp/issues/430
return styleUrl.filter(urlWithScheme ->
doesUrlMatchSourceListInOrigin(urlWithScheme, directive, origin)).isPresent();
}
/**
* Determines whether this policy allows an inline {@code <style>} element.
*
* @param nonce the nonce attribute value of the style element, if any
* @param source the text content of the inline style, if known (used for hash matching)
* @return {@code true} if this policy allows the inline style
*/
public boolean allowsInlineStyle(final Optional<String> nonce, final Optional<String> source) {
return doesElementMatchSourceListForTypeAndSource(InlineType.Style, nonce, source, Optional.empty());
}
/**
* Determines whether this policy allows an inline style attribute (e.g. {@code style="..."}).
*
* @param source the text content of the style attribute, if known
* (used for hash matching with {@code 'unsafe-hashes'})
* @return {@code true} if this policy allows the style attribute
*/
public boolean allowsStyleAsAttribute(final Optional<String> source) {
return doesElementMatchSourceListForTypeAndSource(
InlineType.StyleAttribute, Optional.empty(), source, Optional.empty());
}
/**
* Determines whether this policy allows loading a frame (iframe/frame) from the given source.
* <p>
* Uses the {@code frame-src} effective directive with its fallback chain.
* </p>
*
* @param source the URL of the framed resource, if known
* @param origin the origin of the protected resource, if known
* @return {@code true} if this policy allows the frame
*/
public boolean allowsFrame(final Optional<? extends URLWithScheme> source,
final Optional<? extends URLWithScheme> origin) {
final SourceExpressionDirective sourceList
= getGoverningDirectiveForEffectiveDirective(FetchDirectiveKind.FrameSrc).orElse(null);
if (sourceList == null) {
return true;
}
return source.filter(urlWithScheme ->
doesUrlMatchSourceListInOrigin(urlWithScheme, sourceList, origin)).isPresent();
}