forked from ossf/scorecard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpinned_dependencies.go
788 lines (675 loc) · 23.9 KB
/
pinned_dependencies.go
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
// Copyright 2021 Security Scorecard Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package checks
import (
"fmt"
"path"
"regexp"
"strings"
"github.com/moby/buildkit/frontend/dockerfile/parser"
"gopkg.in/yaml.v3"
"github.com/ossf/scorecard/v2/checker"
sce "github.com/ossf/scorecard/v2/errors"
)
// CheckPinnedDependencies is the registered name for FrozenDeps.
const CheckPinnedDependencies = "Pinned-Dependencies"
// defaultShellNonWindows is the default shell used for GitHub workflow actions for Linux and Mac.
const defaultShellNonWindows = "bash"
// defaultShellWindows is the default shell used for GitHub workflow actions for Windows.
const defaultShellWindows = "pwsh"
// Structure for workflow config.
// We only declare the fields we need.
// Github workflows format: https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions
type gitHubActionWorkflowConfig struct {
Jobs map[string]gitHubActionWorkflowJob
Name string `yaml:"name"`
}
// A Github Action Workflow Job.
// We only declare the fields we need.
// Github workflows format: https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions
type gitHubActionWorkflowJob struct {
Name string `yaml:"name"`
Steps []gitHubActionWorkflowStep `yaml:"steps"`
Defaults struct {
Run struct {
Shell string `yaml:"shell"`
} `yaml:"run"`
} `yaml:"defaults"`
RunsOn stringOrSlice `yaml:"runs-on"`
Strategy struct {
Matrix struct {
Os []string `yaml:"os"`
} `yaml:"matrix"`
} `yaml:"strategy"`
}
// A Github Action Workflow Step.
// We only declare the fields we need.
// Github workflows format: https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions
type gitHubActionWorkflowStep struct {
Name string `yaml:"name"`
ID string `yaml:"id"`
Shell string `yaml:"shell"`
Run string `yaml:"run"`
If string `yaml:"if"`
Uses stringWithLine `yaml:"uses"`
}
// stringOrSlice is for fields that can be a single string or a slice of strings. If the field is a single string,
// this value will be a slice with a single string item.
type stringOrSlice []string
func (s *stringOrSlice) UnmarshalYAML(value *yaml.Node) error {
var stringSlice []string
err := value.Decode(&stringSlice)
if err == nil {
*s = stringSlice
return nil
}
var single string
err = value.Decode(&single)
if err != nil {
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("error decoding stringOrSlice Value: %v", err))
}
*s = []string{single}
return nil
}
// stringWithLine is for when you want to keep track of the line number that the string came from.
type stringWithLine struct {
Value string
Line int
}
// Structure to host information about pinned github
// or third party dependencies.
type worklowPinningResult struct {
thirdParties pinnedResult
gitHubOwned pinnedResult
}
func (ws *stringWithLine) UnmarshalYAML(value *yaml.Node) error {
err := value.Decode(&ws.Value)
if err != nil {
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("error decoding stringWithLine Value: %v", err))
}
ws.Line = value.Line
return nil
}
//nolint:gochecknoinits
func init() {
registerCheck(CheckPinnedDependencies, PinnedDependencies)
}
// PinnedDependencies will check the repository if it contains frozen dependecies.
func PinnedDependencies(c *checker.CheckRequest) checker.CheckResult {
// Lock file.
lockScore, lockErr := isPackageManagerLockFilePresent(c)
if lockErr != nil {
return checker.CreateRuntimeErrorResult(CheckPinnedDependencies, lockErr)
}
// GitHub actions.
actionScore, actionErr := isGitHubActionsWorkflowPinned(c)
if actionErr != nil {
return checker.CreateRuntimeErrorResult(CheckPinnedDependencies, actionErr)
}
// Docker files.
dockerFromScore, dockerFromErr := isDockerfilePinned(c)
if dockerFromErr != nil {
return checker.CreateRuntimeErrorResult(CheckPinnedDependencies, dockerFromErr)
}
// Docker downloads.
dockerDownloadScore, dockerDownloadErr := isDockerfileFreeOfInsecureDownloads(c)
if dockerDownloadErr != nil {
return checker.CreateRuntimeErrorResult(CheckPinnedDependencies, dockerDownloadErr)
}
// Script downloads.
scriptScore, scriptError := isShellScriptFreeOfInsecureDownloads(c)
if scriptError != nil {
return checker.CreateRuntimeErrorResult(CheckPinnedDependencies, scriptError)
}
// Action script downloads.
actionScriptScore, actionScriptError := isGitHubWorkflowScriptFreeOfInsecureDownloads(c)
if actionScriptError != nil {
return checker.CreateRuntimeErrorResult(CheckPinnedDependencies, actionScriptError)
}
// Scores may be inconclusive.
lockScore = maxScore(0, lockScore)
actionScore = maxScore(0, actionScore)
dockerFromScore = maxScore(0, dockerFromScore)
dockerDownloadScore = maxScore(0, dockerDownloadScore)
scriptScore = maxScore(0, scriptScore)
actionScriptScore = maxScore(0, actionScriptScore)
score := checker.AggregateScores(lockScore, actionScore, dockerFromScore,
dockerDownloadScore, scriptScore, actionScriptScore)
if score == checker.MaxResultScore {
return checker.CreateMaxScoreResult(CheckPinnedDependencies, "all dependencies are pinned")
}
return checker.CreateProportionalScoreResult(CheckPinnedDependencies,
"dependency not pinned by hash detected", score, checker.MaxResultScore)
}
// TODO(laurent): need to support GCB pinning.
//nolint
func maxScore(s1, s2 int) int {
if s1 > s2 {
return s1
}
return s2
}
type pinnedResult int
const (
pinnedUndefined pinnedResult = iota
pinned
notPinned
)
// For the 'to' param, true means the file is pinning dependencies (or there are no dependencies),
// false means there are unpinned dependencies.
func addPinnedResult(r *pinnedResult, to bool) {
// If the result is `notPinned`, we keep it.
// In other cases, we always update the result.
if *r == notPinned {
return
}
switch to {
case true:
*r = pinned
case false:
*r = notPinned
}
}
func dataAsWorkflowResultPointer(data FileCbData) *worklowPinningResult {
pdata, ok := data.(*worklowPinningResult)
if !ok {
// panic if it is not correct type
panic("type need to be of worklowPinningResult")
}
return pdata
}
func createReturnValuesForGitHubActionsWorkflowPinned(r worklowPinningResult, infoMsg string,
dl checker.DetailLogger, err error) (int, error) {
if err != nil {
return checker.InconclusiveResultScore, err
}
score := checker.MinResultScore
if r.gitHubOwned != notPinned {
score += 2
// TODO: set Snippet and line numbers.
dl.Info3(&checker.LogMessage{
Type: checker.FileTypeSource,
Text: fmt.Sprintf("%s %s", "GitHub-owned", infoMsg),
})
}
if r.thirdParties != notPinned {
score += 8
// TODO: set Snippet and line numbers.
dl.Info3(&checker.LogMessage{
Type: checker.FileTypeSource,
Text: fmt.Sprintf("%s %s", "Third-party", infoMsg),
})
}
return score, nil
}
func dataAsResultPointer(data FileCbData) *pinnedResult {
pdata, ok := data.(*pinnedResult)
if !ok {
// This never happens.
panic("invalid type")
}
return pdata
}
func createReturnValues(r pinnedResult, infoMsg string, dl checker.DetailLogger, err error) (int, error) {
if err != nil {
return checker.InconclusiveResultScore, err
}
switch r {
default:
panic("invalid value")
case pinned, pinnedUndefined:
dl.Info(infoMsg)
return checker.MaxResultScore, nil
case notPinned:
// No logging needed as it's done by the checks.
return checker.MinResultScore, nil
}
}
func isShellScriptFreeOfInsecureDownloads(c *checker.CheckRequest) (int, error) {
var r pinnedResult
err := CheckFilesContent("*", false, c, validateShellScriptIsFreeOfInsecureDownloads, &r)
return createReturnForIsShellScriptFreeOfInsecureDownloads(r, c.Dlogger, err)
}
func createReturnForIsShellScriptFreeOfInsecureDownloads(r pinnedResult,
dl checker.DetailLogger, err error) (int, error) {
return createReturnValues(r,
"no insecure (not pinned by hash) dependency downloads found in shell scripts",
dl, err)
}
func testValidateShellScriptIsFreeOfInsecureDownloads(pathfn string,
content []byte, dl checker.DetailLogger) (int, error) {
var r pinnedResult
_, err := validateShellScriptIsFreeOfInsecureDownloads(pathfn, content, dl, &r)
return createReturnForIsShellScriptFreeOfInsecureDownloads(r, dl, err)
}
func validateShellScriptIsFreeOfInsecureDownloads(pathfn string, content []byte,
dl checker.DetailLogger, data FileCbData) (bool, error) {
pdata := dataAsResultPointer(data)
// Validate the file type.
if !isSupportedShellScriptFile(pathfn, content) {
addPinnedResult(pdata, true)
return true, nil
}
r, err := validateShellFile(pathfn, content, dl)
if err != nil {
return false, err
}
addPinnedResult(pdata, r)
return true, nil
}
func isDockerfileFreeOfInsecureDownloads(c *checker.CheckRequest) (int, error) {
var r pinnedResult
err := CheckFilesContent("*Dockerfile*", false, c, validateDockerfileIsFreeOfInsecureDownloads, &r)
return createReturnForIsDockerfileFreeOfInsecureDownloads(r, c.Dlogger, err)
}
// Create the result.
func createReturnForIsDockerfileFreeOfInsecureDownloads(r pinnedResult,
dl checker.DetailLogger, err error) (int, error) {
return createReturnValues(r,
"no insecure (not pinned by hash) dependency downloads found in Dockerfiles",
dl, err)
}
func testValidateDockerfileIsFreeOfInsecureDownloads(pathfn string,
content []byte, dl checker.DetailLogger) (int, error) {
var r pinnedResult
_, err := validateDockerfileIsFreeOfInsecureDownloads(pathfn, content, dl, &r)
return createReturnForIsDockerfileFreeOfInsecureDownloads(r, dl, err)
}
func validateDockerfileIsFreeOfInsecureDownloads(pathfn string, content []byte,
dl checker.DetailLogger, data FileCbData) (bool, error) {
pdata := dataAsResultPointer(data)
// Return early if this is a script, e.g. script_dockerfile_something.sh
if isShellScriptFile(pathfn, content) {
addPinnedResult(pdata, true)
return true, nil
}
if !CheckFileContainsCommands(content, "#") {
addPinnedResult(pdata, true)
return true, nil
}
contentReader := strings.NewReader(string(content))
res, err := parser.Parse(contentReader)
if err != nil {
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalInvalidDockerFile, err))
}
var bytes []byte
// Walk the Dockerfile's AST.
for _, child := range res.AST.Children {
cmdType := child.Value
// Only look for the 'RUN' command.
if cmdType != "run" {
continue
}
var valueList []string
for n := child.Next; n != nil; n = n.Next {
valueList = append(valueList, n.Value)
}
if len(valueList) == 0 {
return false, sce.WithMessage(sce.ErrScorecardInternal, errInternalInvalidDockerFile.Error())
}
// Build a file content.
cmd := strings.Join(valueList, " ")
bytes = append(bytes, cmd...)
bytes = append(bytes, '\n')
}
r, err := validateShellFile(pathfn, bytes, dl)
if err != nil {
return false, err
}
addPinnedResult(pdata, r)
return true, nil
}
func isDockerfilePinned(c *checker.CheckRequest) (int, error) {
var r pinnedResult
err := CheckFilesContent("*Dockerfile*", false, c, validateDockerfileIsPinned, &r)
return createReturnForIsDockerfilePinned(r, c.Dlogger, err)
}
// Create the result.
func createReturnForIsDockerfilePinned(r pinnedResult, dl checker.DetailLogger, err error) (int, error) {
return createReturnValues(r,
"Dockerfile dependencies are pinned",
dl, err)
}
func testValidateDockerfileIsPinned(pathfn string, content []byte, dl checker.DetailLogger) (int, error) {
var r pinnedResult
_, err := validateDockerfileIsPinned(pathfn, content, dl, &r)
return createReturnForIsDockerfilePinned(r, dl, err)
}
func validateDockerfileIsPinned(pathfn string, content []byte,
dl checker.DetailLogger, data FileCbData) (bool, error) {
// Users may use various names, e.g.,
// Dockerfile.aarch64, Dockerfile.template, Dockerfile_template, dockerfile, Dockerfile-name.template
// Templates may trigger false positives, e.g. FROM { NAME }.
pdata := dataAsResultPointer(data)
// Return early if this is a script, e.g. script_dockerfile_something.sh
if isShellScriptFile(pathfn, content) {
addPinnedResult(pdata, true)
return true, nil
}
if !CheckFileContainsCommands(content, "#") {
addPinnedResult(pdata, true)
return true, nil
}
// We have what looks like a docker file.
// Let's interpret the content as utf8-encoded strings.
contentReader := strings.NewReader(string(content))
regex := regexp.MustCompile(`.*@sha256:[a-f\d]{64}`)
ret := true
pinnedAsNames := make(map[string]bool)
res, err := parser.Parse(contentReader)
if err != nil {
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalInvalidDockerFile, err))
}
for _, child := range res.AST.Children {
cmdType := child.Value
if cmdType != "from" {
continue
}
var valueList []string
for n := child.Next; n != nil; n = n.Next {
valueList = append(valueList, n.Value)
}
switch {
// scratch is no-op.
case len(valueList) > 0 && strings.EqualFold(valueList[0], "scratch"):
continue
// FROM name AS newname.
case len(valueList) == 3 && strings.EqualFold(valueList[1], "as"):
name := valueList[0]
asName := valueList[2]
// Check if the name is pinned.
// (1): name = <>@sha245:hash
// (2): name = XXX where XXX was pinned
_, pinned := pinnedAsNames[name]
if pinned || regex.Match([]byte(name)) {
// Record the asName.
pinnedAsNames[asName] = true
continue
}
// Not pinned.
ret = false
dl.Warn("dependency not pinned by hash %v: '%v'", pathfn, name)
// FROM name.
case len(valueList) == 1:
name := valueList[0]
if !regex.Match([]byte(name)) {
ret = false
dl.Warn("dependency not pinned by hash %v: '%v'", pathfn, name)
}
default:
// That should not happen.
return false, sce.WithMessage(sce.ErrScorecardInternal, errInternalInvalidDockerFile.Error())
}
}
//nolint
// The file need not have a FROM statement,
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/dockerfiles/partials/jupyter.partial.Dockerfile.
addPinnedResult(pdata, ret)
return true, nil
}
func isGitHubWorkflowScriptFreeOfInsecureDownloads(c *checker.CheckRequest) (int, error) {
var r pinnedResult
err := CheckFilesContent(".github/workflows/*", false, c, validateGitHubWorkflowIsFreeOfInsecureDownloads, &r)
return createReturnForIsGitHubWorkflowScriptFreeOfInsecureDownloads(r, c.Dlogger, err)
}
// Create the result.
func createReturnForIsGitHubWorkflowScriptFreeOfInsecureDownloads(r pinnedResult,
dl checker.DetailLogger, err error) (int, error) {
return createReturnValues(r,
"no insecure (not pinned by hash) dependency downloads found in GitHub workflows",
dl, err)
}
func testValidateGitHubWorkflowScriptFreeOfInsecureDownloads(pathfn string,
content []byte, dl checker.DetailLogger) (int, error) {
var r pinnedResult
_, err := validateGitHubWorkflowIsFreeOfInsecureDownloads(pathfn, content, dl, &r)
return createReturnForIsGitHubWorkflowScriptFreeOfInsecureDownloads(r, dl, err)
}
// validateGitHubWorkflowIsFreeOfInsecureDownloads checks if the workflow file downloads dependencies that are unpinned.
// Returns true if the check should continue executing after this file.
func validateGitHubWorkflowIsFreeOfInsecureDownloads(pathfn string, content []byte,
dl checker.DetailLogger, data FileCbData) (bool, error) {
if !isWorkflowFile(pathfn) {
return true, nil
}
pdata := dataAsResultPointer(data)
if !CheckFileContainsCommands(content, "#") {
addPinnedResult(pdata, true)
return true, nil
}
var workflow gitHubActionWorkflowConfig
err := yaml.Unmarshal(content, &workflow)
if err != nil {
return false, sce.WithMessage(sce.ErrScorecardInternal,
fmt.Sprintf("%v: %v", errInternalInvalidYamlFile, err))
}
githubVarRegex := regexp.MustCompile(`{{[^{}]*}}`)
validated := true
scriptContent := ""
for _, job := range workflow.Jobs {
job := job
for _, step := range job.Steps {
step := step
if step.Run == "" {
continue
}
// https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstepsrun.
shell, err := getShellForStep(&step, &job)
if err != nil {
return false, err
}
// Skip unsupported shells. We don't support Windows shells or some Unix shells.
if !isSupportedShell(shell) {
continue
}
run := step.Run
// We replace the `${{ github.variable }}` to avoid shell parsing failures.
script := githubVarRegex.ReplaceAll([]byte(run), []byte("GITHUB_REDACTED_VAR"))
scriptContent = fmt.Sprintf("%v\n%v", scriptContent, string(script))
}
}
if scriptContent != "" {
validated, err = validateShellFile(pathfn, []byte(scriptContent), dl)
if err != nil {
return false, err
}
}
addPinnedResult(pdata, validated)
return true, nil
}
// The only OS that this job runs on is Windows.
func jobAlwaysRunsOnWindows(job *gitHubActionWorkflowJob) bool {
var jobOses []string
// The 'runs-on' field either lists the OS'es directly, or it can have an expression '${{ matrix.os }}' which
// is where the OS'es are actually listed.
if len(job.RunsOn) == 1 && strings.Contains(job.RunsOn[0], "matrix.os") {
jobOses = job.Strategy.Matrix.Os
} else {
jobOses = job.RunsOn
}
for _, os := range jobOses {
if !strings.HasPrefix(strings.ToLower(os), "windows-") {
return false
}
}
return true
}
// getShellForStep returns the shell that is used to run the given step.
func getShellForStep(step *gitHubActionWorkflowStep, job *gitHubActionWorkflowJob) (string, error) {
// https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#using-a-specific-shell.
if step.Shell != "" {
return step.Shell, nil
}
if job.Defaults.Run.Shell != "" {
return job.Defaults.Run.Shell, nil
}
isStepWindows, err := isStepWindows(step)
if err != nil {
return "", err
}
if isStepWindows {
return defaultShellWindows, nil
}
if jobAlwaysRunsOnWindows(job) {
return defaultShellWindows, nil
}
return defaultShellNonWindows, nil
}
// isStepWindows returns true if the step will be run on Windows.
func isStepWindows(step *gitHubActionWorkflowStep) (bool, error) {
windowsRegexes := []string{
// Looking for "if: runner.os == 'Windows'" (and variants)
`(?i)runner\.os\s*==\s*['"]windows['"]`,
// Looking for "if: ${{ startsWith(runner.os, 'Windows') }}" (and variants)
`(?i)\$\{\{\s*startsWith\(runner\.os,\s*['"]windows['"]\)`,
// Looking for "if: matrix.os == 'windows-2019'" (and variants)
`(?i)matrix\.os\s*==\s*['"]windows-`,
}
for _, windowsRegex := range windowsRegexes {
matches, err := regexp.MatchString(windowsRegex, step.If)
if err != nil {
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("error matching Windows regex: %v", err))
}
if matches {
return true, nil
}
}
return false, nil
}
// Check pinning of github actions in workflows.
func isGitHubActionsWorkflowPinned(c *checker.CheckRequest) (int, error) {
var r worklowPinningResult
err := CheckFilesContent(".github/workflows/*", true, c, validateGitHubActionWorkflow, &r)
return createReturnForIsGitHubActionsWorkflowPinned(r, c.Dlogger, err)
}
// Create the result.
func createReturnForIsGitHubActionsWorkflowPinned(r worklowPinningResult, dl checker.DetailLogger,
err error) (int, error) {
return createReturnValuesForGitHubActionsWorkflowPinned(r,
"actions are pinned",
dl, err)
}
func testIsGitHubActionsWorkflowPinned(pathfn string, content []byte, dl checker.DetailLogger) (int, error) {
var r worklowPinningResult
_, err := validateGitHubActionWorkflow(pathfn, content, dl, &r)
return createReturnForIsGitHubActionsWorkflowPinned(r, dl, err)
}
// validateGitHubActionWorkflow checks if the workflow file contains unpinned actions. Returns true if the check
// should continue executing after this file.
func validateGitHubActionWorkflow(pathfn string, content []byte,
dl checker.DetailLogger, data FileCbData) (bool, error) {
pdata := dataAsWorkflowResultPointer(data)
if !CheckFileContainsCommands(content, "#") {
addWorkflowPinnedResult(pdata, true, true)
addWorkflowPinnedResult(pdata, true, true)
return true, nil
}
var workflow gitHubActionWorkflowConfig
err := yaml.Unmarshal(content, &workflow)
if err != nil {
return false, sce.WithMessage(sce.ErrScorecardInternal,
fmt.Sprintf("%v: %v", errInternalInvalidYamlFile, err))
}
hashRegex := regexp.MustCompile(`^.*@[a-f\d]{40,}`)
for jobName, job := range workflow.Jobs {
if len(job.Name) > 0 {
jobName = job.Name
}
for _, step := range job.Steps {
if len(step.Uses.Value) > 0 {
// Ensure a hash at least as large as SHA1 is used (40 hex characters).
// Example: action-name@hash
match := hashRegex.Match([]byte(step.Uses.Value))
if !match {
dl.Warn3(&checker.LogMessage{
Path: pathfn, Type: checker.FileTypeSource, Offset: step.Uses.Line, Snippet: step.Uses.Value,
Text: fmt.Sprintf("dependency not pinned by hash (job '%v')", jobName),
})
}
githubOwned := isGitHubOwnedAction(step.Uses.Value)
addWorkflowPinnedResult(pdata, match, githubOwned)
}
}
}
return true, nil
}
// isWorkflowFile returns true if this is a GitHub workflow file.
func isWorkflowFile(pathfn string) bool {
// From https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions:
// "Workflow files use YAML syntax, and must have either a .yml or .yaml file extension."
switch path.Ext(pathfn) {
case ".yml", ".yaml":
return true
default:
return false
}
}
// isGitHubOwnedAction check github specific action.
func isGitHubOwnedAction(v string) bool {
a := strings.HasPrefix(v, "actions/")
c := strings.HasPrefix(v, "github/")
return a || c
}
func addWorkflowPinnedResult(w *worklowPinningResult, to, isGitHub bool) {
if isGitHub {
addPinnedResult(&w.gitHubOwned, to)
} else {
addPinnedResult(&w.thirdParties, to)
}
}
// Check presence of lock files thru validatePackageManagerFile().
func isPackageManagerLockFilePresent(c *checker.CheckRequest) (int, error) {
var r pinnedResult
err := CheckIfFileExists(CheckPinnedDependencies, c, validatePackageManagerFile, &r)
if err != nil {
return checker.InconclusiveResultScore, err
}
if r != pinned {
c.Dlogger.Warn("no lock files detected for a package manager")
return checker.InconclusiveResultScore, nil
}
return checker.MaxResultScore, nil
}
// validatePackageManagerFile will validate the if frozen dependecies file name exists.
// TODO(laurent): need to differentiate between libraries and programs.
// TODO(laurent): handle multi-language repos.
func validatePackageManagerFile(name string, dl checker.DetailLogger, data FileCbData) (bool, error) {
switch strings.ToLower(name) {
// TODO(laurent): "go.mod" is for libraries
default:
return true, nil
case "go.sum":
dl.Info("go lock file detected: %s", name)
case "vendor/", "third_party/", "third-party/":
dl.Info("vendoring detected in: %s", name)
case "package-lock.json", "npm-shrinkwrap.json":
dl.Info("javascript lock file detected: %s", name)
// TODO(laurent): add check for hashbased pinning in requirements.txt - https://davidwalsh.name/hashin
// Note: because requirements.txt does not handle transitive dependencies, we consider it
// not a lock file, until we have remediation steps for pip-build.
case "pipfile.lock":
dl.Info("python lock file detected: %s", name)
case "gemfile.lock":
dl.Info("ruby lock file detected: %s", name)
case "cargo.lock":
dl.Info("rust lock file detected: %s", name)
case "yarn.lock":
dl.Info("yarn lock file detected: %s", name)
case "composer.lock":
dl.Info("composer lock file detected: %s", name)
}
pdata := dataAsResultPointer(data)
addPinnedResult(pdata, true)
return false, nil
}