-
Notifications
You must be signed in to change notification settings - Fork 84
/
security_report.rs
1870 lines (1680 loc) · 67.2 KB
/
security_report.rs
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
//! Contains definitions for the security report interfaces.
//!
//! The security interfaces are CSP, HPKP, ExpectCT and ExpectStaple.
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::{self, Write};
use chrono::{DateTime, Utc};
use serde::de::{Error, IgnoredAny};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::protocol::{
Event, HeaderName, HeaderValue, Headers, LogEntry, PairList, Request, TagEntry, Tags,
};
use crate::types::{Annotated, Array, Object, Value};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct InvalidSecurityError;
impl fmt::Display for InvalidSecurityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid security report")
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CspDirective {
BaseUri,
ChildSrc,
ConnectSrc,
DefaultSrc,
FontSrc,
FormAction,
FrameAncestors,
FrameSrc,
ImgSrc,
ManifestSrc,
MediaSrc,
ObjectSrc,
PluginTypes,
PrefetchSrc,
Referrer,
ScriptSrc,
ScriptSrcAttr,
ScriptSrcElem,
StyleSrc,
StyleSrcElem,
StyleSrcAttr,
UpgradeInsecureRequests,
WorkerSrc,
// Sandbox , // unsupported
}
derive_fromstr_and_display!(CspDirective, InvalidSecurityError, {
CspDirective::BaseUri => "base-uri",
CspDirective::ChildSrc => "child-src",
CspDirective::ConnectSrc => "connect-src",
CspDirective::DefaultSrc => "default-src",
CspDirective::FontSrc => "font-src",
CspDirective::FormAction => "form-action",
CspDirective::FrameAncestors => "frame-ancestors",
CspDirective::FrameSrc => "frame-src",
CspDirective::ImgSrc => "img-src",
CspDirective::ManifestSrc => "manifest-src",
CspDirective::MediaSrc => "media-src",
CspDirective::ObjectSrc => "object-src",
CspDirective::PluginTypes => "plugin-types",
CspDirective::PrefetchSrc => "prefetch-src",
CspDirective::Referrer => "referrer",
CspDirective::ScriptSrc => "script-src",
CspDirective::ScriptSrcAttr => "script-src-attr",
CspDirective::ScriptSrcElem => "script-src-elem",
CspDirective::StyleSrc => "style-src",
CspDirective::StyleSrcElem => "style-src-elem",
CspDirective::StyleSrcAttr => "style-src-attr",
CspDirective::UpgradeInsecureRequests => "upgrade-insecure-requests",
CspDirective::WorkerSrc => "worker-src",
});
impl_str_serde!(CspDirective);
fn is_local(uri: &str) -> bool {
matches!(uri, "" | "self" | "'self'")
}
fn schema_uses_host(schema: &str) -> bool {
// List of schemas with host (netloc) from Python's urlunsplit:
// see <https://github.com/python/cpython/blob/1eac437e8da106a626efffe9fce1cb47dbf5be35/Lib/urllib/parse.py#L51>
//
// Only modification: "" is set to false, since there is a separate check in the urlunsplit
// implementation that omits the leading "//" in that case.
matches!(
schema,
"ftp"
| "http"
| "gopher"
| "nntp"
| "telnet"
| "imap"
| "wais"
| "file"
| "mms"
| "https"
| "shttp"
| "snews"
| "prospero"
| "rtsp"
| "rtspu"
| "rsync"
| "svn"
| "svn+ssh"
| "sftp"
| "nfs"
| "git"
| "git+ssh"
| "ws"
| "wss"
)
}
/// Mimicks Python's urlunsplit with all its quirks.
fn unsplit_uri(schema: &str, host: &str) -> String {
if !host.is_empty() || schema_uses_host(schema) {
format!("{}://{}", schema, host)
} else if !schema.is_empty() {
format!("{}:{}", schema, host)
} else {
String::new()
}
}
fn normalize_uri(value: &str) -> Cow<'_, str> {
if is_local(value) {
return Cow::Borrowed("'self'");
}
// A lot of these values get reported as literally just the scheme. So a value like 'data'
// or 'blob', which are valid schemes, just not a uri. So we want to normalize it into a
// URI.
if !value.contains(':') {
return Cow::Owned(unsplit_uri(value, ""));
}
let url = match Url::parse(value) {
Ok(url) => url,
Err(_) => return Cow::Borrowed(value),
};
let normalized = match url.scheme() {
"http" | "https" => Cow::Borrowed(url.host_str().unwrap_or_default()),
scheme => Cow::Owned(unsplit_uri(scheme, url.host_str().unwrap_or_default())),
};
Cow::Owned(match url.port() {
Some(port) => format!("{}:{}", normalized, port),
None => normalized.into_owned(),
})
}
/// Inner (useful) part of a CSP report.
///
/// See `Csp` for meaning of fields.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct CspRaw {
#[serde(skip_serializing_if = "Option::is_none")]
effective_directive: Option<CspDirective>,
#[serde(default = "CspRaw::default_blocked_uri")]
blocked_uri: String,
#[serde(skip_serializing_if = "Option::is_none")]
document_uri: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
original_policy: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
referrer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
status_code: Option<u64>,
#[serde(default = "String::new")]
violated_directive: String,
#[serde(skip_serializing_if = "Option::is_none")]
source_file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
line_number: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
column_number: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
script_sample: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
disposition: Option<String>,
#[serde(flatten)]
other: BTreeMap<String, serde_json::Value>,
}
impl CspRaw {
fn default_blocked_uri() -> String {
"self".to_string()
}
fn effective_directive(&self) -> Result<CspDirective, InvalidSecurityError> {
// Firefox doesn't send effective-directive, so parse it from
// violated-directive but prefer effective-directive when present
//
// refs: https://bugzil.la/1192684#c8
if let Some(directive) = self.effective_directive {
return Ok(directive);
}
self.violated_directive
.splitn(2, ' ')
.next()
.and_then(|v| v.parse().ok())
.ok_or(InvalidSecurityError)
}
fn get_message(&self, effective_directive: CspDirective) -> String {
if is_local(&self.blocked_uri) {
match effective_directive {
CspDirective::ChildSrc => "Blocked inline 'child'".to_string(),
CspDirective::ConnectSrc => "Blocked inline 'connect'".to_string(),
CspDirective::FontSrc => "Blocked inline 'font'".to_string(),
CspDirective::ImgSrc => "Blocked inline 'image'".to_string(),
CspDirective::ManifestSrc => "Blocked inline 'manifest'".to_string(),
CspDirective::MediaSrc => "Blocked inline 'media'".to_string(),
CspDirective::ObjectSrc => "Blocked inline 'object'".to_string(),
CspDirective::ScriptSrcAttr => "Blocked unsafe 'script' element".to_string(),
CspDirective::ScriptSrcElem => "Blocked inline script attribute".to_string(),
CspDirective::StyleSrc => "Blocked inline 'style'".to_string(),
CspDirective::StyleSrcElem => "Blocked 'style' or 'link' element".to_string(),
CspDirective::StyleSrcAttr => "Blocked style attribute".to_string(),
CspDirective::ScriptSrc => {
if self.violated_directive.contains("'unsafe-inline'") {
"Blocked unsafe inline 'script'".to_string()
} else if self.violated_directive.contains("'unsafe-eval'") {
"Blocked unsafe eval() 'script'".to_string()
} else {
"Blocked unsafe (eval() or inline) 'script'".to_string()
}
}
directive => format!("Blocked inline '{}'", directive),
}
} else {
let uri = normalize_uri(&self.blocked_uri);
match effective_directive {
CspDirective::ChildSrc => format!("Blocked 'child' from '{}'", uri),
CspDirective::ConnectSrc => format!("Blocked 'connect' from '{}'", uri),
CspDirective::FontSrc => format!("Blocked 'font' from '{}'", uri),
CspDirective::FormAction => format!("Blocked 'form' action to '{}'", uri),
CspDirective::ImgSrc => format!("Blocked 'image' from '{}'", uri),
CspDirective::ManifestSrc => format!("Blocked 'manifest' from '{}'", uri),
CspDirective::MediaSrc => format!("Blocked 'media' from '{}'", uri),
CspDirective::ObjectSrc => format!("Blocked 'object' from '{}'", uri),
CspDirective::ScriptSrc => format!("Blocked 'script' from '{}'", uri),
CspDirective::ScriptSrcAttr => {
format!("Blocked inline script attribute from '{}'", uri)
}
CspDirective::ScriptSrcElem => format!("Blocked 'script' from '{}'", uri),
CspDirective::StyleSrc => format!("Blocked 'style' from '{}'", uri),
CspDirective::StyleSrcElem => format!("Blocked 'style' from '{}'", uri),
CspDirective::StyleSrcAttr => format!("Blocked style attribute from '{}'", uri),
directive => format!("Blocked '{}' from '{}'", directive, uri),
}
}
}
fn into_protocol(self, effective_directive: CspDirective) -> Csp {
Csp {
effective_directive: Annotated::from(effective_directive.to_string()),
blocked_uri: Annotated::from(self.blocked_uri),
document_uri: Annotated::from(self.document_uri),
original_policy: Annotated::from(self.original_policy),
referrer: Annotated::from(self.referrer),
status_code: Annotated::from(self.status_code),
violated_directive: Annotated::from(self.violated_directive),
source_file: Annotated::from(self.source_file),
line_number: Annotated::from(self.line_number),
column_number: Annotated::from(self.column_number),
script_sample: Annotated::from(self.script_sample),
disposition: Annotated::from(self.disposition),
other: self
.other
.into_iter()
.map(|(k, v)| (k, Annotated::from(v)))
.collect(),
}
}
fn sanitized_blocked_uri(&self) -> String {
// HACK: This is 100% to work around Stripe urls that will casually put extremely sensitive
// information in querystrings. The real solution is to apply data scrubbing to all tags
// generically.
//
// if netloc == 'api.stripe.com':
// query = '' fragment = ''
let mut uri = self.blocked_uri.clone();
if uri.starts_with("https://api.stripe.com/") {
if let Some(index) = uri.find(&['#', '?'][..]) {
uri.truncate(index);
}
}
uri
}
fn normalize_value<'a>(&self, value: &'a str, document_uri: &str) -> Cow<'a, str> {
// > If no scheme is specified, the same scheme as the one used to access the protected
// > document is assumed.
// Source: https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
if let "'none'" | "'self'" | "'unsafe-inline'" | "'unsafe-eval'" = value {
return Cow::Borrowed(value);
}
// Normalize a value down to 'self' if it matches the origin of document-uri FireFox
// transforms a 'self' value into the spelled out origin, so we want to reverse this and
// bring it back.
if value.starts_with("data:")
|| value.starts_with("mediastream:")
|| value.starts_with("blob:")
|| value.starts_with("filesystem:")
|| value.starts_with("http:")
|| value.starts_with("https:")
|| value.starts_with("file:")
{
if document_uri == normalize_uri(value) {
return Cow::Borrowed("'self'");
}
// Their rule had an explicit scheme, so let's respect that
return Cow::Borrowed(value);
}
// Value doesn't have a scheme, but let's see if their hostnames match at least, if so,
// they're the same.
if value == document_uri {
return Cow::Borrowed("'self'");
}
// Now we need to stitch on a scheme to the value, but let's not stitch on the boring
// values.
let original_uri = match self.document_uri {
Some(ref u) => &u,
None => "",
};
match original_uri.splitn(2, ':').next().unwrap_or_default() {
"http" | "https" => Cow::Borrowed(value),
scheme => Cow::Owned(unsplit_uri(scheme, value)),
}
}
fn get_culprit(&self) -> String {
if self.violated_directive.is_empty() {
return String::new();
}
let mut bits = self.violated_directive.split_ascii_whitespace();
let mut culprit = bits.next().unwrap_or_default().to_owned();
let document_uri = self.document_uri.as_deref().unwrap_or("");
let normalized_uri = normalize_uri(document_uri);
for bit in bits {
write!(culprit, " {}", self.normalize_value(bit, &normalized_uri)).ok();
}
culprit
}
fn get_tags(&self, effective_directive: CspDirective) -> Tags {
Tags(PairList::from(vec![
Annotated::new(TagEntry(
Annotated::new("effective-directive".to_string()),
Annotated::new(effective_directive.to_string()),
)),
Annotated::new(TagEntry(
Annotated::new("blocked-uri".to_string()),
Annotated::new(self.sanitized_blocked_uri()),
)),
]))
}
fn get_request(&self) -> Request {
let headers = match self.referrer {
Some(ref referrer) if !referrer.is_empty() => {
Annotated::new(Headers(PairList(vec![Annotated::new((
Annotated::new(HeaderName::new("Referer")),
Annotated::new(HeaderValue::new(referrer.clone())),
))])))
}
Some(_) | None => Annotated::empty(),
};
Request {
url: Annotated::from(self.document_uri.clone()),
headers,
..Request::default()
}
}
}
/// Defines external, RFC-defined schema we accept, while `Csp` defines our own schema.
///
/// See `Csp` for meaning of fields.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct CspReportRaw {
csp_report: CspRaw,
}
/// Models the content of a CSP report.
///
/// Note this models the older CSP reports (report-uri policy directive).
/// The new CSP reports (using report-to policy directive) are different.
///
/// NOTE: This is the structure used inside the Event (serialization is based on Annotated
/// infrastructure). We also use a version of this structure to deserialize from raw JSON
/// via serde.
///
///
/// See <https://www.w3.org/TR/CSP3/>
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)]
pub struct Csp {
/// The directive whose enforcement caused the violation.
#[metastructure(pii = "true")]
pub effective_directive: Annotated<String>,
/// The URI of the resource that was blocked from loading by the Content Security Policy.
#[metastructure(pii = "true")]
pub blocked_uri: Annotated<String>,
/// The URI of the document in which the violation occurred.
#[metastructure(pii = "true")]
pub document_uri: Annotated<String>,
/// The original policy as specified by the Content-Security-Policy HTTP header.
pub original_policy: Annotated<String>,
/// The referrer of the document in which the violation occurred.
#[metastructure(pii = "true")]
pub referrer: Annotated<String>,
/// The HTTP status code of the resource on which the global object was instantiated.
pub status_code: Annotated<u64>,
/// The name of the policy section that was violated.
pub violated_directive: Annotated<String>,
/// The URL of the resource where the violation occurred.
pub source_file: Annotated<String>,
/// The line number in source-file on which the violation occurred.
pub line_number: Annotated<u64>,
/// The column number in source-file on which the violation occurred.
pub column_number: Annotated<u64>,
/// The first 40 characters of the inline script, event handler, or style that caused the
/// violation.
pub script_sample: Annotated<String>,
/// Policy disposition (enforce or report).
pub disposition: Annotated<String>,
/// Additional arbitrary fields for forwards compatibility.
#[metastructure(pii = "true", additional_properties)]
pub other: Object<Value>,
}
impl Csp {
pub fn apply_to_event(data: &[u8], event: &mut Event) -> Result<(), serde_json::Error> {
let raw_report = serde_json::from_slice::<CspReportRaw>(data)?;
let raw_csp = raw_report.csp_report;
let effective_directive = raw_csp
.effective_directive()
.map_err(serde::de::Error::custom)?;
event.logentry = Annotated::new(LogEntry::from(raw_csp.get_message(effective_directive)));
event.culprit = Annotated::new(raw_csp.get_culprit());
event.tags = Annotated::new(raw_csp.get_tags(effective_directive));
event.request = Annotated::new(raw_csp.get_request());
event.csp = Annotated::new(raw_csp.into_protocol(effective_directive));
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ExpectCtStatus {
Unknown,
Valid,
Invalid,
}
derive_fromstr_and_display!(ExpectCtStatus, InvalidSecurityError, {
ExpectCtStatus::Unknown => "unknown",
ExpectCtStatus::Valid => "valid",
ExpectCtStatus::Invalid => "invalid",
});
impl_str_serde!(ExpectCtStatus);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ExpectCtSource {
TlsExtension,
Ocsp,
Embedded,
}
derive_fromstr_and_display!(ExpectCtSource, InvalidSecurityError, {
ExpectCtSource::TlsExtension => "tls-extension",
ExpectCtSource::Ocsp => "ocsp",
ExpectCtSource::Embedded => "embedded",
});
impl_str_serde!(ExpectCtSource);
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct SingleCertificateTimestampRaw {
version: Option<i64>,
status: Option<ExpectCtStatus>,
source: Option<ExpectCtSource>,
serialized_sct: Option<String>, // NOT kebab-case!
}
impl SingleCertificateTimestampRaw {
fn into_protocol(self) -> SingleCertificateTimestamp {
SingleCertificateTimestamp {
version: Annotated::from(self.version),
status: Annotated::from(self.status.map(|s| s.to_string())),
source: Annotated::from(self.source.map(|s| s.to_string())),
serialized_sct: Annotated::from(self.serialized_sct),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct ExpectCtRaw {
#[serde(with = "serde_date_time_3339")]
date_time: Option<DateTime<Utc>>,
hostname: String,
port: Option<i64>,
effective_expiration_date: Option<DateTime<Utc>>,
served_certificate_chain: Option<Vec<String>>,
validated_certificate_chain: Option<Vec<String>>,
scts: Option<Vec<SingleCertificateTimestampRaw>>,
}
mod serde_date_time_3339 {
use super::*;
use serde::de::Visitor;
pub fn serialize<S>(date_time: &Option<DateTime<Utc>>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match date_time {
None => serializer.serialize_none(),
Some(d) => serializer.serialize_str(&d.to_rfc3339()),
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
where
D: serde::Deserializer<'de>,
{
struct DateTimeVisitor;
impl<'de> Visitor<'de> for DateTimeVisitor {
type Value = Option<DateTime<Utc>>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("expected a date-time in RFC 3339 format")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
DateTime::parse_from_rfc3339(s)
.map(|d| Some(d.with_timezone(&Utc)))
.map_err(serde::de::Error::custom)
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}
}
deserializer.deserialize_any(DateTimeVisitor)
}
}
impl ExpectCtRaw {
fn get_message(&self) -> String {
format!("Expect-CT failed for '{}'", self.hostname)
}
fn into_protocol(self) -> ExpectCt {
ExpectCt {
date_time: Annotated::from(self.date_time.map(|d| d.to_rfc3339())),
hostname: Annotated::from(self.hostname),
port: Annotated::from(self.port),
effective_expiration_date: Annotated::from(
self.effective_expiration_date.map(|d| d.to_rfc3339()),
),
served_certificate_chain: Annotated::new(
self.served_certificate_chain
.map(|s| s.into_iter().map(Annotated::from).collect())
.unwrap_or_default(),
),
validated_certificate_chain: Annotated::new(
self.validated_certificate_chain
.map(|v| v.into_iter().map(Annotated::from).collect())
.unwrap_or_default(),
),
scts: Annotated::from(self.scts.map(|scts| {
scts.into_iter()
.map(|elm| Annotated::from(elm.into_protocol()))
.collect()
})),
}
}
fn get_culprit(&self) -> String {
self.hostname.clone()
}
fn get_tags(&self) -> Tags {
let mut tags = vec![Annotated::new(TagEntry(
Annotated::new("hostname".to_string()),
Annotated::new(self.hostname.clone()),
))];
if let Some(port) = self.port {
tags.push(Annotated::new(TagEntry(
Annotated::new("port".to_string()),
Annotated::new(port.to_string()),
)));
}
Tags(PairList::from(tags))
}
fn get_request(&self) -> Request {
Request {
url: Annotated::from(self.hostname.clone()),
..Request::default()
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct ExpectCtReportRaw {
expect_ct_report: ExpectCtRaw,
}
/// Object used in ExpectCt reports
///
/// See https://tools.ietf.org/html/draft-ietf-httpbis-expect-ct-07#section-3.1
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)]
pub struct SingleCertificateTimestamp {
pub version: Annotated<i64>,
pub status: Annotated<String>,
pub source: Annotated<String>,
pub serialized_sct: Annotated<String>,
}
/// Expect CT security report sent by user agent (browser).
///
/// See <https://tools.ietf.org/html/draft-ietf-httpbis-expect-ct-07#section-3.1>
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)]
pub struct ExpectCt {
/// Date time in rfc3339 format YYYY-MM-DDTHH:MM:DD{.FFFFFF}(Z|+/-HH:MM)
/// UTC time that the UA observed the CT compliance failure
pub date_time: Annotated<String>,
/// The hostname to which the UA made the original request that failed the CT compliance check.
pub hostname: Annotated<String>,
pub port: Annotated<i64>,
/// Date time in rfc3339 format
pub effective_expiration_date: Annotated<String>,
pub served_certificate_chain: Annotated<Array<String>>,
pub validated_certificate_chain: Annotated<Array<String>>,
pub scts: Annotated<Array<SingleCertificateTimestamp>>,
}
impl ExpectCt {
pub fn apply_to_event(data: &[u8], event: &mut Event) -> Result<(), serde_json::Error> {
let raw_report = serde_json::from_slice::<ExpectCtReportRaw>(data)?;
let raw_expect_ct = raw_report.expect_ct_report;
event.logentry = Annotated::new(LogEntry::from(raw_expect_ct.get_message()));
event.culprit = Annotated::new(raw_expect_ct.get_culprit());
event.tags = Annotated::new(raw_expect_ct.get_tags());
event.request = Annotated::new(raw_expect_ct.get_request());
event.expectct = Annotated::new(raw_expect_ct.into_protocol());
Ok(())
}
}
/// Defines external, RFC-defined schema we accept, while `Hpkp` defines our own schema.
///
/// See `Hpkp` for meaning of fields.
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct HpkpRaw {
#[serde(skip_serializing_if = "Option::is_none")]
date_time: Option<DateTime<Utc>>,
hostname: String,
#[serde(skip_serializing_if = "Option::is_none")]
port: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
effective_expiration_date: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
include_subdomains: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
noted_hostname: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
served_certificate_chain: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
validated_certificate_chain: Option<Vec<String>>,
known_pins: Vec<String>,
#[serde(flatten)]
other: BTreeMap<String, serde_json::Value>,
}
impl HpkpRaw {
fn get_message(&self) -> String {
format!(
"Public key pinning validation failed for '{}'",
self.hostname
)
}
fn into_protocol(self) -> Hpkp {
Hpkp {
date_time: Annotated::from(self.date_time.map(|d| d.to_rfc3339())),
hostname: Annotated::new(self.hostname),
port: Annotated::from(self.port),
effective_expiration_date: Annotated::from(
self.effective_expiration_date.map(|d| d.to_rfc3339()),
),
include_subdomains: Annotated::from(self.include_subdomains),
noted_hostname: Annotated::from(self.noted_hostname),
served_certificate_chain: Annotated::from(
self.served_certificate_chain
.map(|chain| chain.into_iter().map(Annotated::from).collect()),
),
validated_certificate_chain: Annotated::from(
self.validated_certificate_chain
.map(|chain| chain.into_iter().map(Annotated::from).collect()),
),
known_pins: Annotated::new(self.known_pins.into_iter().map(Annotated::from).collect()),
other: self
.other
.into_iter()
.map(|(k, v)| (k, Annotated::from(v)))
.collect(),
}
}
fn get_tags(&self) -> Tags {
let mut tags = vec![Annotated::new(TagEntry(
Annotated::new("hostname".to_string()),
Annotated::new(self.hostname.clone()),
))];
if let Some(port) = self.port {
tags.push(Annotated::new(TagEntry(
Annotated::new("port".to_string()),
Annotated::new(port.to_string()),
)));
}
if let Some(include_subdomains) = self.include_subdomains {
tags.push(Annotated::new(TagEntry(
Annotated::new("include-subdomains".to_string()),
Annotated::new(include_subdomains.to_string()),
)));
}
Tags(PairList::from(tags))
}
fn get_request(&self) -> Request {
Request {
url: Annotated::from(self.hostname.clone()),
..Request::default()
}
}
}
/// Schema as defined in RFC7469, Section 3
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)]
pub struct Hpkp {
/// Indicates the time the UA observed the Pin Validation failure.
pub date_time: Annotated<String>,
/// Hostname to which the UA made the original request that failed Pin Validation.
pub hostname: Annotated<String>,
/// The port to which the UA made the original request that failed Pin Validation.
pub port: Annotated<u64>,
/// Effective Expiration Date for the noted pins.
pub effective_expiration_date: Annotated<String>,
/// Indicates whether or not the UA has noted the includeSubDomains directive for the Known
/// Pinned Host.
pub include_subdomains: Annotated<bool>,
/// Indicates the hostname that the UA noted when it noted the Known Pinned Host. This field
/// allows operators to understand why Pin Validation was performed for, e.g., foo.example.com
/// when the noted Known Pinned Host was example.com with includeSubDomains set.
pub noted_hostname: Annotated<String>,
/// The certificate chain, as served by the Known Pinned Host during TLS session setup. It
/// is provided as an array of strings; each string pem1, ... pemN is the Privacy-Enhanced Mail
/// (PEM) representation of each X.509 certificate as described in [RFC7468].
///
/// [RFC7468]: https://tools.ietf.org/html/rfc7468
pub served_certificate_chain: Annotated<Array<String>>,
/// The certificate chain, as constructed by the UA during certificate chain verification.
pub validated_certificate_chain: Annotated<Array<String>>,
/// Pins that the UA has noted for the Known Pinned Host.
// TODO: regex this string for 'pin-sha256="ABC123"' syntax
#[metastructure(required = "true")]
pub known_pins: Annotated<Array<String>>,
#[metastructure(pii = "true", additional_properties)]
pub other: Object<Value>,
}
impl Hpkp {
pub fn apply_to_event(data: &[u8], event: &mut Event) -> Result<(), serde_json::Error> {
let raw_hpkp = serde_json::from_slice::<HpkpRaw>(data)?;
event.logentry = Annotated::new(LogEntry::from(raw_hpkp.get_message()));
event.tags = Annotated::new(raw_hpkp.get_tags());
event.request = Annotated::new(raw_hpkp.get_request());
event.hpkp = Annotated::new(raw_hpkp.into_protocol());
Ok(())
}
}
/// Defines external, RFC-defined schema we accept, while `ExpectStaple` defines our own schema.
///
/// See `ExpectStaple` for meaning of fields.
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct ExpectStapleReportRaw {
expect_staple_report: ExpectStapleRaw,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExpectStapleResponseStatus {
Missing,
Provided,
ErrorResponse,
BadProducedAt,
NoMatchingResponse,
InvalidDate,
ParseResponseError,
ParseResponseDataError,
}
derive_fromstr_and_display!(ExpectStapleResponseStatus, InvalidSecurityError, {
ExpectStapleResponseStatus::Missing => "MISSING",
ExpectStapleResponseStatus::Provided => "PROVIDED",
ExpectStapleResponseStatus::ErrorResponse => "ERROR_RESPONSE",
ExpectStapleResponseStatus::BadProducedAt => "BAD_PRODUCED_AT",
ExpectStapleResponseStatus::NoMatchingResponse => "NO_MATCHING_RESPONSE",
ExpectStapleResponseStatus::InvalidDate => "INVALID_DATE",
ExpectStapleResponseStatus::ParseResponseError => "PARSE_RESPONSE_ERROR",
ExpectStapleResponseStatus::ParseResponseDataError => "PARSE_RESPONSE_DATA_ERROR",
});
impl_str_serde!(ExpectStapleResponseStatus);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExpectStapleCertStatus {
Good,
Revoked,
Unknown,
}
derive_fromstr_and_display!(ExpectStapleCertStatus, InvalidSecurityError, {
ExpectStapleCertStatus::Good => "GOOD",
ExpectStapleCertStatus::Revoked => "REVOKED",
ExpectStapleCertStatus::Unknown => "UNKNOWN",
});
impl_str_serde!(ExpectStapleCertStatus);
/// Inner (useful) part of a Expect Stable report as sent by a user agent ( browser)
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct ExpectStapleRaw {
#[serde(skip_serializing_if = "Option::is_none")]
date_time: Option<DateTime<Utc>>,
hostname: String,
#[serde(skip_serializing_if = "Option::is_none")]
port: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
effective_expiration_date: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
response_status: Option<ExpectStapleResponseStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
ocsp_response: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
cert_status: Option<ExpectStapleCertStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
served_certificate_chain: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
validated_certificate_chain: Option<Vec<String>>,
}
impl ExpectStapleRaw {
fn get_message(&self) -> String {
format!("Expect-Staple failed for '{}'", self.hostname)
}
fn into_protocol(self) -> ExpectStaple {
ExpectStaple {
date_time: Annotated::from(self.date_time.map(|d| d.to_rfc3339())),
hostname: Annotated::from(self.hostname),
port: Annotated::from(self.port),
effective_expiration_date: Annotated::from(
self.effective_expiration_date.map(|d| d.to_rfc3339()),
),
response_status: Annotated::from(self.response_status.map(|rs| rs.to_string())),
cert_status: Annotated::from(self.cert_status.map(|cs| cs.to_string())),
served_certificate_chain: Annotated::from(
self.served_certificate_chain
.map(|cert_chain| cert_chain.into_iter().map(Annotated::from).collect()),
),
validated_certificate_chain: Annotated::from(
self.validated_certificate_chain
.map(|cert_chain| cert_chain.into_iter().map(Annotated::from).collect()),
),
ocsp_response: Annotated::from(self.ocsp_response),
}
}
fn get_culprit(&self) -> String {
self.hostname.clone()
}
fn get_tags(&self) -> Tags {
let mut tags = vec![Annotated::new(TagEntry(
Annotated::new("hostname".to_string()),
Annotated::new(self.hostname.clone()),
))];
if let Some(port) = self.port {
tags.push(Annotated::new(TagEntry(
Annotated::new("port".to_string()),
Annotated::new(port.to_string()),
)));
}
if let Some(response_status) = self.response_status {
tags.push(Annotated::new(TagEntry(
Annotated::new("response_status".to_string()),
Annotated::new(response_status.to_string()),
)));
}
if let Some(cert_status) = self.cert_status {
tags.push(Annotated::new(TagEntry(
Annotated::new("cert_status".to_string()),
Annotated::new(cert_status.to_string()),
)));
}
Tags(PairList::from(tags))
}
fn get_request(&self) -> Request {
Request {
url: Annotated::from(self.hostname.clone()),
..Request::default()
}
}
}
/// Represents an Expect Staple security report.
///
/// See <https://scotthelme.co.uk/ocsp-expect-staple/> for specification.
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)]
pub struct ExpectStaple {
date_time: Annotated<String>,
hostname: Annotated<String>,
port: Annotated<i64>,
effective_expiration_date: Annotated<String>,
response_status: Annotated<String>,
cert_status: Annotated<String>,
served_certificate_chain: Annotated<Array<String>>,
validated_certificate_chain: Annotated<Array<String>>,
ocsp_response: Annotated<Value>,
}