forked from gocsaf/csaf
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprocessor.go
More file actions
1572 lines (1367 loc) · 40.8 KB
/
Copy pathprocessor.go
File metadata and controls
1572 lines (1367 loc) · 40.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
// This file is Free Software under the Apache-2.0 License
// without warranty, see README.md and LICENSES/Apache-2.0.txt for details.
//
// SPDX-License-Identifier: Apache-2.0
//
// SPDX-FileCopyrightText: 2021 German Federal Office for Information Security (BSI) <https://www.bsi.bund.de>
// Software-Engineering: 2021 Intevation GmbH <https://intevation.de>
package main
import (
"bufio"
"bytes"
"crypto/sha256"
"crypto/sha512"
"crypto/tls"
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/gocsaf/csaf/v3/internal/misc"
"github.com/ProtonMail/gopenpgp/v2/crypto"
"golang.org/x/time/rate"
"github.com/gocsaf/csaf/v3/csaf"
"github.com/gocsaf/csaf/v3/util"
)
// topicMessages stores the collected topicMessages for a specific topic.
type topicMessages []Message
type processor struct {
cfg *config
validator csaf.RemoteValidator
client util.Client
unauthClient util.Client
redirects map[string][]string
noneTLS util.Set[string]
alreadyChecked map[string]whereType
pmdURL string
pmd256 []byte
pmd any
keys *crypto.KeyRing
labelChecker labelChecker
timesChanges map[string]time.Time
timesAdv map[string]time.Time
invalidAdvisories topicMessages
badFilenames topicMessages
badIntegrities topicMessages
badPGPs topicMessages
badSignatures topicMessages
badProviderMetadata topicMessages
badSecurity topicMessages
badIndices topicMessages
badChanges topicMessages
badFolders topicMessages
badWellknownMetadata topicMessages
badDNSPath topicMessages
badDirListings topicMessages
badROLIEFeed topicMessages
badROLIEService topicMessages
badROLIECategory topicMessages
badWhitePermissions topicMessages
badAmberRedPermissions topicMessages
expr *util.PathEval
}
// reporter is implemented by any value that has a report method.
// The implementation of the report controls how to test
// the respective requirement and generate the report.
type reporter interface {
report(*processor, *Domain)
}
// errContinue indicates that the current check should continue.
var errContinue = errors.New("continue")
type whereType byte
const (
rolieMask = whereType(1) << iota
indexMask
changesMask
listingMask
)
func (wt whereType) String() string {
switch wt {
case rolieMask:
return "ROLIE"
case indexMask:
return "index.txt"
case changesMask:
return "changes.csv"
case listingMask:
return "directory listing"
default:
var mixed []string
for mask := rolieMask; mask <= changesMask; mask <<= 1 {
if x := wt & mask; x == mask {
mixed = append(mixed, x.String())
}
}
return strings.Join(mixed, "|")
}
}
// add adds a message to this topic.
func (m *topicMessages) add(typ MessageType, format string, args ...any) {
*m = append(*m, Message{Type: typ, Text: fmt.Sprintf(format, args...)})
}
// error adds an error message to this topic.
func (m *topicMessages) error(format string, args ...any) {
m.add(ErrorType, format, args...)
}
// warn adds a warning message to this topic.
func (m *topicMessages) warn(format string, args ...any) {
m.add(WarnType, format, args...)
}
// info adds an info message to this topic.
func (m *topicMessages) info(format string, args ...any) {
m.add(InfoType, format, args...)
}
// use signals that we're going to use this topic.
func (m *topicMessages) use() {
if *m == nil {
*m = []Message{}
}
}
// reset resets the messages to this topic.
func (m *topicMessages) reset() { *m = nil }
// used returns true if we have used this topic.
func (m *topicMessages) used() bool { return *m != nil }
// hasErrors checks if there are any error messages.
func (m *topicMessages) hasErrors() bool {
if !m.used() {
return false
}
for _, msg := range *m {
if msg.Type == ErrorType {
return true
}
}
return false
}
// newProcessor returns an initialized processor.
func newProcessor(cfg *config) (*processor, error) {
var validator csaf.RemoteValidator
if cfg.RemoteValidator != "" {
validatorOptions := csaf.RemoteValidatorOptions{
URL: cfg.RemoteValidator,
Presets: cfg.RemoteValidatorPresets,
Cache: cfg.RemoteValidatorCache,
}
var err error
if validator, err = validatorOptions.Open(); err != nil {
return nil, fmt.Errorf(
"preparing remote validator failed: %w", err)
}
}
return &processor{
cfg: cfg,
alreadyChecked: map[string]whereType{},
expr: util.NewPathEval(),
validator: validator,
labelChecker: labelChecker{
advisories: map[csaf.TLPLabel]util.Set[string]{},
whiteAdvisories: map[identifier]bool{},
},
timesAdv: map[string]time.Time{},
timesChanges: map[string]time.Time{},
noneTLS: util.Set[string]{},
}, nil
}
// close closes external ressources of the processor.
func (p *processor) close() {
if p.validator != nil {
p.validator.Close()
p.validator = nil
}
}
// reset clears the fields values of the given processor.
func (p *processor) reset() {
p.redirects = nil
p.pmdURL = ""
p.pmd256 = nil
p.pmd = nil
p.keys = nil
clear(p.alreadyChecked)
clear(p.noneTLS)
clear(p.timesAdv)
clear(p.timesChanges)
p.invalidAdvisories.reset()
p.badFilenames.reset()
p.badIntegrities.reset()
p.badPGPs.reset()
p.badSignatures.reset()
p.badProviderMetadata.reset()
p.badSecurity.reset()
p.badIndices.reset()
p.badChanges.reset()
p.badFolders.reset()
p.badWellknownMetadata.reset()
p.badDNSPath.reset()
p.badDirListings.reset()
p.badROLIEFeed.reset()
p.badROLIEService.reset()
p.badROLIECategory.reset()
p.badWhitePermissions.reset()
p.badAmberRedPermissions.reset()
p.labelChecker.reset()
}
// run calls checkDomain function for each domain in the given "domains" parameter.
// Then it calls the report method on each report from the given "reporters" parameter for each domain.
// It returns a pointer to the report and nil, otherwise an error.
func (p *processor) run(domains []string) (*Report, error) {
report := Report{
Date: ReportTime{Time: time.Now().UTC()},
Version: util.SemVersion,
TimeRange: p.cfg.Range,
}
for _, d := range domains {
p.reset()
if !p.checkProviderMetadata(d) {
// We need to fail the domain if the PMD cannot be parsed.
p.badProviderMetadata.use()
p.badProviderMetadata.error("Could not parse the Provider-Metadata.json of: %s", d)
}
if err := p.checkDomain(d); err != nil {
p.badProviderMetadata.use()
p.badProviderMetadata.error("Failed to find valid provider-metadata.json for domain %s: %v. ", d, err)
}
domain := &Domain{Name: d}
if err := p.fillMeta(domain); err != nil {
log.Printf("Filling meta data failed: %v\n", err)
// reporters depend on role.
continue
}
if domain.Role == nil {
log.Printf("No role found in meta data for domain %q\n", d)
// Assume trusted provider to continue report generation
role := csaf.MetadataRoleTrustedProvider
domain.Role = &role
}
rules := roleRequirements(*domain.Role)
// TODO: store error base on rules eval in report.
if rules == nil {
log.Printf(
"WARN: Cannot find requirement rules for role %q. Assuming trusted provider.\n",
*domain.Role)
rules = trustedProviderRules
}
// 18, 19, 20 should always be checked.
for _, r := range rules.reporters([]int{18, 19, 20}) {
r.report(p, domain)
}
domain.Passed = rules.eval(p)
report.Domains = append(report.Domains, domain)
}
return &report, nil
}
// fillMeta fills the report with extra informations from provider metadata.
func (p *processor) fillMeta(domain *Domain) error {
if p.pmd == nil {
return nil
}
var (
pub csaf.Publisher
role csaf.MetadataRole
)
if err := p.expr.Match([]util.PathEvalMatcher{
{Expr: `$.publisher`, Action: util.ReMarshalMatcher(&pub), Optional: true},
{Expr: `$.role`, Action: util.ReMarshalMatcher(&role), Optional: true},
}, p.pmd); err != nil {
return err
}
domain.Publisher = &pub
domain.Role = &role
return nil
}
// domainChecks compiles a list of checks which should be performed
// for a given domain.
func (p *processor) domainChecks(domain string) []func(*processor, string) error {
// If we have a direct domain url we dont need to
// perform certain checks.
direct := strings.HasPrefix(domain, "https://")
checks := []func(*processor, string) error{
(*processor).checkPGPKeys,
}
if !direct {
checks = append(checks, (*processor).checkWellknownSecurityDNS)
} else {
p.badSecurity.use()
p.badSecurity.info(
"Performed no test of security.txt " +
"since the direct url of the provider-metadata.json was used.")
p.badWellknownMetadata.use()
p.badWellknownMetadata.info(
"Performed no test on whether the provider-metadata.json is available " +
"under the .well-known path " +
"since the direct url of the provider-metadata.json was used.")
p.badDNSPath.use()
p.badDNSPath.info(
"Performed no test on the contents of https://csaf.data.security.DOMAIN " +
"since the direct url of the provider-metadata.json was used.")
}
checks = append(checks,
(*processor).checkCSAFs,
(*processor).checkMissing,
(*processor).checkInvalid,
(*processor).checkListing,
(*processor).checkWhitePermissions,
)
return checks
}
// checkDomain runs a set of domain specific checks on a given
// domain.
func (p *processor) checkDomain(domain string) error {
for _, check := range p.domainChecks(domain) {
if err := check(p, domain); err != nil {
if err == errContinue {
continue
}
return err
}
}
return nil
}
// checkTLS parses the given URL to check its schema, as a result it sets
// the value of "noneTLS" field if it is not HTTPS.
func (p *processor) checkTLS(u string) {
if x, err := url.Parse(u); err == nil && x.Scheme != "https" {
p.noneTLS.Add(u)
}
}
func (p *processor) markChecked(s string, mask whereType) bool {
v, ok := p.alreadyChecked[s]
p.alreadyChecked[s] = v | mask
return ok
}
func (p *processor) checkRedirect(r *http.Request, via []*http.Request) error {
url := r.URL.String()
p.checkTLS(url)
if p.redirects == nil {
p.redirects = map[string][]string{}
}
if redirects := p.redirects[url]; len(redirects) == 0 {
redirects = make([]string, len(via))
for i, v := range via {
redirects[i] = v.URL.String()
}
p.redirects[url] = redirects
}
if len(via) > 10 {
return errors.New("too many redirections")
}
return nil
}
// fullClient returns a fully configure HTTP client.
func (p *processor) fullClient() util.Client {
hClient := http.Client{}
hClient.CheckRedirect = p.checkRedirect
var tlsConfig tls.Config
if p.cfg.Insecure {
tlsConfig.InsecureSkipVerify = true
}
if len(p.cfg.clientCerts) != 0 {
tlsConfig.Certificates = p.cfg.clientCerts
}
hClient.Transport = &http.Transport{
TLSClientConfig: &tlsConfig,
Proxy: http.ProxyFromEnvironment,
}
client := util.Client(&hClient)
// Add extra headers.
client = &util.HeaderClient{
Client: client,
Header: p.cfg.ExtraHeader,
}
// Add optional URL logging.
if p.cfg.Verbose {
client = &util.LoggingClient{Client: client}
}
// Add optional rate limiting.
if p.cfg.Rate != nil {
client = &util.LimitingClient{
Client: client,
Limiter: rate.NewLimiter(rate.Limit(*p.cfg.Rate), 1),
}
}
return client
}
// basicClient returns a http Client w/o certs and headers.
func (p *processor) basicClient() *http.Client {
if p.cfg.Insecure {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Proxy: http.ProxyFromEnvironment,
}
return &http.Client{Transport: tr}
}
return &http.Client{}
}
// httpClient returns a cached HTTP client to be used to
// download remote ressources.
func (p *processor) httpClient() util.Client {
if p.client == nil {
p.client = p.fullClient()
}
return p.client
}
// unauthorizedClient returns a cached HTTP client without
// authentification.
func (p *processor) unauthorizedClient() util.Client {
if p.unauthClient == nil {
p.unauthClient = p.basicClient()
}
return p.unauthClient
}
// usedAuthorizedClient tells if an authorized client is used
// for downloading.
func (p *processor) usedAuthorizedClient() bool {
return p.cfg.protectedAccess()
}
// rolieFeedEntries loads the references to the advisory files for a given feed.
func (p *processor) rolieFeedEntries(feed string) ([]csaf.AdvisoryFile, error) {
client := p.httpClient()
res, err := client.Get(feed)
p.badDirListings.use()
if err != nil {
p.badProviderMetadata.error("Cannot fetch feed %s: %v", feed, err)
return nil, errContinue
}
if res.StatusCode != http.StatusOK {
p.badProviderMetadata.warn("Fetching %s failed. Status code %d (%s)",
feed, res.StatusCode, res.Status)
return nil, errContinue
}
rfeed, rolieDoc, err := func() (*csaf.ROLIEFeed, any, error) {
defer res.Body.Close()
all, err := io.ReadAll(res.Body)
if err != nil {
return nil, nil, err
}
rfeed, err := csaf.LoadROLIEFeed(bytes.NewReader(all))
if err != nil {
return nil, nil, fmt.Errorf("%s: %v", feed, err)
}
var rolieDoc any
err = misc.StrictJSONParse(bytes.NewReader(all), &rolieDoc)
return rfeed, rolieDoc, err
}()
if err != nil {
p.badProviderMetadata.error("Loading ROLIE feed failed: %v.", err)
return nil, errContinue
}
if rfeed.CountEntries() == 0 {
p.badROLIEFeed.warn("No entries in %s", feed)
}
errors, err := csaf.ValidateROLIE(rolieDoc)
if err != nil {
return nil, err
}
if len(errors) > 0 {
p.badProviderMetadata.error("%s: Validating against JSON schema failed:", feed)
for _, msg := range errors {
p.badProviderMetadata.error("%s", strings.ReplaceAll(msg, `%`, `%%`))
}
}
// Extract the CSAF files from feed.
var files []csaf.AdvisoryFile
rfeed.Entries(func(entry *csaf.Entry) {
// Filter if we have date checking.
if accept := p.cfg.Range; accept != nil {
if t := time.Time(entry.Updated); !t.IsZero() && !accept.Contains(t) {
return
}
}
var url, sha256, sha512, sign string
for i := range entry.Link {
link := &entry.Link[i]
lower := strings.ToLower(link.HRef)
switch link.Rel {
case "self":
if !strings.HasSuffix(lower, ".json") {
p.badProviderMetadata.warn(
`ROLIE feed entry link %s in %s with "rel": "self" has unexpected file extension.`,
link.HRef, feed)
}
url = link.HRef
case "signature":
if !strings.HasSuffix(lower, ".asc") {
p.badProviderMetadata.warn(
`ROLIE feed entry link %s in %s with "rel": "signature" has unexpected file extension.`,
link.HRef, feed)
}
sign = link.HRef
case "hash":
switch {
case strings.HasSuffix(lower, "sha256"):
sha256 = link.HRef
case strings.HasSuffix(lower, "sha512"):
sha512 = link.HRef
default:
p.badProviderMetadata.warn(
`ROLIE feed entry link %s in %s with "rel": "hash" has unsupported file extension.`,
link.HRef, feed)
}
}
}
if url == "" {
p.badProviderMetadata.warn(
`ROLIE feed %s contains entry link with no "self" URL.`, feed)
return
}
var file csaf.AdvisoryFile
switch {
case sha256 == "" && sha512 != "":
p.badROLIEFeed.info("%s has no sha256 hash file listed", url)
case sha256 != "" && sha512 == "":
p.badROLIEFeed.info("%s has no sha512 hash file listed", url)
case sha256 == "" && sha512 == "":
p.badROLIEFeed.error("No hash listed on ROLIE feed %s", url)
case sign == "":
p.badROLIEFeed.error("No signature listed on ROLIE feed %s", url)
}
file = csaf.PlainAdvisoryFile{Path: url, SHA256: sha256, SHA512: sha512, Sign: sign}
files = append(files, file)
})
return files, nil
}
// makeAbsolute returns a function that checks if a given
// URL is absolute or not. If not it returns an
// absolute URL based on a given base URL.
func makeAbsolute(base *url.URL) func(*url.URL) *url.URL {
return func(u *url.URL) *url.URL {
if u.IsAbs() {
return u
}
return base.JoinPath(u.String())
}
}
var yearFromURL = regexp.MustCompile(`.*/(\d{4})/[^/]+$`)
// integrity checks several csaf.AdvisoryFiles for formal
// mistakes, from conforming filenames to invalid advisories.
func (p *processor) integrity(
files []csaf.AdvisoryFile,
mask whereType,
lg func(MessageType, string, ...any),
) error {
client := p.httpClient()
var data bytes.Buffer
for _, f := range files {
fp, err := url.Parse(f.URL())
if err != nil {
lg(ErrorType, "Bad URL %s: %v", f, err)
continue
}
u := fp.String()
// Should this URL be ignored?
if p.cfg.ignoreURL(u) {
if p.cfg.Verbose {
log.Printf("Ignoring %q\n", u)
}
continue
}
if p.markChecked(u, mask) {
continue
}
p.checkTLS(u)
// Check if the filename is conforming.
p.badFilenames.use()
if !util.ConformingFileName(filepath.Base(u)) {
p.badFilenames.error("%s does not have a conforming filename.", u)
}
var folderYear *int
if m := yearFromURL.FindStringSubmatch(u); m != nil {
year, _ := strconv.Atoi(m[1])
folderYear = &year
}
res, err := client.Get(u)
if err != nil {
lg(ErrorType, "Fetching %s failed: %v.", u, err)
continue
}
if res.StatusCode != http.StatusOK {
lg(ErrorType, "Fetching %s failed: Status code %d (%s)",
u, res.StatusCode, res.Status)
continue
}
// Error if we do not get JSON.
if ct := res.Header.Get("Content-Type"); ct != "application/json" {
lg(ErrorType,
"The content type of %s should be 'application/json' but is '%s'",
u, ct)
}
s256 := sha256.New()
s512 := sha512.New()
data.Reset()
hasher := io.MultiWriter(s256, s512, &data)
var doc any
if err := func() error {
defer res.Body.Close()
tee := io.TeeReader(res.Body, hasher)
return misc.StrictJSONParse(tee, &doc)
}(); err != nil {
lg(ErrorType, "Reading %s failed: %v", u, err)
continue
}
p.invalidAdvisories.use()
// Validate against JSON schema.
errors, err := csaf.ValidateCSAF(doc)
if err != nil {
p.invalidAdvisories.error("Failed to validate %s: %v", u, err)
continue
}
if len(errors) > 0 {
p.invalidAdvisories.error("CSAF file %s has %d validation errors.", u, len(errors))
}
if err := util.IDMatchesFilename(p.expr, doc, filepath.Base(u)); err != nil {
p.badFilenames.error("%s: %v", u, err)
continue
}
// Validate against remote validator.
if p.validator != nil {
if rvr, err := p.validator.Validate(doc); err != nil {
p.invalidAdvisories.error("Calling remote validator on %s failed: %v", u, err)
} else if !rvr.Valid {
p.invalidAdvisories.error("Remote validation of %s failed.", u)
}
}
p.labelChecker.check(p, doc, u)
// Check if file is in the right folder.
p.badFolders.use()
switch date, fault := p.extractTime(doc, `initial_release_date`, u); {
case fault != "":
p.badFolders.error("%s", fault)
case folderYear == nil:
p.badFolders.error("No year folder found in %s", u)
case date.UTC().Year() != *folderYear:
p.badFolders.error("%s should be in folder %d", u, date.UTC().Year())
}
current, fault := p.extractTime(doc, `current_release_date`, u)
if fault != "" {
p.badChanges.error("%s", fault)
} else {
p.timesAdv[f.URL()] = current
}
// Check hashes
p.badIntegrities.use()
type hash struct {
ext string
url func() string
hash []byte
}
hashes := []hash{}
if f.SHA256URL() != "" {
hashes = append(hashes, hash{"SHA256", f.SHA256URL, s256.Sum(nil)})
}
if f.SHA512URL() != "" {
hashes = append(hashes, hash{"SHA512", f.SHA512URL, s512.Sum(nil)})
}
couldFetchHash := false
hashFetchErrors := []string{}
for _, x := range hashes {
hu, err := url.Parse(x.url())
if err != nil {
lg(ErrorType, "Bad URL %s: %v", x.url(), err)
continue
}
hashFile := hu.String()
p.checkTLS(hashFile)
if res, err = client.Get(hashFile); err != nil {
hashFetchErrors = append(hashFetchErrors, fmt.Sprintf("Fetching %s failed: %v.", hashFile, err))
continue
}
if res.StatusCode != http.StatusOK {
hashFetchErrors = append(hashFetchErrors, fmt.Sprintf("Fetching %s failed: Status code %d (%s)",
hashFile, res.StatusCode, res.Status))
continue
}
couldFetchHash = true
h, err := func() ([]byte, error) {
defer res.Body.Close()
return util.HashFromReader(res.Body)
}()
if err != nil {
p.badIntegrities.error("Reading %s failed: %v.", hashFile, err)
continue
}
if len(h) == 0 {
p.badIntegrities.error("No hash found in %s.", hashFile)
continue
}
if !bytes.Equal(h, x.hash) {
p.badIntegrities.error("%s hash of %s does not match %s.",
x.ext, u, hashFile)
}
}
msgType := ErrorType
// Log only as warning, if the other hash could be fetched
if couldFetchHash {
msgType = WarnType
}
if f.IsDirectory() {
msgType = InfoType
}
for _, fetchError := range hashFetchErrors {
p.badIntegrities.add(msgType, "%s", fetchError)
}
// Check signature
su, err := url.Parse(f.SignURL())
if err != nil {
lg(ErrorType, "Bad URL %s: %v", f.SignURL(), err)
continue
}
sigFile := su.String()
p.checkTLS(sigFile)
p.badSignatures.use()
if res, err = client.Get(sigFile); err != nil {
p.badSignatures.error("Fetching %s failed: %v.", sigFile, err)
continue
}
if res.StatusCode != http.StatusOK {
p.badSignatures.error("Fetching %s failed: status code %d (%s)",
sigFile, res.StatusCode, res.Status)
continue
}
sig, err := func() (*crypto.PGPSignature, error) {
defer res.Body.Close()
all, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
return crypto.NewPGPSignatureFromArmored(string(all))
}()
if err != nil {
p.badSignatures.error("Loading signature from %s failed: %v.",
sigFile, err)
continue
}
if p.keys != nil {
pm := crypto.NewPlainMessage(data.Bytes())
t := crypto.GetUnixTime()
if err := p.keys.VerifyDetached(pm, sig, t); err != nil {
p.badSignatures.error("Signature of %s could not be verified: %v.", u, err)
}
}
}
// If we tested an existing changes.csv
if len(p.timesAdv) > 0 && p.badChanges.used() {
// Iterate over all files again
for _, f := range files {
// If there was no previous error when extracting times from advisories and we have a valid time
if timeAdv, ok := p.timesAdv[f.URL()]; ok {
// If there was no previous error when extracting times from changes and the file was listed in changes.csv
if timeCha, ok := p.timesChanges[f.URL()]; ok {
// check if the time matches
if !timeAdv.Equal(timeCha) {
// if not, give an error and remove the pair so it isn't reported multiple times should integrity be called again
p.badChanges.error("Current release date in changes.csv and %s is not identical.", f.URL())
delete(p.timesAdv, f.URL())
delete(p.timesChanges, f.URL())
}
}
}
}
}
return nil
}
// extractTime extracts a time.Time value from a json document and returns it and an empty string or zero time alongside
// a string representing the error message that prevented obtaining the proper time value.
func (p *processor) extractTime(doc any, value string, u any) (time.Time, string) {
filter := "$.document.tracking." + value
date, err := p.expr.Eval(filter, doc)
if err != nil {
return time.Time{}, fmt.Sprintf("Extracting '%s' from %s failed: %v", value, u, err)
}
text, ok := date.(string)
if !ok {
return time.Time{}, fmt.Sprintf("'%s' is not a string in %s", value, u)
}
d, err := time.Parse(time.RFC3339, text)
if err != nil {
return time.Time{}, fmt.Sprintf("Parsing '%s' as RFC3339 failed in %s: %v", value, u, err)
}
return d, ""
}
// checkIndex fetches the "index.txt" and calls "checkTLS" method for HTTPS checks.
// It extracts the file names from the file and passes them to "integrity" function.
// It returns error if fetching/reading the file(s) fails, otherwise nil.
func (p *processor) checkIndex(base string, mask whereType) error {
client := p.httpClient()
bu, err := url.Parse(base)
if err != nil {
return err
}
index := bu.JoinPath("index.txt").String()
p.checkTLS(index)
p.badIndices.use()
res, err := client.Get(index)
if err != nil {
p.badIndices.error("Fetching %s failed: %v", index, err)
return errContinue
}
if res.StatusCode != http.StatusOK {
// It's optional
if res.StatusCode != http.StatusNotFound {
p.badIndices.error("Fetching %s failed. Status code %d (%s)",
index, res.StatusCode, res.Status)
} else {
p.badIndices.error("Fetching index.txt failed: %v not found.", index)
}
return errContinue
}
p.badIndices.info("Found %v", index)
files, err := func() ([]csaf.AdvisoryFile, error) {
defer res.Body.Close()
var files []csaf.AdvisoryFile
scanner := bufio.NewScanner(res.Body)
for line := 1; scanner.Scan(); line++ {
u := scanner.Text()
up, err := url.Parse(u)
if err != nil {
p.badIntegrities.error("index.txt contains invalid URL %q in line %d", u, line)
continue
}
files = append(files, csaf.DirectoryAdvisoryFile{Path: misc.JoinURL(bu, up).String()})
}
return files, scanner.Err()
}()
if err != nil {
p.badIndices.error("Reading %s failed: %v", index, err)
return errContinue
}
if len(files) == 0 {
p.badIntegrities.warn("index.txt contains no URLs")
}
// Block rolie checks.
p.labelChecker.feedLabel = ""
return p.integrity(files, mask, p.badIndices.add)
}
// checkChanges fetches the "changes.csv" and calls the "checkTLS" method for HTTPs checks.
// It extracts the file content, tests the column number and the validity of the time format
// of the fields' values and if they are sorted properly. Then it passes the files to the
// "integrity" functions. It returns error if some test fails, otherwise nil.
func (p *processor) checkChanges(base string, mask whereType) error {
bu, err := url.Parse(base)
if err != nil {
return err
}
changes := bu.JoinPath("changes.csv").String()
p.checkTLS(changes)
client := p.httpClient()
res, err := client.Get(changes)
p.badChanges.use()
if err != nil {
p.badChanges.error("Fetching %s failed: %v", changes, err)
return errContinue
}
if res.StatusCode != http.StatusOK {
if res.StatusCode != http.StatusNotFound {
// It's optional
p.badChanges.error("Fetching %s failed. Status code %d (%s)",
changes, res.StatusCode, res.Status)
} else {
p.badChanges.error("Fetching changes.csv failed: %v not found.", changes)
}
return errContinue
}
p.badChanges.info("Found %v", changes)