-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
284 lines (232 loc) · 7.2 KB
/
main.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
package main
import (
"context"
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/google/go-github/v55/github"
"golang.org/x/oauth2"
)
func main() {
// Check the number of command-line arguments
if len(os.Args) < 3 {
fmt.Println("Usage: program_name username branch [recursionOption] [iteration]")
os.Exit(1)
}
// Username or Org
username := os.Args[1]
// Branch
ref := os.Args[2]
if ref == "" {
fmt.Println("Please specify a branch")
os.Exit(1)
}
// Github Token (optional)
token := os.Getenv("GITHUB_TOKEN")
// Recursion Option (optional)
var recursionOption string
if len(os.Args) > 3 {
recursionOption = os.Args[3]
if recursionOption != "true" && recursionOption != "false" {
fmt.Println("Enter true or false as values for recursion")
os.Exit(1)
}
} else {
recursionOption = "false"
}
// Iteration, for continuation after hitting rate limit (optional)
var iterationStr string
if len(os.Args) > 4 {
iterationStr = os.Args[4]
} else {
iterationStr = "0"
}
// Convert Iteration to Integer
iteration, err := strconv.Atoi(iterationStr)
if err != nil {
fmt.Println("Invalid iteration value:", err)
os.Exit(1)
}
// Create Github Client
client := createGitHubClient(token)
// Get List of Repos
repos, err := getRepositories(client, username)
if err != nil {
log.Println(err)
}
// Loop through repos to search for Dockerfiles
for range repos {
for {
// Check to see if a repo contains any Dockerfiles
hasDockerfile, err := hasDockerfiles(client, username, repos[iteration].GetName())
if err != nil {
handleRateLimit(err, repos[iteration].GetName(), iteration)
}
// Parse any found Dockerfiles
if hasDockerfile {
getDockerfileContent(client, repos[iteration].GetName(), username, recursionOption, ref)
}
iteration++
if iteration >= len(repos) {
log.Println("Complete")
os.Exit(0)
}
}
}
}
// Function to create Github Client
func createGitHubClient(token string) *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
return github.NewClient(tc)
}
// Function to get repos
func getRepositories(client *github.Client, username string) ([]*github.Repository, error) {
ctx := context.Background()
opt := &github.RepositoryListOptions{
Type: "all",
}
var allRepos []*github.Repository
page := 1
for {
repos, _, err := client.Repositories.List(ctx, username, opt)
if err != nil {
return nil, err
}
allRepos = append(allRepos, repos...)
if len(repos) == 0 {
break
}
page++
opt.Page = page
}
return allRepos, nil
}
// Function to check if repo has Dockefiles
func hasDockerfiles(client *github.Client, username, repo string) (bool, error) {
ctx := context.Background()
// Retrieve the repository's languages
languages, _, err := client.Repositories.ListLanguages(ctx, username, repo)
if err != nil {
return false, err
}
// Check if "Dockerfile" language is present
_, ok := languages["Dockerfile"]
return ok, nil
}
// Function to parse Dockerfiles
func getDockerfileContent(client *github.Client, repoFullName string, username string, recursionOption string, ref string) {
ctx := context.Background()
path := ""
// Get Dockerfiles with modified names
DockerfileNames := getDockerfileName(client, repoFullName, username, path, recursionOption, ref)
// Parse Dockerfiles
if len(DockerfileNames) != 0 {
for _, DockerfileName := range DockerfileNames {
// Retrieve the repository file content
fileContent, _, _, err := client.Repositories.GetContents(ctx, username, repoFullName, DockerfileName, nil)
if err != nil {
log.Println(err)
continue // Skip this file and move to the next one
}
// Check if content is nil
if fileContent == nil {
log.Printf("Content is nil for file %s in repo %s\n", DockerfileName, repoFullName)
continue // Skip this file and move to the next one
}
decodedContent, err := fileContent.GetContent()
if err != nil {
log.Println(err)
continue // Skip this file and move to the next one
}
// Find Base image name
container := findFROMLine(decodedContent)
for containerName := range container {
fmt.Print(repoFullName + ": ")
fmt.Println(container[containerName])
}
}
}
}
// Function to get modified Dockerfile names
func getDockerfileName(client *github.Client, repoFullName string, username string, path string, recursionOption string, ref string) []string {
ctx := context.Background()
// Define the regular expression pattern to match Dockerfile variations
pattern := `^(Dockerfile|.*\.Dockerfile|Dockerfile\..*)$`
// Compile the regex pattern
regex, err := regexp.Compile(pattern)
if err != nil {
// Handle error
return nil
}
// Recursively fetch the contents of the specified directory
_, rootContents, _, err := client.Repositories.GetContents(ctx, username, repoFullName, path, &github.RepositoryContentGetOptions{Ref: ref})
if err != nil {
// Handle error
return nil
}
// Initialize a slice to hold matching Dockerfile names
var DockerfileNames []string
// Iterate through the directory contents
for _, content := range rootContents {
if *content.Type == "file" {
fileName := string(*content.Name)
if regex.MatchString(fileName) {
// Construct the full path for the matching Dockerfile
filePath := fileName
if path != "" {
filePath = path + "/" + fileName
}
DockerfileNames = append(DockerfileNames, filePath)
}
} else if *content.Type == "dir" && recursionOption == "true" {
// Recursively call the function for subdirectories
subDirPath := path + "/" + string(*content.Name)
subDirDockerfiles := getDockerfileName(client, repoFullName, username, subDirPath, recursionOption, ref)
DockerfileNames = append(DockerfileNames, subDirDockerfiles...)
}
}
return DockerfileNames
}
// Function to extract container name
func findFROMLine(content string) []string {
lines := strings.Split(content, "\n")
var FROMline []string
// Regular expression to match "FROM" lines and capture the container name. Tweak this if necessary
regex := regexp.MustCompile(`\b([a-zA-Z0-9\-.:/]+)(:latest)?\b`)
regex2 := regexp.MustCompile(`\b(AS\b|platform\b|TARGETARCH\b)`)
for _, line := range lines {
if strings.HasPrefix(strings.TrimSpace(line), "FROM ") {
line = strings.TrimPrefix(line, "FROM ")
// Use regex2 to check if the line matches unwanted terms
if !regex2.MatchString(line) {
// Find matches in the line using the regular expression
matches := regex.FindStringSubmatch(line)
if len(matches) > 1 {
// Extract the container name (group 1 in the regex match)
containerName := matches[1]
FROMline = append(FROMline, containerName)
}
}
}
}
return FROMline
}
// Function to handle hitting rate limit
func handleRateLimit(err error, repoFullName string, iteration int) {
log.Println(err)
if e, ok := err.(*github.RateLimitError); ok {
resetTime := e.Rate.Reset.Time
sleepTime := time.Until(resetTime)
log.Printf("Rate limit exceeded at %s. Try again in %s...\n", resetTime, sleepTime)
log.Printf("When rate limit resets, restart from iteration %d. Repo to be scanned: %s\n", iteration, repoFullName)
os.Exit(0)
}
}