-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
419 lines (362 loc) · 12.1 KB
/
main.go
File metadata and controls
419 lines (362 loc) · 12.1 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
// Copyright (c) 2025 Naren Yellavula & Cybrota contributors
// Apache License, Version 2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// Package main is the entry point for the application
package main
import (
_ "embed"
"encoding/csv"
"encoding/json"
"fmt"
"log"
"os"
"regexp"
"strings"
"time"
"github.com/cybrota/scharf/logging"
nw "github.com/cybrota/scharf/network"
sc "github.com/cybrota/scharf/scanner"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
)
const asciiLogo = `
_______ _______ _ _ _______ ______ _______
|______ | |_____| |_____| |_____/ |______
______| |_____ | | | | | \_ |
Prevent supply-chain attacks from your third-party GitHub actions!
Copyright (c) 2025 Naren Yellavula & Cybrota contributors - https://github.com/cybrota
`
var logger = logging.GetLogger(0)
const defaultUpgradeCooldownHours = 24
//go:embed version.json
var versionJSON []byte
type versionInfo struct {
Version string `json:"version"`
Commit string `json:"commit"`
Date string `json:"date"`
}
func cliVersion() string {
info := versionInfo{
Version: "dev",
Commit: "unknown",
Date: "unknown",
}
if err := json.Unmarshal(versionJSON, &info); err != nil {
return "version: dev (commit: unknown, built: unknown)"
}
if info.Version == "" {
info.Version = "dev"
}
if info.Commit == "" {
info.Commit = "unknown"
}
if info.Date == "" {
info.Date = "unknown"
}
return fmt.Sprintf("version: %s (commit: %s, built: %s)", info.Version, info.Commit, info.Date)
}
var actionSHAInputRegex = regexp.MustCompile(`^[\w.-]+/[\w.-]+@[a-f0-9]{40}$`)
func isSHAUpgradeInput(input string) bool {
return actionSHAInputRegex.MatchString(input)
}
func splitActionRef(input string) (string, string, error) {
parts := strings.SplitN(input, "@", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return "", "", fmt.Errorf("invalid action format: %s. expected owner/repo@ref-or-sha", input)
}
return parts[0], parts[1], nil
}
func validateUpgradeInput(input string, fromVersion string) error {
if _, _, err := splitActionRef(input); err != nil {
return err
}
if isSHAUpgradeInput(input) && strings.TrimSpace(fromVersion) == "" {
return fmt.Errorf("input %q looks like a pinned SHA; please provide --from-version to resolve the next upgrade", input)
}
return nil
}
func addSharedUpgradeFlags(cmd *cobra.Command) {
cmd.Flags().Int("cooldown-hours", defaultUpgradeCooldownHours, "Warn when next version is under cooldown age in hours")
cmd.Flags().Bool("dry-run", false, "Preview changes without writing files")
}
func writeToJSON(inv *sc.Inventory) {
f, _ := os.Create("findings.json")
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent(" ", " ")
enc.Encode(inv)
}
func WriteToCSV(inv *sc.Inventory) {
writeRows := [][]string{
{
"repository_name",
"branch_name",
"actions_file",
"action",
},
}
for _, ir := range inv.Records {
for _, mat := range ir.Matches {
writeRows = append(writeRows, []string{
ir.Repository,
ir.Branch,
ir.FilePath,
mat,
})
}
}
f, _ := os.Create("findings.csv")
defer f.Close()
csv_writer := csv.NewWriter(f)
csv_writer.WriteAll(writeRows)
}
func newRootCmd() *cobra.Command {
// list table configuration
tw := tablewriter.NewWriter(os.Stdout)
var cmdAudit = &cobra.Command{
Use: "audit",
Short: "🥽 Audit a local or remote Git repository to identify vulnerable actions with mutable references: 'scharf audit <repo>|<url>'",
Long: fmt.Sprintf("%s\n%s", asciiLogo, `🥽 Audit the actions and raise error if any mutable references found. Good used with Ci/CD pipelines: 'scharf audit <repo>|<url>'`),
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
then := time.Now()
rp, err := sc.BuildRepoPath("audit", args)
if err != nil {
fmt.Println(err.Error())
return
}
wfs, err := sc.AuditRepository(*rp)
if err != nil {
fmt.Printf("Not a git repository nor workflows found. Skipping checks!")
return
}
now := time.Now()
di := now.Sub(then)
if len(*wfs) > 0 {
fmt.Println(sc.FormatAuditReport(*wfs))
shouldRaise := cmd.Flag("raise-error")
if shouldRaise.Value.String() == "true" {
os.Exit(1)
}
} else {
fmt.Println("No mutable references found. Good job!")
}
fmt.Printf("Total time: %.2f s\n", di.Seconds())
},
}
cmdAudit.PersistentFlags().Bool("raise-error", false, "Raise error on any matches. Useful for interrupting CI pipelines")
var cmdAutoFix = &cobra.Command{
Use: "autofix",
Short: "🪄 Auto-fixes vulnerable third-party GitHub actions with mutable references: 'scharf autofix <repo>|<url>'",
Long: fmt.Sprintf("%s\n%s", asciiLogo, `🪄 Auto-fixes vulnerable third-party GitHub actions with mutable references: 'scharf audit <repo>|<url>'`),
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
isDryRun := cmd.Flag("dry-run")
var isDR bool
if isDryRun.Value.String() == "true" {
isDR = true
} else {
isDR = false
}
then := time.Now()
rp, err := sc.BuildRepoPath("autofix", args)
if err != nil {
fmt.Println(err.Error())
return
}
err = sc.AutoFixRepository(*rp, isDR)
if err != nil {
fmt.Println(err.Error())
fmt.Println("Not a git repository. Skipping autofix!")
return
}
now := time.Now()
di := now.Sub(then)
fmt.Printf("Total time: %.2f s\n", di.Seconds())
},
}
cmdAutoFix.PersistentFlags().Bool("dry-run", false, "Preview the fixes before actually making the changes")
var cmdFind = &cobra.Command{
Use: "find",
Short: "🔎 Find all GitHub actions with mutable references in a workspace. Should clone your Git repositories into the workspace",
Long: fmt.Sprintf("%s\n%s", asciiLogo, `🔎 Find all GitHub actions with mutable references in a workspace. Should clone your Git repositories into the workspace`),
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
root_path_flag := cmd.Flag("root")
var ho bool
head_only := cmd.Flag("head-only")
if head_only.Value.String() == "true" {
ho = true
} else {
ho = false
}
inv, err := sc.Find(root_path_flag.Value.String(), ho)
if err != nil {
log.Fatal(err.Error())
}
out_fmt_flag := cmd.Flag("out")
out_fmt := out_fmt_flag.Value.String()
switch out_fmt {
case "json":
writeToJSON(inv)
break
case "csv":
WriteToCSV(inv)
break
default:
logger.Error("The given value to --out flag is invalid. Valid values are json, csv.", "value", out_fmt)
}
},
}
var cmdLookup = &cobra.Command{
Use: "lookup",
Short: "👀 Look up the immutable commit-SHA of a given third-party GitHub action plus reference. Ex: scharf lookup actions/checkout@v4",
Long: fmt.Sprintf("%s\n%s", asciiLogo, `👀 Look up the immutable commit-SHA of a given third-party GitHub action plus reference. Ex: scharf lookup actions/checkout@v4`),
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if args[0] != "" {
s := nw.NewSHAResolver()
sha, err := s.Resolve(args[0])
if err != nil {
logger.Error("problem while fetching action SHA. Please check the action again.", "action", args[0])
}
fmt.Println(sha)
} else {
logger.Error("Please give a GitHub action to look up SHA-commit. Ex: actions/checkout@v4")
}
},
}
var cmdUpgrade = &cobra.Command{
Use: "upgrade <owner/repo@ref-or-sha>",
Short: "⬆️ Upgrade a pinned action to the next version and SHA",
Long: fmt.Sprintf("%s\n%s", asciiLogo, `⬆️ Upgrade a pinned action to the next version and SHA. Ex: scharf upgrade actions/checkout@v4`),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
input := args[0]
fromVersion, _ := cmd.Flags().GetString("from-version")
cooldownHours, _ := cmd.Flags().GetInt("cooldown-hours")
isDryRun, _ := cmd.Flags().GetBool("dry-run")
if err := validateUpgradeInput(input, fromVersion); err != nil {
cmd.SetOut(cmd.ErrOrStderr())
_ = cmd.Usage()
cmd.SilenceUsage = true
return err
}
action, refOrSHA, err := splitActionRef(input)
if err != nil {
cmd.SetOut(cmd.ErrOrStderr())
_ = cmd.Usage()
cmd.SilenceUsage = true
return err
}
currentVersion := refOrSHA
if isSHAUpgradeInput(input) {
currentVersion = fromVersion
}
resolver := nw.NewSHAResolver()
result, err := resolver.ResolveNext(action, currentVersion, cooldownHours)
if err != nil {
return err
}
if result.UnderCooldown {
fmt.Printf("%sWarning:%s %s@%s is under cooldown; proceeding with upgrade\n", sc.Yellow, sc.Reset, action, currentVersion)
}
upgradedPin := fmt.Sprintf("%s@%s # %s", action, result.NextSHA, result.NextVersion)
if isDryRun {
fmt.Printf("Dry-run: planned upgrade %s -> %s\n", input, upgradedPin)
return nil
}
fmt.Println(upgradedPin)
return nil
},
}
var cmdUpgradeAllSHA = &cobra.Command{
Use: "upgrade-all-sha [repo|url]",
Short: "⬆️ Upgrade all Scharf-formatted pinned SHAs in workflows",
Long: fmt.Sprintf("%s\n%s", asciiLogo, `⬆️ Upgrade all Scharf-formatted pinned SHAs in workflows for a local repo or remote URL`),
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
cooldownHours, _ := cmd.Flags().GetInt("cooldown-hours")
isDryRun, _ := cmd.Flags().GetBool("dry-run")
then := time.Now()
rp, err := sc.BuildRepoPath("upgrade-all-sha", args)
if err != nil {
fmt.Println(err.Error())
return
}
if err := sc.UpgradePinnedSHAs(*rp, cooldownHours, isDryRun); err != nil {
fmt.Println(err.Error())
return
}
now := time.Now()
di := now.Sub(then)
fmt.Printf("Total time: %.2f s\n", di.Seconds())
},
}
addSharedUpgradeFlags(cmdUpgrade)
addSharedUpgradeFlags(cmdUpgradeAllSHA)
cmdUpgrade.Flags().String("from-version", "", "Current version to upgrade from when input is owner/repo@<sha>")
cmdFind.PersistentFlags().String("root", ".", "Absolute path of root directory of GitHub repositories")
cmdFind.PersistentFlags().String("out", "json", "Output format of findings. Available options: json, csv")
cmdFind.PersistentFlags().Bool("head-only", false, "Limit scan only to HEAD (Activated branch)")
var cmdList = &cobra.Command{
Use: "list",
Short: "📋 Lists available references and their SHA versions of a GitHub action. Ex: scharf list actions/checkout",
Long: "📋 Lists available references and their SHA versions of an action in tabular form. Ex: actions/checkout. Prints <Version | Commit SHA> as a table rows",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
tw.SetHeader([]string{
"Version",
"Commit SHA",
})
tw.SetHeaderColor(
tablewriter.Colors{tablewriter.Bold, tablewriter.FgGreenColor},
tablewriter.Colors{tablewriter.Bold, tablewriter.FgGreenColor},
)
if args[0] != "" {
list, err := nw.GetRefList(args[0])
if err != nil {
logger.Error("No tags found. Please check the action again.", "action", args[0])
}
for i := range list {
tw.Append([]string{
list[i].Name,
list[i].Commit.Sha,
})
}
tw.Render()
} else {
logger.Error("Please give a GitHub action to look up SHA-commit. Ex: actions/checkout@v4")
}
},
}
var cmdVersion = &cobra.Command{
Use: "version",
Short: "Print Scharf version information",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintln(cmd.OutOrStdout(), cliVersion())
},
}
var rootCmd = &cobra.Command{
Use: "scharf",
Long: asciiLogo,
Run: func(cmd *cobra.Command, args []string) {
showVersion, _ := cmd.Flags().GetBool("version")
if showVersion {
fmt.Fprintln(cmd.OutOrStdout(), cliVersion())
return
}
_ = cmd.Help()
},
}
rootCmd.Flags().BoolP("version", "V", false, "Print Scharf version information")
rootCmd.AddCommand(cmdLookup, cmdFind, cmdList, cmdAudit, cmdAutoFix, cmdUpgrade, cmdUpgradeAllSHA, cmdVersion)
return rootCmd
}
func main() {
if err := newRootCmd().Execute(); err != nil {
os.Exit(1)
}
}