├── LICENSE
├── Makefile
├── README.md
├── go.mod
├── go.sum
├── main.go
├── screenshot
└── sc.png
└── src
└── configs
├── ignore_extensions.json
└── regex_patterns.json
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 UndeadSec
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SRC_DIR = src/
2 | DEST_DIR = /etc/dockerspy
3 | BIN_DIR = /usr/local/bin
4 |
5 | GREEN = \033[0;32m
6 | YELLOW = \033[0;33m
7 | BLUE = \033[0;34m
8 | NC = \033[0m
9 |
10 | all: build cleanup
11 |
12 | build: copy-deps
13 | @echo "$(BLUE)[#] Building the dockerspy binary...$(NC)"
14 | sudo go build -o dockerspy
15 | @echo "$(BLUE)[#] Copying the dockerspy binary to $(BIN_DIR)...$(NC)"
16 | sudo cp dockerspy $(BIN_DIR)
17 | sudo chmod +x $(BIN_DIR)/dockerspy
18 |
19 | copy-deps:
20 | @echo "$(YELLOW)[#] Copying configuration files...$(NC)"
21 | sudo mkdir -p $(DEST_DIR)
22 | sudo cp -R $(SRC_DIR)* $(DEST_DIR)
23 |
24 | cleanup:
25 | @echo "$(BLUE)[#] Cleaning up...$(NC)"
26 | sudo rm -f dockerspy
27 |
28 | .PHONY: all build copy-deps cleanup
29 |
30 | all: build cleanup
31 | @echo "$(GREEN)[###] Build complete. You can now run dockerspy from the terminal.$(NC)"
32 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DockerSpy
2 | DockerSpy searches for images on Docker Hub and extracts sensitive information such as authentication secrets, private keys, and more.
3 |
4 |
5 |
6 |
7 |
8 | ### What is Docker?
9 |
10 | Docker is an open-source platform that automates the deployment, scaling, and management of applications using containerization technology. Containers allow developers to package an application and its dependencies into a single, portable unit that can run consistently across various computing environments. Docker simplifies the development and deployment process by ensuring that applications run the same way regardless of where they are deployed.
11 |
12 | ### About Docker Hub
13 |
14 | Docker Hub is a cloud-based repository where developers can store, share, and distribute container images. It serves as the largest library of container images, providing access to both official images created by Docker and community-contributed images. Docker Hub enables developers to easily find, download, and deploy pre-built images, facilitating rapid application development and deployment.
15 |
16 | ### Why OSINT on Docker Hub?
17 |
18 | Open Source Intelligence (OSINT) on Docker Hub involves using publicly available information to gather insights and data from container images and repositories hosted on Docker Hub. This is particularly important for identifying exposed secrets for several reasons:
19 |
20 | 1. **Security Audits**: By analyzing Docker images, organizations can uncover exposed secrets such as API keys, authentication tokens, and private keys that might have been inadvertently included. This helps in mitigating potential security risks.
21 |
22 | 2. **Incident Prevention**: Proactively searching for exposed secrets in Docker images can prevent security breaches before they happen, protecting sensitive information and maintaining the integrity of applications.
23 |
24 | 3. **Compliance**: Ensuring that container images do not expose secrets is crucial for meeting regulatory and organizational security standards. OSINT helps verify that no sensitive information is unintentionally disclosed.
25 |
26 | 4. **Vulnerability Assessment**: Identifying exposed secrets as part of regular security assessments allows organizations to address these vulnerabilities promptly, reducing the risk of exploitation by malicious actors.
27 |
28 | 5. **Enhanced Security Posture**: Continuously monitoring Docker Hub for exposed secrets strengthens an organization's overall security posture, making it more resilient against potential threats.
29 |
30 | Utilizing OSINT on Docker Hub to find exposed secrets enables organizations to enhance their security measures, prevent data breaches, and ensure the confidentiality of sensitive information within their containerized applications.
31 |
32 | - [Thousands of images on Docker Hub leak auth secrets, private keys](https://www.bleepingcomputer.com/news/security/thousands-of-images-on-docker-hub-leak-auth-secrets-private-keys/)
33 | - [Docker Hub images found to expose secrets and private keys](https://www.threatdown.com/blog/docker-hub-images-found-to-expose-secrets-and-private-keys/)
34 |
35 | ## How DockerSpy Works
36 |
37 | DockerSpy obtains information from Docker Hub and uses regular expressions to inspect the content for sensitive information, such as secrets.
38 |
39 | ## Getting Started
40 |
41 | To use DockerSpy, follow these steps:
42 |
43 | 1. **Installation:** Clone the DockerSpy repository and install the required dependencies.
44 |
45 | ```bash
46 | git clone https://github.com/UndeadSec/DockerSpy.git && cd DockerSpy && make
47 | ```
48 |
49 | 2. **Usage:** Run DockerSpy from terminal.
50 |
51 | ```bash
52 | dockerspy
53 | ```
54 |
55 | ## Custom Configurations
56 |
57 | To customize DockerSpy configurations, edit the following files:
58 | - [Regular Expressions](src/configs/regex_patterns.json)
59 | - [Ignored File Extensions](src/configs/ignore_extensions.json)
60 |
61 | ## Disclaimer
62 |
63 | DockerSpy is intended for educational and research purposes only. Users are responsible for ensuring that their use of this tool complies with applicable laws and regulations.
64 |
65 | ## Contribution
66 |
67 | Contributions to DockerSpy are welcome! Feel free to submit issues, feature requests, or pull requests to help improve this tool.
68 |
69 | ## About the Author
70 |
71 | DockerSpy is developed and maintained by *Alisson Moretto* (UndeadSec)
72 |
73 | I'm a passionate cyber threat intelligence pro who loves sharing insights and crafting cybersecurity tools.
74 |
75 | Consider following me:
76 |
77 | [](https://twitter.com/UndeadSec)
78 | [](https://linkedin.com/in/alissonmoretto)
79 | [](https://github.com/UndeadSec)
80 |
81 | ## TODO
82 |
83 | ### Regular Expressions Enhancement
84 |
85 | - [ ] Review and improve existing regular expressions.
86 | - [ ] Ensure that regular expressions adhere to best practices.
87 | - [ ] Check for any potential optimizations in the regex patterns.
88 | - [ ] Test regular expressions with various input scenarios for accuracy.
89 | - [ ] Document any complex or non-trivial regex patterns for better understanding.
90 |
91 | ## License
92 |
93 | DockerSpy is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
94 |
95 | ### Thanks
96 |
97 | Special thanks to [@akaclandestine](https://x.com/akaclandestine)
98 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module dockerspy
2 |
3 | go 1.22
4 |
5 | require github.com/fatih/color v1.17.0
6 |
7 | require (
8 | github.com/mattn/go-colorable v0.1.13 // indirect
9 | github.com/mattn/go-isatty v0.0.20 // indirect
10 | golang.org/x/sys v0.22.0 // indirect
11 | )
12 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4=
2 | github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI=
3 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
4 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
5 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
6 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
7 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
8 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
9 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
10 | golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
11 | golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
12 | golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
13 | golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
14 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "archive/tar"
5 | "bufio"
6 | "compress/gzip"
7 | "encoding/json"
8 | "fmt"
9 | "github.com/fatih/color"
10 | "io"
11 | "net/http"
12 | "net/url"
13 | "os"
14 | "path/filepath"
15 | "regexp"
16 | "strconv"
17 | "strings"
18 | )
19 |
20 | type IgnoreExtensions struct {
21 | Extensions []string `json:"extensions"`
22 | }
23 |
24 | type SearchResult struct {
25 | NumResults int `json:"count"`
26 | Next string `json:"next"`
27 | Results []struct {
28 | Name string `json:"repo_name"`
29 | Description string `json:"short_description"`
30 | PullCount int `json:"pull_count"`
31 | StarCount int `json:"star_count"`
32 | IsOfficial bool `json:"is_official"`
33 | } `json:"results"`
34 | }
35 |
36 | type TagsResult struct {
37 | Count int `json:"count"`
38 | Next string `json:"next"`
39 | Previous string `json:"previous"`
40 | Results []struct {
41 | Name string `json:"name"`
42 | } `json:"results"`
43 | }
44 |
45 | const (
46 | dockerHubAPI = "https://registry-1.docker.io/v2/"
47 | )
48 |
49 | type TokenResponse struct {
50 | Token string `json:"token"`
51 | }
52 |
53 | type Manifest struct {
54 | Config Descriptor `json:"config"`
55 | Layers []Descriptor `json:"layers"`
56 | MediaType string `json:"mediaType"`
57 | }
58 |
59 | type Descriptor struct {
60 | MediaType string `json:"mediaType"`
61 | Size int64 `json:"size"`
62 | Digest string `json:"digest"`
63 | }
64 |
65 | func getDockerHubToken(repo string) (string, error) {
66 | authURL := fmt.Sprintf("https://auth.docker.io/token?service=registry.docker.io&scope=repository:%s:pull", repo)
67 | resp, err := http.Get(authURL)
68 | if err != nil {
69 | return "", err
70 | }
71 | defer resp.Body.Close()
72 |
73 | if resp.StatusCode != http.StatusOK {
74 | return "", fmt.Errorf("failed to authenticate: %s", resp.Status)
75 | }
76 |
77 | var tokenResponse TokenResponse
78 | if err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil {
79 | return "", err
80 | }
81 |
82 | return tokenResponse.Token, nil
83 | }
84 |
85 | func getManifest(repo, tag, token string) (*Manifest, error) {
86 | client := &http.Client{}
87 | url := fmt.Sprintf("%s%s/manifests/%s", dockerHubAPI, repo, tag)
88 | req, err := http.NewRequest("GET", url, nil)
89 | if err != nil {
90 | return nil, err
91 | }
92 | req.Header.Set("Authorization", "Bearer "+token)
93 | req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json")
94 |
95 | resp, err := client.Do(req)
96 | if err != nil {
97 | return nil, err
98 | }
99 | defer resp.Body.Close()
100 |
101 | if resp.StatusCode != http.StatusOK {
102 | return nil, fmt.Errorf("failed to get manifest: %s", resp.Status)
103 | }
104 |
105 | var manifest Manifest
106 | if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil {
107 | return nil, err
108 | }
109 |
110 | return &manifest, nil
111 | }
112 |
113 | func downloadLayer(repo, token, digest, outputPath string, size int64) error {
114 | client := &http.Client{}
115 | url := fmt.Sprintf("%s%s/blobs/%s", dockerHubAPI, repo, digest)
116 | req, err := http.NewRequest("GET", url, nil)
117 | if err != nil {
118 | return err
119 | }
120 | req.Header.Set("Authorization", "Bearer "+token)
121 |
122 | resp, err := client.Do(req)
123 | if err != nil {
124 | return err
125 | }
126 | defer resp.Body.Close()
127 |
128 | if resp.StatusCode != http.StatusOK {
129 | return fmt.Errorf("failed to download layer: %s", resp.Status)
130 | }
131 |
132 | file, err := os.Create(outputPath)
133 | if err != nil {
134 | return err
135 | }
136 | defer file.Close()
137 |
138 | progressWriter := &ProgressWriter{Writer: file, Total: size}
139 | _, err = io.Copy(progressWriter, resp.Body)
140 | return err
141 | }
142 |
143 | type ProgressWriter struct {
144 | Writer io.Writer
145 | Total int64
146 | Downloaded int64
147 | }
148 |
149 | func (pw *ProgressWriter) Write(p []byte) (int, error) {
150 | n, err := pw.Writer.Write(p)
151 | pw.Downloaded += int64(n)
152 | pw.printProgress()
153 | return n, err
154 | }
155 |
156 | func (pw *ProgressWriter) printProgress() {
157 | percent := float64(pw.Downloaded) / float64(pw.Total) * 100
158 | fmt.Printf("\rDownloading... %.2f%% complete", percent)
159 | }
160 |
161 | func loadRegexPatterns(filename string) (map[string]*regexp.Regexp, error) {
162 | file, err := os.Open(filename)
163 | if err != nil {
164 | return nil, err
165 | }
166 | defer file.Close()
167 |
168 | var patterns map[string]string
169 | decoder := json.NewDecoder(file)
170 | if err := decoder.Decode(&patterns); err != nil {
171 | return nil, err
172 | }
173 |
174 | regexPatterns := make(map[string]*regexp.Regexp)
175 | for name, pattern := range patterns {
176 | re, err := regexp.Compile(pattern)
177 | if err != nil {
178 | return nil, fmt.Errorf("failed to compile regex %s: %v", name, err)
179 | }
180 | regexPatterns[name] = re
181 | }
182 |
183 | return regexPatterns, nil
184 | }
185 |
186 | func checkPatterns(content string, patterns map[string]*regexp.Regexp) map[string][]string {
187 | matches := make(map[string][]string)
188 | for name, re := range patterns {
189 | foundMatches := re.FindAllString(content, -1)
190 | if foundMatches != nil {
191 | matches[name] = foundMatches
192 | }
193 | }
194 | return matches
195 | }
196 |
197 | func extractTarGz(tarGzPath, outputDir string) error {
198 | file, err := os.Open(tarGzPath)
199 | if err != nil {
200 | return err
201 | }
202 | defer file.Close()
203 |
204 | gzr, err := gzip.NewReader(file)
205 | if err != nil {
206 | return err
207 | }
208 | defer gzr.Close()
209 |
210 | tarReader := tar.NewReader(gzr)
211 | for {
212 | header, err := tarReader.Next()
213 | if err == io.EOF {
214 | break
215 | }
216 | if err != nil {
217 | return err
218 | }
219 |
220 | target := filepath.Join(outputDir, header.Name)
221 | switch header.Typeflag {
222 | case tar.TypeDir:
223 | if err := os.MkdirAll(target, os.ModePerm); err != nil {
224 | return err
225 | }
226 | case tar.TypeReg:
227 | outFile, err := os.Create(target)
228 | if err != nil {
229 | return err
230 | }
231 | if _, err := io.Copy(outFile, tarReader); err != nil {
232 | outFile.Close()
233 | return err
234 | }
235 | outFile.Close()
236 | default:
237 | //fmt.Printf("Unable to untar type: %c in file %s", header.Typeflag, header.Name)
238 | }
239 | }
240 | return nil
241 | }
242 |
243 | func loadIgnoreExtensions(filename string) ([]string, error) {
244 | file, err := os.Open(filename)
245 | if err != nil {
246 | return nil, err
247 | }
248 | defer file.Close()
249 |
250 | var ignoreExtensions IgnoreExtensions
251 | decoder := json.NewDecoder(file)
252 | if err := decoder.Decode(&ignoreExtensions); err != nil {
253 | return nil, err
254 | }
255 |
256 | return ignoreExtensions.Extensions, nil
257 | }
258 |
259 | func shouldSkipFile(filename string, ignoreExtensions []string) bool {
260 | for _, ext := range ignoreExtensions {
261 | if strings.HasSuffix(strings.ToLower(filename), ext) {
262 | return true
263 | }
264 | }
265 | return false
266 | }
267 |
268 | func removeDir(dir string) error {
269 | if _, err := os.Stat(dir); os.IsNotExist(err) {
270 | return nil
271 | }
272 | return os.RemoveAll(dir)
273 | }
274 |
275 | func printBanner() {
276 | banner := `
277 | ╭━━━━━━━━╮┏━╮╭━┓
278 | ┃┈┈┈┈┈┈┈┈┃╰╮╰╯╭╯ v1.1
279 | ┃╰╯┈┈┈┈┈┈╰╮╰╮╭╯┈ DOCKERSPY by Alisson Moretto (UndeadSec)
280 | ┣━━╯┈┈┈┈┈┈╰━╯┃┈┈ AUTOMATED OSINT ON DOCKER HUB
281 | ╰━━━━━━━━━━━━╯┈┈`
282 | fmt.Println(color.New(color.FgGreen).Sprint(banner))
283 | }
284 |
285 | func fetchPaginatedResults(url string) ([]struct {
286 | Name string `json:"repo_name"`
287 | Description string `json:"short_description"`
288 | PullCount int `json:"pull_count"`
289 | StarCount int `json:"star_count"`
290 | IsOfficial bool `json:"is_official"`
291 | }, error) {
292 | var allResults []struct {
293 | Name string `json:"repo_name"`
294 | Description string `json:"short_description"`
295 | PullCount int `json:"pull_count"`
296 | StarCount int `json:"star_count"`
297 | IsOfficial bool `json:"is_official"`
298 | }
299 |
300 | count := 0
301 | for {
302 | if count >= 100 {
303 | break
304 | }
305 |
306 | resp, err := http.Get(url)
307 | if err != nil {
308 | return nil, err
309 | }
310 | defer resp.Body.Close()
311 |
312 | if resp.StatusCode != http.StatusOK {
313 | return nil, fmt.Errorf("API response error: %s", resp.Status)
314 | }
315 |
316 | var searchResult SearchResult
317 | if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil {
318 | return nil, err
319 | }
320 |
321 | allResults = append(allResults, searchResult.Results...)
322 | count += len(searchResult.Results)
323 |
324 | if searchResult.Next == "" {
325 | break
326 | }
327 |
328 | url = searchResult.Next
329 | }
330 |
331 | if len(allResults) > 100 {
332 | allResults = allResults[:100]
333 | }
334 |
335 | return allResults, nil
336 | }
337 |
338 | func main() {
339 | printBanner()
340 |
341 | err := removeDir("docker_image")
342 | if err != nil {
343 | fmt.Println("\nError removing docker_image directory:", err)
344 | return
345 | }
346 |
347 | regexPatterns, err := loadRegexPatterns("/etc/dockerspy/configs/regex_patterns.json")
348 | if err != nil {
349 | fmt.Println("\nError loading regex patterns:", err)
350 | return
351 | }
352 |
353 | ignoreExtensions, err := loadIgnoreExtensions("/etc/dockerspy/configs/ignore_extensions.json")
354 | if err != nil {
355 | fmt.Println("\nError loading ignore extensions:", err)
356 | return
357 | }
358 |
359 | scanner := bufio.NewScanner(os.Stdin)
360 | info := color.New(color.FgCyan).SprintFunc()
361 | warning := color.New(color.FgYellow).SprintFunc()
362 | errorColor := color.New(color.FgRed).SprintFunc()
363 | success := color.New(color.FgGreen).SprintFunc()
364 | highlight := color.New(color.FgHiMagenta, color.Bold).SprintFunc()
365 |
366 | for {
367 | fmt.Print(info("\nEnter search term (or 'exit' to quit): "))
368 | scanner.Scan()
369 | searchTerm := scanner.Text()
370 |
371 | if strings.ToLower(searchTerm) == "exit" {
372 | break
373 | }
374 |
375 | dockerHubURL := "https://hub.docker.com/v2/search/repositories"
376 | params := url.Values{}
377 | params.Add("query", searchTerm)
378 |
379 | searchURL := fmt.Sprintf("%s?%s", dockerHubURL, params.Encode())
380 | results, err := fetchPaginatedResults(searchURL)
381 | if err != nil {
382 | fmt.Println(errorColor("\nError fetching search results:"), err)
383 | continue
384 | }
385 |
386 | fmt.Printf(info("\nFound %d results for '%s':"), len(results), searchTerm)
387 | for i, result := range results {
388 | fmt.Printf("\n%s - Name: %s\nDescription: %s\nStars: %d\nOfficial: %t", highlight(i+1), result.Name, result.Description, result.StarCount, result.IsOfficial)
389 | }
390 |
391 | fmt.Print(info("\nChoose a number or enter the full name to view repository tags (or 'cancel' to search again): "))
392 | scanner.Scan()
393 | choice := scanner.Text()
394 |
395 | if strings.ToLower(choice) == "cancel" {
396 | continue
397 | }
398 |
399 | var selectedRepo string
400 | choiceNum, err := strconv.Atoi(choice)
401 | if err == nil && choiceNum >= 1 && choiceNum <= len(results) {
402 | selectedRepo = results[choiceNum-1].Name
403 | } else {
404 | selectedRepo = choice
405 | }
406 |
407 | tagsURL := fmt.Sprintf("https://hub.docker.com/v2/repositories/%s/tags", selectedRepo)
408 | resp, err := http.Get(tagsURL)
409 | if err != nil {
410 | fmt.Println(errorColor("\nError fetching tags:"), err)
411 | continue
412 | }
413 | defer resp.Body.Close()
414 |
415 | var tagsResult TagsResult
416 | if err := json.NewDecoder(resp.Body).Decode(&tagsResult); err != nil {
417 | fmt.Println(errorColor("\nError decoding JSON response:"), err)
418 | continue
419 | }
420 |
421 | fmt.Printf(info("Available tags for repository '%s':"), selectedRepo)
422 | for i, tag := range tagsResult.Results {
423 | fmt.Printf("\n%s - %s", highlight(i+1), tag.Name)
424 | }
425 |
426 | fmt.Print(info("\nChoose a number to download the tag (or 'cancel' to search again): "))
427 | scanner.Scan()
428 | tagChoice := scanner.Text()
429 |
430 | if strings.ToLower(tagChoice) == "cancel" {
431 | continue
432 | }
433 |
434 | tagChoiceNum, err := strconv.Atoi(tagChoice)
435 | if err != nil || tagChoiceNum < 1 || tagChoiceNum > len(tagsResult.Results) {
436 | fmt.Println(warning("\nInvalid choice. Please try again."))
437 | continue
438 | }
439 |
440 | tag := tagsResult.Results[tagChoiceNum-1].Name
441 |
442 | repo := selectedRepo
443 | outputDir := "./docker_image"
444 |
445 | token, err := getDockerHubToken(repo)
446 | if err != nil {
447 | fmt.Println("\nError getting token:", err)
448 | return
449 | }
450 |
451 | manifest, err := getManifest(repo, tag, token)
452 | if err != nil {
453 | fmt.Println("\nError getting manifest:", err)
454 | return
455 | }
456 |
457 | os.MkdirAll(outputDir, os.ModePerm)
458 |
459 | var envContent string
460 | matchesResult := make(map[string]map[string][]string)
461 |
462 | for _, layer := range manifest.Layers {
463 | digestParts := strings.Split(layer.Digest, ":")
464 | if len(digestParts) != 2 {
465 | fmt.Println("\nInvalid digest format:", layer.Digest)
466 | continue
467 | }
468 | outputPath := filepath.Join(outputDir, digestParts[1]+".tar.gz")
469 | fmt.Println("\nDownloading layer:", layer.Digest)
470 | if err := downloadLayer(repo, token, layer.Digest, outputPath, layer.Size); err != nil {
471 | fmt.Println("\nError downloading layer:", err)
472 | return
473 | }
474 |
475 | extractedDir := filepath.Join(outputDir, digestParts[1])
476 | fmt.Println("\nExtracting layer:", outputPath)
477 | if err := extractTarGz(outputPath, extractedDir); err != nil {
478 | fmt.Println("\nError extracting layer:", err)
479 | continue
480 | }
481 |
482 | filepath.Walk(extractedDir, func(path string, info os.FileInfo, err error) error {
483 | if err != nil {
484 | return err
485 | }
486 | if !info.IsDir() && !shouldSkipFile(path, ignoreExtensions) {
487 | content, err := os.ReadFile(path)
488 | if err != nil {
489 | fmt.Println("\nError reading file:", err)
490 | return nil
491 | }
492 | if filepath.Base(path) == ".env" {
493 | fmt.Println(success("\nFound .env file:"))
494 | envContent = string(content)
495 | fmt.Println(envContent)
496 | }
497 | matches := checkPatterns(string(content), regexPatterns)
498 | if len(matches) > 0 {
499 | fmt.Println(success("\nMatches found in file:"), path)
500 | matchesResult[path] = matches
501 | for pattern, matchedStrings := range matches {
502 | fmt.Printf(" Pattern: %s\n", pattern)
503 | for _, match := range matchedStrings {
504 | fmt.Printf(" %s\n", match)
505 | }
506 | }
507 | }
508 | }
509 | return nil
510 | })
511 | }
512 |
513 | fmt.Println(success("\nImage downloaded and extracted successfully\n"))
514 |
515 | resultData := map[string]interface{}{
516 | "selectedRepo": selectedRepo,
517 | "selectedTag": tag,
518 | "envContent": envContent,
519 | "matches": matchesResult,
520 | }
521 |
522 | jsonFile, err := os.Create("results.json")
523 | if err != nil {
524 | fmt.Println(errorColor("\nError creating JSON file:"), err)
525 | return
526 | }
527 | defer jsonFile.Close()
528 |
529 | encoder := json.NewEncoder(jsonFile)
530 | if err := encoder.Encode(resultData); err != nil {
531 | fmt.Println(errorColor("\nError encoding JSON:"), err)
532 | return
533 | }
534 |
535 | fmt.Println(success("Results saved to results.json"))
536 | }
537 | }
538 |
--------------------------------------------------------------------------------
/screenshot/sc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UndeadSec/DockerSpy/030b4224f4280596ff4ebafa774ecf3277a5c4be/screenshot/sc.png
--------------------------------------------------------------------------------
/src/configs/ignore_extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "extensions": [".md",".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".tif", ".mp4", ".mp3", ".avi", ".mkv", ".mov", ".exe", ".dll", ".so", ".bin", ".dmg", ".iso", ".jar", ".bat", ".sh", ".msi"]
3 | }
4 |
--------------------------------------------------------------------------------
/src/configs/regex_patterns.json:
--------------------------------------------------------------------------------
1 | {
2 | "amazon_mws_auth_token": "amzn\\\\.mws\\\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
3 | "amazon_aws_url": "s3\\.amazonaws.com[/]+|[a-zA-Z0-9_-]*\\.s3\\.amazonaws.com",
4 | "authorization_bearer": "bearer [a-zA-Z0-9_\\-\\.=:_\\+/]{5,100}",
5 | "github_access_token": "[a-zA-Z0-9_-]*:[a-zA-Z0-9_\\-]+@github\\.com*",
6 | "rsa_private_key": "-----BEGIN RSA PRIVATE KEY-----",
7 | "ssh_dsa_private_key": "-----BEGIN DSA PRIVATE KEY-----",
8 | "ssh_dc_private_key": "-----BEGIN EC PRIVATE KEY-----",
9 | "pgp_private_block": "-----BEGIN PGP PRIVATE KEY BLOCK-----",
10 | "slack_token": "\\\"api_token\\\":\\\"(xox[a-zA-Z]-[a-zA-Z0-9-]+)\\\"",
11 | "SSH_privKey": "([-]+BEGIN [^\\s]+ PRIVATE KEY[-]+[\\s]*[^-]*[-]+END [^\\s]+ PRIVATE KEY[-]+)"
12 | }
--------------------------------------------------------------------------------