forked from rust-ammonia/rust-content-security-policy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2905 lines (2783 loc) · 114 KB
/
Copy pathlib.rs
File metadata and controls
2905 lines (2783 loc) · 114 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
/*!
Parse and validate Web [Content-Security-Policy level 3](https://www.w3.org/TR/CSP/)
# Example
```rust
extern crate content_security_policy;
use content_security_policy::*;
fn main() {
let csp_list = CspList::parse("script-src *.notriddle.com", PolicySource::Header, PolicyDisposition::Enforce);
let (check_result, _) = csp_list.should_request_be_blocked(&Request {
url: Url::parse("https://www.notriddle.com/script.js").unwrap(),
current_url: Url::parse("https://www.notriddle.com/script.js").unwrap(),
origin: Origin::Tuple("https".to_string(), url::Host::Domain("notriddle.com".to_owned()), 443),
redirect_count: 0,
destination: Destination::Script,
initiator: Initiator::None,
nonce: String::new(),
integrity_metadata: String::new(),
parser_metadata: ParserMetadata::None,
});
assert_eq!(check_result, CheckResult::Allowed);
let (check_result, _) = csp_list.should_request_be_blocked(&Request {
url: Url::parse("https://www.evil.example/script.js").unwrap(),
current_url: Url::parse("https://www.evil.example/script.js").unwrap(),
origin: Origin::Tuple("https".to_string(), url::Host::Domain("notriddle.com".to_owned()), 443),
redirect_count: 0,
destination: Destination::Script,
initiator: Initiator::None,
nonce: String::new(),
integrity_metadata: String::new(),
parser_metadata: ParserMetadata::None,
});
assert_eq!(check_result, CheckResult::Blocked);
}
```
*/
#![forbid(unsafe_code)]
pub extern crate percent_encoding;
pub extern crate url;
pub mod sandboxing_directive;
pub(crate) mod text_util;
use once_cell::sync::Lazy;
use regex::Regex;
use sandboxing_directive::{parse_a_sandboxing_directive, SandboxingFlagSet};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::borrow::{Borrow, Cow};
use std::cmp;
use std::collections::HashSet;
use std::fmt::{self, Display, Formatter};
use std::str::FromStr;
use text_util::{
ascii_case_insensitive_match, collect_a_sequence_of_non_ascii_white_space_code_points,
split_ascii_whitespace, split_commas, strip_leading_and_trailing_ascii_whitespace,
};
pub use url::{Origin, Position, Url};
use MatchResult::DoesNotMatch;
use MatchResult::Matches;
fn scheme_is_network(scheme: &str) -> bool {
scheme == "ftp" || scheme_is_httpx(scheme)
}
fn scheme_is_httpx(scheme: &str) -> bool {
scheme == "http" || scheme == "https"
}
/**
A single parsed content security policy.
https://www.w3.org/TR/CSP/#content-security-policy-object
*/
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Policy {
pub directive_set: Vec<Directive>,
pub disposition: PolicyDisposition,
pub source: PolicySource,
}
impl Display for Policy {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
for (i, directive) in self.directive_set.iter().enumerate() {
if i != 0 {
write!(f, "; ")?;
}
<Directive as Display>::fmt(directive, f)?;
}
Ok(())
}
}
impl Policy {
pub fn is_valid(&self) -> bool {
self.directive_set.iter().all(Directive::is_valid)
&& self
.directive_set
.iter()
.map(|d| d.name.clone())
.collect::<HashSet<_>>()
.len()
== self.directive_set.len()
&& !self.directive_set.is_empty()
}
/// https://www.w3.org/TR/CSP/#parse-serialized-policy
pub fn parse(serialized: &str, source: PolicySource, disposition: PolicyDisposition) -> Policy {
// Step 1. If serialized is a byte sequence,
// then set serialized to be the result of isomorphic decoding serialized.
//
// N/a, we take in a string
// Step 2. Let policy be a new policy with an empty directive set,
// a source of source, and a disposition of disposition.
let mut policy = Policy {
directive_set: Vec::new(),
source,
disposition,
};
// Step 3. For each token returned by strictly splitting
// serialized on the U+003B SEMICOLON character (;):
//
// Rust's str::split corresponds to a WHATWG "strict split"
for token in serialized.split(';') {
// Step 3.1. Strip leading and trailing ASCII whitespace from token.
let token = strip_leading_and_trailing_ascii_whitespace(token);
// Step 3.2. If token is an empty string,
// or if token is not an ASCII string, continue.
if token.is_empty() || !token.is_ascii() {
continue;
};
// Step 3.3. Let directive name be the result of
// collecting a sequence of code points from token which are not ASCII whitespace.
let (directive_name, token) =
collect_a_sequence_of_non_ascii_white_space_code_points(token);
// Step 3.4. Set directive name to be the result of running ASCII lowercase on directive name.
let mut directive_name = directive_name.to_owned();
directive_name.make_ascii_lowercase();
// Step 3.5. If policy’s directive set contains a directive whose name is directive name, continue.
if policy.contains_a_directive_whose_name_is(&directive_name) {
continue;
}
// Step 3.6. Let directive value be the result of splitting token on ASCII whitespace.
let directive_value = split_ascii_whitespace(token).map(String::from).collect();
// Step 3.7. Let directive be a new directive whose name is directive name, and value is directive value.
// Step 3.8. Append directive to policy’s directive set.
policy.directive_set.push(Directive {
name: directive_name,
value: directive_value,
});
}
// Step 4. Return policy.
policy
}
pub fn contains_a_directive_whose_name_is(&self, directive_name: &str) -> bool {
self.directive_set.iter().any(|d| d.name == directive_name)
}
/// https://www.w3.org/TR/CSP/#does-request-violate-policy
pub fn does_request_violate_policy(&self, request: &Request) -> Violates {
if request.initiator == Initiator::Prefetch {
return self.does_resource_hint_violate_policy(request);
}
let mut violates = Violates::DoesNotViolate;
for directive in &self.directive_set {
let result = directive.pre_request_check(request, self);
if result == CheckResult::Blocked {
violates = Violates::Directive(directive.clone());
}
}
violates
}
/// https://www.w3.org/TR/CSP/#does-resource-hint-violate-policy
pub fn does_resource_hint_violate_policy(&self, request: &Request) -> Violates {
let default_directive = &self.directive_set.iter().find(|x| x.name == "default-src");
if default_directive.is_none() {
return Violates::DoesNotViolate;
}
for directive in &self.directive_set {
let result = directive.pre_request_check(request, self);
if result == CheckResult::Allowed {
return Violates::DoesNotViolate;
}
}
return Violates::Directive(default_directive.unwrap().clone());
}
}
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// https://www.w3.org/TR/CSP/#csp-list
pub struct CspList(pub Vec<Policy>);
impl Display for CspList {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
for (i, directive) in self.0.iter().enumerate() {
if i != 0 {
write!(f, ",")?;
}
<Policy as Display>::fmt(directive, f)?;
}
Ok(())
}
}
/// https://www.w3.org/TR/trusted-types/#trusted-types-csp-directive
static TRUSTED_POLICY_SOURCE_GRAMMAR: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"^[0-9a-zA-Z\-\#=_\/@\.%]+$"#).unwrap());
impl CspList {
pub fn is_valid(&self) -> bool {
self.0.iter().all(Policy::is_valid)
}
/// https://www.w3.org/TR/CSP/#contains-a-header-delivered-content-security-policy
pub fn contains_a_header_delivered_content_security_policy(&self) -> bool {
self.0
.iter()
.any(|policy| policy.source == PolicySource::Header)
}
/// https://www.w3.org/TR/CSP/#parse-serialized-policy-list
pub fn parse(list: &str, source: PolicySource, disposition: PolicyDisposition) -> CspList {
let mut policies = Vec::new();
for token in split_commas(list) {
let policy = Policy::parse(token, source, disposition);
if policy.directive_set.is_empty() {
continue;
};
policies.push(policy)
}
CspList(policies)
}
pub fn append(&mut self, mut other: CspList) {
self.0.append(&mut other.0)
}
pub fn push(&mut self, policy: Policy) {
self.0.push(policy)
}
/**
Given a request, this algorithm reports violations based on client’s "report only" policies.
https://www.w3.org/TR/CSP/#report-for-request
*/
pub fn report_violations_for_request(&self, request: &Request) -> Vec<Violation> {
let mut violations = Vec::new();
for policy in &self.0 {
if policy.disposition == PolicyDisposition::Enforce {
continue;
};
let violates = policy.does_request_violate_policy(request);
if let Violates::Directive(directive) = violates {
let resource = ViolationResource::Url(request.url.clone());
violations.push(Violation {
resource,
directive: Directive {
name: get_the_effective_directive_for_request(request).to_owned(),
value: directive.value.clone(),
},
policy: policy.clone(),
});
}
}
violations
}
/**
Given a request, this algorithm returns Blocked or Allowed and reports violations based on
request’s client’s Content Security Policy.
https://www.w3.org/TR/CSP/#should-block-request
*/
pub fn should_request_be_blocked(&self, request: &Request) -> (CheckResult, Vec<Violation>) {
let mut result = CheckResult::Allowed;
let mut violations = Vec::new();
for policy in &self.0 {
if policy.disposition == PolicyDisposition::Report {
continue;
};
let violates = policy.does_request_violate_policy(request);
if let Violates::Directive(directive) = violates {
result = CheckResult::Blocked;
let resource = ViolationResource::Url(request.url.clone());
violations.push(Violation {
resource,
directive: Directive {
name: get_the_effective_directive_for_request(request).to_owned(),
value: directive.value.clone(),
},
policy: policy.clone(),
});
}
}
(result, violations)
}
/**
Given a response and a request, this algorithm returns Blocked or Allowed, and reports
violations based on request’s client’s Content Security Policy.
https://www.w3.org/TR/CSP/#should-block-response
*/
pub fn should_response_to_request_be_blocked(
&self,
request: &Request,
response: &Response,
) -> (CheckResult, Vec<Violation>) {
// Step 1. Let CSP list be request’s policy container’s CSP list.
// step 2. Let result be "Allowed".
let mut result = CheckResult::Allowed;
let mut violations = Vec::new();
// Step 3. For each policy of CSP list:
for policy in &self.0 {
// Step 3.1. For each directive of policy:
for directive in &policy.directive_set {
// Step 3.1.1. If the result of executing directive’s post-request check is "Blocked", then:
if directive.post_request_check(request, response, policy) == CheckResult::Blocked {
// Step 3.1.1.1. Execute §5.5 Report a violation on the result of executing
// §2.4.2 Create a violation object for request, and policy. on request, and policy.
violations.push(Violation {
resource: ViolationResource::Url(request.url.clone()),
directive: Directive {
name: get_the_effective_directive_for_request(request).to_owned(),
value: directive.value.clone(),
},
policy: policy.clone(),
});
// Step 3.1.1.2. If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = CheckResult::Blocked;
}
}
}
}
(result, violations)
}
/// https://www.w3.org/TR/CSP/#should-block-inline
pub fn should_elements_inline_type_behavior_be_blocked(
&self,
element: &Element,
type_: InlineCheckType,
source: &str,
) -> (CheckResult, Vec<Violation>) {
use CheckResult::*;
let mut result = Allowed;
let mut violations = Vec::new();
for policy in &self.0 {
for directive in &policy.directive_set {
if directive.inline_check(element, type_, policy, source) == Allowed {
continue;
}
let sample = if directive.value.iter().any(|t| &t[..] == "'report-sample'") {
let max_length = cmp::min(40, source.len());
Some(source[0..max_length].to_owned())
} else {
None
};
let violation = Violation {
resource: ViolationResource::Inline { sample },
directive: Directive {
name: get_the_effective_directive_for_inline_checks(type_).to_owned(),
value: directive.value.clone(),
},
policy: policy.clone(),
};
violations.push(violation);
if policy.disposition == PolicyDisposition::Enforce {
result = Blocked;
}
}
}
(result, violations)
}
/**
https://www.w3.org/TR/CSP/#allow-base-for-document
Note that, while this algoritm is defined as operating on a document, the only property it
actually uses is the document's CSP List. So this function operates on that.
*/
pub fn is_base_allowed_for_document(
&self,
base: &Url,
self_origin: &Origin,
) -> (CheckResult, Vec<Violation>) {
use CheckResult::*;
let mut violations = Vec::new();
for policy in &self.0 {
let directive = policy
.directive_set
.iter()
.find(|directive| directive.name == "base-uri");
if let Some(directive) = directive {
if SourceList(&directive.value)
.does_url_match_source_list_in_origin_with_redirect_count(base, &self_origin, 0)
== DoesNotMatch
{
let violation = Violation {
directive: directive.clone(),
resource: ViolationResource::Inline { sample: None },
policy: policy.clone(),
};
violations.push(violation);
if policy.disposition == PolicyDisposition::Enforce {
return (Blocked, violations);
}
}
}
}
return (Allowed, violations);
}
/**
https://w3c.github.io/trusted-types/dist/spec/#should-block-create-policy
Note that, while this algoritm is defined as operating on a global object, the only property it
actually uses is the global's CSP List. So this function operates on that.
*/
pub fn is_trusted_type_policy_creation_allowed(
&self,
policy_name: &str,
created_policy_names: &[&str],
) -> (CheckResult, Vec<Violation>) {
use CheckResult::*;
// Step 1: Let result be "Allowed".
let mut result = Allowed;
let mut violations = Vec::new();
// Step 2: For each policy in global’s CSP list:
for policy in &self.0 {
// Step 2.1: Let createViolation be false.
let mut create_violation = false;
// Step 2.2: If policy’s directive set does not contain a directive which name is "trusted-types", skip to the next policy.
let directive = policy
.directive_set
.iter()
.find(|directive| directive.name == "trusted-types");
// Step 2.3: Let directive be the policy’s directive set’s directive which name is "trusted-types"
if let Some(directive) = directive {
// Step 2.4: If directive’s value only contains a tt-keyword which is a match for a value 'none', set createViolation to true.
if directive.value.len() == 1 && directive.value.contains(&"'none'".to_string()) {
create_violation = true;
}
// Step 2.5: If createdPolicyNames contains policyName and directive’s value does not contain a tt-keyword
// which is a match for a value 'allow-duplicates', set createViolation to true.
if created_policy_names.contains(&policy_name)
&& !directive.value.iter().any(|v| v == "'allow-duplicates'")
{
create_violation = true;
}
// Step 2.6: If directive’s value does not contain a tt-policy-name, which value is policyName,
// and directive’s value does not contain a tt-wildcard, set createViolation to true.
if !(TRUSTED_POLICY_SOURCE_GRAMMAR.is_match(&policy_name)
&& (directive.value.iter().any(|p| p == policy_name)
|| directive.value.iter().any(|v| v == "*")))
{
create_violation = true;
}
// Step 2.7: If createViolation is false, skip to the next policy.
if !create_violation {
continue;
}
let max_length = cmp::min(40, policy_name.len());
// Step 2.10: Set violation’s sample to the substring of policyName, containing its first 40 characters.
let sample = policy_name[0..max_length].to_owned();
// Step 2.8: Let violation be the result of executing Create a violation object for global, policy,
// and directive on global, policy and "trusted-types"
let violation = Violation {
directive: directive.clone(),
// Step 2.9: Set violation’s resource to "trusted-types-policy".
resource: ViolationResource::TrustedTypePolicy {
// Step 2.10: Set violation’s sample to the substring of policyName, containing its first 40 characters.
sample,
},
policy: policy.clone(),
};
// Step 2.11: Execute Report a violation on violation.
violations.push(violation);
// Step 2.12: If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = Blocked
}
}
}
return (result, violations);
}
/**
https://w3c.github.io/trusted-types/dist/spec/#abstract-opdef-does-sink-type-require-trusted-types
Note that, while this algoritm is defined as operating on a global object, the only property it
actually uses is the global's CSP List. So this function operates on that.
*/
pub fn does_sink_type_require_trusted_types(
&self,
sink_group: &str,
include_report_only_policies: bool,
) -> bool {
let sink_group = &sink_group.to_owned();
// Step 1: For each policy in global’s CSP list:
for policy in &self.0 {
// Step 1.1: If policy’s directive set does not contain a directive whose name is "require-trusted-types-for", skip to the next policy.
let directive = policy
.directive_set
.iter()
.find(|directive| directive.name == "require-trusted-types-for");
// Step 1.2: Let directive be the policy’s directive set’s directive whose name is "require-trusted-types-for"
if let Some(directive) = directive {
// Step 1.3: If directive’s value does not contain a trusted-types-sink-group which is a match for sinkGroup, skip to the next policy.
if !directive.value.contains(sink_group) {
continue;
}
// Step 1.4: Let enforced be true if policy’s disposition is "enforce", and false otherwise.
let enforced = policy.disposition == PolicyDisposition::Enforce;
// Step 1.5: If enforced is true, return true.
if enforced {
return true;
}
// Step 1.6: If includeReportOnlyPolicies is true, return true.
if include_report_only_policies {
return true;
}
}
}
// Step 2: Return false.
false
}
/**
https://w3c.github.io/trusted-types/dist/spec/#should-block-sink-type-mismatch
Note that, while this algoritm is defined as operating on a global object, the only property it
actually uses is the global's CSP List. So this function operates on that.
*/
pub fn should_sink_type_mismatch_violation_be_blocked_by_csp(
&self,
sink: &str,
sink_group: &str,
source: &str,
) -> (CheckResult, Vec<Violation>) {
use CheckResult::*;
let sink_group = &sink_group.to_owned();
// Step 1: Let result be "Allowed".
let mut result = Allowed;
let mut violations = Vec::new();
// Step 2: Let sample be source.
let mut sample = source;
// Step 3: If sink is "Function", then:
if sink == "Function" {
// Step 3.1: If sample starts with "function anonymous", strip that from sample.
if sample.starts_with("function anonymous") {
sample = &sample[18..];
// Step 3.2: Otherwise if sample starts with "async function anonymous", strip that from sample.
} else if sample.starts_with("async function anonymous") {
sample = &sample[24..];
// Step 3.3: Otherwise if sample starts with "function* anonymous", strip that from sample.
} else if sample.starts_with("function* anonymous") {
sample = &sample[19..];
// Step 3.4: Otherwise if sample starts with "async function* anonymous", strip that from sample.
} else if sample.starts_with("async function* anonymous") {
sample = &sample[25..];
}
}
// Step 4: For each policy in global’s CSP list:
for policy in &self.0 {
// Step 4.1: If policy’s directive set does not contain a directive whose name is "require-trusted-types-for", skip to the next policy.
let directive = policy
.directive_set
.iter()
.find(|directive| directive.name == "require-trusted-types-for");
// Step 4.2: Let directive be the policy’s directive set’s directive whose name is "require-trusted-types-for"
let Some(directive) = directive else { continue };
// Step 4.3: If directive’s value does not contain a trusted-types-sink-group which is a match for sinkGroup, skip to the next policy.
if !directive.value.contains(sink_group) {
continue;
}
// Step 4.6: Let trimmedSample be the substring of sample, containing its first 40 characters.
let mut trimmed_sample: String = sample.into();
trimmed_sample.truncate(40);
// Step 4.4: Let violation be the result of executing Create a violation object for global, policy,
// and directive on global, policy and "require-trusted-types-for"
violations.push(Violation {
// Step 4.5: Set violation’s resource to "trusted-types-sink".
resource: ViolationResource::TrustedTypeSink {
// Step 4.7: Set violation’s sample to be the result of concatenating the list « sink, trimmedSample « using "|" as a separator.
sample: sink.to_owned() + "|" + &trimmed_sample,
},
directive: directive.clone(),
policy: policy.clone(),
});
// Step 4.9: If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = Blocked
}
}
// Step 2: Return false.
(result, violations)
}
/// <https://html.spec.whatwg.org/multipage/#csp-derived-sandboxing-flags>
pub fn get_sandboxing_flag_set_for_document(&self) -> Option<SandboxingFlagSet> {
// Step 1. Let directives be an empty ordered set.
// Step 2. For each policy in cspList:
self.0
.iter()
.flat_map(|policy| {
policy
.directive_set
.iter()
// Step 4. Let directive be directives[directives's size − 1].
.rev()
// Step 2.2. If policy's directive set contains a directive whose name is "sandbox",
// then append that directive to directives.
.find(|directive| directive.name == "sandbox")
.and_then(|directive| directive.get_sandboxing_flag_set_for_document(policy))
})
// Step 3. If directives is empty, then return an empty sandboxing flag set.
.next()
}
/// https://www.w3.org/TR/CSP/#can-compile-strings
pub fn is_js_evaluation_allowed(&self, source: &str) -> (CheckResult, Vec<Violation>) {
let mut result = CheckResult::Allowed;
let mut violations = Vec::new();
// Step 5: For each policy of global’s CSP list:
for policy in &self.0 {
// Step 5.1: Let source-list be null.
let directive = policy
.directive_set
.iter()
// Step 5.2: If policy contains a directive whose name is "script-src",
// then set source-list to that directive’s value.
.find(|directive| directive.name == "script-src")
// Step 5.2: Otherwise if policy contains a directive whose name is "default-src",
// then set source-list to that directive’s value.
.or_else(|| {
policy
.directive_set
.iter()
.find(|directive| directive.name == "default-src")
});
// Step 5.3: If source-list is not null:
let Some(directive) = directive else { continue };
let source_list = SourceList(&directive.value);
if source_list.does_a_source_list_allow_js_evaluation() == AllowResult::Allows {
continue;
}
// Step 5.3.1: Let trustedTypesRequired be the result of executing
// Does sink type require trusted types?, with realm, 'script', and false.
let trusted_types_required =
self.does_sink_type_require_trusted_types("'script'", false);
// Step 5.3.2: If trustedTypesRequired is true and source-list contains a source expression
// which is an ASCII case-insensitive match for the string "'trusted-types-eval'", then skip the following steps.
if trusted_types_required
&& directive
.value
.iter()
.any(|t| ascii_case_insensitive_match(&t[..], "'trusted-types-eval'"))
{
continue;
}
// Step 5.3.3: If source-list contains a source expression which is
// an ASCII case-insensitive match for the string "'unsafe-eval'", then skip the following steps.
if directive
.value
.iter()
.any(|t| ascii_case_insensitive_match(&t[..], "'unsafe-eval'"))
{
continue;
}
// Step 5.3.6: If source-list contains the expression "'report-sample'",
// then set violation’s sample to the substring of sourceString containing its first 40 characters.
let sample = if directive.value.iter().any(|t| &t[..] == "'report-sample'") {
let max_length = cmp::min(40, source.len());
Some(source[0..max_length].to_owned())
} else {
None
};
// Step 5.3.4: Let violation be the result of executing Create a violation object for global, policy,
// and directive on global, policy and "require-trusted-types-for"
violations.push(Violation {
// Step 5.3.5: Set violation’s resource to "eval".
resource: ViolationResource::Eval { sample },
directive: directive.clone(),
policy: policy.clone(),
});
// Step 5.3.8: If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = CheckResult::Blocked
}
}
(result, violations)
}
/// https://www.w3.org/TR/CSP/#can-compile-wasm-bytes
pub fn is_wasm_evaluation_allowed(&self) -> (CheckResult, Vec<Violation>) {
let mut result = CheckResult::Allowed;
let mut violations = Vec::new();
// Step 3: For each policy of global’s CSP list:
for policy in &self.0 {
// Step 3.1: Let source-list be null.
let directive = policy
.directive_set
.iter()
// Step 3.2: If policy contains a directive whose name is "script-src",
// then set source-list to that directive’s value.
.find(|directive| directive.name == "script-src")
// Step 3.2: Otherwise if policy contains a directive whose name is "default-src",
// then set source-list to that directive’s value.
.or_else(|| {
policy
.directive_set
.iter()
.find(|directive| directive.name == "default-src")
});
let Some(directive) = directive else { continue };
let source_list = SourceList(&directive.value);
// Step 3.3: If source-list is non-null, and does not contain a source expression
// which is an ASCII case-insensitive match for the string "'unsafe-eval'",
// and does not contain a source expression which is an ASCII case-insensitive
// match for the string "'wasm-unsafe-eval'", then:
if source_list.does_a_source_list_allow_wasm_evaluation() == AllowResult::Allows {
continue;
}
// Step 3.3.1: Let violation be the result of executing § 2.4.1 Create a violation
// object for global, policy, and directive on global, policy, and "script-src".
violations.push(Violation {
// Step 5.3.5: Set violation’s resource to "wasm-eval".
resource: ViolationResource::WasmEval,
directive: directive.clone(),
policy: policy.clone(),
});
// Step 3.3.4: If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = CheckResult::Blocked
}
}
(result, violations)
}
/// <https://w3c.github.io/webappsec-csp/#should-block-navigation-request>
///
/// Here, `url_processor` is a callback to process trusted types (if applicable).
/// In case the Trusted Types algorithm returns an Error, return a None. Otherwise
/// return a Some with the string as provided by the policy.
///
/// If trusted types are not applicable, then the `url_processor` can look like this:
/// ```rust
/// |s: &str| Some(s.to_owned());
/// ```
pub fn should_navigation_request_be_blocked<TrustedTypesUrlProcessor>(
&self,
request: &mut Request,
navigation_check_type: NavigationCheckType,
mut url_processor: TrustedTypesUrlProcessor,
) -> (CheckResult, Vec<Violation>)
where
TrustedTypesUrlProcessor: FnMut(&str) -> Option<String>,
{
// Step 1: Let result be "Allowed".
let mut result = CheckResult::Allowed;
let mut violations = Vec::new();
// Step 2: For each policy of navigation request’s policy container’s CSP list:
for policy in &self.0 {
// Step 2.1: For each directive of policy:
for directive in &policy.directive_set {
// Step 2.1.1: If directive’s pre-navigation check returns "Allowed"
// when executed upon navigation request, type, and policy skip to the next directive.
if directive.pre_navigation_check(
request,
navigation_check_type,
&mut url_processor,
policy,
) == CheckResult::Allowed
{
continue;
}
// Step 2.1.2: Otherwise, let violation be the result of executing
// § 2.4.1 Create a violation object for global, policy, and directive
// on navigation request’s client’s global object, policy, and directive’s name.
violations.push(Violation {
// Step 2.1.3: Set violation’s resource to navigation request’s URL.
resource: ViolationResource::Url(request.url.clone()),
directive: Directive {
name: get_the_effective_directive_for_request(request).to_owned(),
value: directive.value.clone(),
},
policy: policy.clone(),
});
// Step 2.1.5: If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = CheckResult::Blocked;
}
}
}
// Step 3: If result is "Allowed", and if navigation request’s current URL’s scheme is javascript:
if result == CheckResult::Allowed && request.current_url.scheme() == "javascript" {
// Step 3.1: For each policy of navigation request’s policy container’s CSP list:
for policy in &self.0 {
// Step 3.1.1: For each directive of policy:
for directive in &policy.directive_set {
// Step 3.1.1.2: If directive’s inline check returns "Allowed" when executed upon null,
// "navigation" and navigation request’s current URL, skip to the next directive.
if directive.inline_check(
&Element { nonce: None },
InlineCheckType::Navigation,
policy,
request.current_url.as_str(),
) == CheckResult::Allowed
{
continue;
}
// Step 3.1.1.3: Otherwise, let violation be the result of executing
// § 2.4.1 Create a violation object for global, policy, and directive
// on navigation request’s client’s global object, policy, and directive’s name.
violations.push(Violation {
// Step 3.1.1.4: Set violation’s resource to navigation request’s URL.
resource: ViolationResource::Inline { sample: None },
directive: Directive {
// Step 3.1.1.1: Let directive-name be the result of executing
// § 6.8.2 Get the effective directive for inline checks on type.
name: get_the_effective_directive_for_inline_checks(
InlineCheckType::Navigation,
)
.to_owned(),
value: directive.value.clone(),
},
policy: policy.clone(),
});
// Step 3.1.1.6: If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = CheckResult::Blocked;
}
}
}
}
(result, violations)
}
/// <https://w3c.github.io/webappsec-csp/#should-block-navigation-response>
pub fn should_navigation_response_to_navigation_request_be_blocked(
&self,
response: &Response,
self_origin: &Origin,
parent_navigable_origins: &Vec<Url>,
) -> (CheckResult, Vec<Violation>) {
// Step 1. Let result be "Allowed".
let mut result = CheckResult::Allowed;
let mut violations = Vec::new();
// Step 2. For each policy of response CSP list’s policies:
for policy in &self.0 {
// Step 2.1. For each directive of policy:
for directive in &policy.directive_set {
// Step 2.1.1. If directive’s navigation response check returns "Allowed"
// when executed upon navigation request, type, navigation response, target,
// "response", policy, and response CSP list’s self-origin, skip to the next directive.
if directive.navigation_response_check(
response,
self_origin,
parent_navigable_origins,
policy,
) == CheckResult::Allowed
{
continue;
}
// Step 2.1.2. Otherwise, let violation be the result of executing
// § 2.4.1 Create a violation object for global, policy, and directive on null, policy, and directive’s name.
violations.push(Violation {
// Step 2.1.3. Set violation’s resource to navigation response’s URL.
resource: ViolationResource::Url(response.url.clone()),
directive: directive.clone(),
policy: policy.clone(),
});
// Step 2.1.5. If policy’s disposition is "enforce", then set result to "Blocked".
if policy.disposition == PolicyDisposition::Enforce {
result = CheckResult::Blocked;
}
}
}
// Step 3. For each policy of navigation request’s policy container’s CSP list’s policies:
//
// Note: We do not implement this step, since there is no directive yet that requires it
(result, violations)
}
}
#[derive(Clone, Debug)]
pub struct Element<'a> {
/// When there is no nonce, populate this member with `None`.
///
/// When the element is not [nonceable], also populate it with `None`.
///
/// [nonceable]: https://www.w3.org/TR/CSP/#is-element-nonceable
pub nonce: Option<Cow<'a, str>>,
}
/**
The valid values for type are "script", "script attribute", "style", and "style attribute".
https://www.w3.org/TR/CSP/#should-block-inline
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InlineCheckType {
Script,
ScriptAttribute,
Style,
StyleAttribute,
Navigation,
}
/**
The valid values for type are "form-submission" and "other".
https://w3c.github.io/webappsec-csp/#directive-pre-navigation-check
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NavigationCheckType {
FormSubmission,
Other,
}
/**
request to be validated
https://fetch.spec.whatwg.org/#concept-request
*/
#[derive(Clone, Debug)]
pub struct Request {
pub url: Url,
pub current_url: Url,
pub origin: Origin,
pub redirect_count: u32,
pub destination: Destination,
pub initiator: Initiator,
pub nonce: String,
pub integrity_metadata: String,
pub parser_metadata: ParserMetadata,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ParserMetadata {
ParserInserted,
NotParserInserted,
None,
}
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Initiator {
Download,
ImageSet,
Manifest,
Prefetch,
Prerender,
Fetch,
Xslt,
None,
}
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Destination {
None,
Audio,
AudioWorklet,
Document,
Embed,
Font,
Frame,
IFrame,
Image,
Json,
Manifest,
Object,
PaintWorklet,
Report,
Script,
ServiceWorker,
SharedWorker,
Style,
Track,
Video,
WebIdentity,
Worker,
Xslt,
}
pub struct InvalidDestination;
impl FromStr for Destination {
type Err = InvalidDestination;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let destination = match s {
"" => Self::None,
"audio" => Self::Audio,
"audioworklet" => Self::AudioWorklet,
"document" => Self::Document,
"embed" => Self::Embed,
"font" => Self::Font,
"frame" => Self::Frame,
"iframe" => Self::IFrame,
"image" => Self::Image,
"json" => Self::Json,