Skip to content

Find, verify, and analyze leaked credentials

dockerhub analyzer (#3861)

Kashif Khanb10342e5da77
diff --git a/pkg/analyzer/analyzers/analyzers.go b/pkg/analyzer/analyzers/analyzers.go
index c58c25130..168f9bd83 100644
--- a/pkg/analyzer/analyzers/analyzers.go
+++ b/pkg/analyzer/analyzers/analyzers.go
@@ -63,6 +63,7 @@ const (
AnalyzerTypeAirbrake
AnalyzerTypeAsana
AnalyzerTypeBitbucket
+ AnalyzerTypeDockerHub
AnalyzerTypeGitHub
AnalyzerTypeGitLab
AnalyzerTypeHuggingFace
@@ -90,6 +91,7 @@ var analyzerTypeStrings = map[AnalyzerType]string{
AnalyzerTypeAirbrake: "Airbrake",
AnalyzerTypeAsana: "Asana",
AnalyzerTypeBitbucket: "Bitbucket",
+ AnalyzerTypeDockerHub: "DockerHub",
AnalyzerTypeGitHub: "GitHub",
AnalyzerTypeGitLab: "GitLab",
AnalyzerTypeHuggingFace: "HuggingFace",
diff --git a/pkg/analyzer/analyzers/dockerhub/dockerhub.go b/pkg/analyzer/analyzers/dockerhub/dockerhub.go
new file mode 100644
index 000000000..a938332f6
--- /dev/null
+++ b/pkg/analyzer/analyzers/dockerhub/dockerhub.go
@@ -0,0 +1,192 @@
+//go:generate generate_permissions permissions.yaml permissions.go elevenlabs
+package dockerhub
+
+import (
+ "errors"
+ "os"
+
+ "github.com/fatih/color"
+ "github.com/jedib0t/go-pretty/table"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/config"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+var _ analyzers.Analyzer = (*Analyzer)(nil)
+
+type Analyzer struct {
+ Cfg *config.Config
+}
+
+// SecretInfo hold the information about the token generated from username and pat
+type SecretInfo struct {
+ User User
+ Valid bool
+ Reference string
+ Permissions []string
+ Repositories []Repository
+ ExpiresIn string
+ Misc map[string]string
+}
+
+// User hold the information about user to whom the personal access token belongs
+type User struct {
+ ID string
+ Username string
+ Email string
+}
+
+// Repository hold information about each repository the user can access
+type Repository struct {
+ ID string
+ Name string
+ Type string
+ IsPrivate bool
+ StarCount int
+ PullCount int
+}
+
+func (a Analyzer) Type() analyzers.AnalyzerType {
+ return analyzers.AnalyzerTypeDockerHub
+}
+
+func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
+ username, exist := credInfo["username"]
+ if !exist {
+ return nil, errors.New("username not found in the credentials info")
+ }
+
+ pat, exist := credInfo["pat"]
+ if !exist {
+ return nil, errors.New("personal access token(PAT) not found in the credentials info")
+ }
+
+ info, err := AnalyzePermissions(a.Cfg, username, pat)
+ if err != nil {
+ return nil, err
+ }
+
+ return secretInfoToAnalyzerResult(info), nil
+}
+
+// AnalyzePermissions will collect all the scopes assigned to token along with resource it can access
+func AnalyzePermissions(cfg *config.Config, username, pat string) (*SecretInfo, error) {
+ // create the http client
+ client := analyzers.NewAnalyzeClientUnrestricted(cfg) // `/user/login` is a non-safe request
+
+ var secretInfo = &SecretInfo{}
+
+ // try to login and get jwt token
+ token, err := login(client, username, pat)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := decodeTokenToSecretInfo(token, secretInfo); err != nil {
+ return nil, err
+ }
+
+ // fetch repositories using the jwt token and translate them to secret info
+ if err := fetchRepositories(client, username, token, secretInfo); err != nil {
+ return nil, err
+ }
+
+ // return secret info
+ return secretInfo, nil
+}
+
+func AnalyzeAndPrintPermissions(cfg *config.Config, username, pat string) {
+ info, err := AnalyzePermissions(cfg, username, pat)
+ if err != nil {
+ // just print the error in cli and continue as a partial success
+ color.Red("[x] Error : %s", err.Error())
+ }
+
+ if info == nil {
+ color.Red("[x] Error : %s", "No information found")
+ return
+ }
+
+ if info.Valid {
+ color.Green("[!] Valid DockerHub Credentials\n\n")
+ // print user information
+ printUser(info.User)
+ // print permissions
+ printPermissions(info.Permissions)
+ // print repositories
+ printRepositories(info.Repositories)
+
+ color.Yellow("\n[i] Expires: %s", info.ExpiresIn)
+ }
+}
+
+// secretInfoToAnalyzerResult translate secret info to Analyzer Result
+func secretInfoToAnalyzerResult(info *SecretInfo) *analyzers.AnalyzerResult {
+ if info == nil {
+ return nil
+ }
+
+ result := analyzers.AnalyzerResult{
+ AnalyzerType: analyzers.AnalyzerTypeDockerHub,
+ Metadata: map[string]any{"Valid_Key": info.Valid},
+ Bindings: make([]analyzers.Binding, len(info.Repositories)),
+ }
+
+ // extract information to create bindings and append to result bindings
+ for _, repo := range info.Repositories {
+ binding := analyzers.Binding{
+ Resource: analyzers.Resource{
+ Name: repo.Name,
+ FullyQualifiedName: repo.ID,
+ Type: repo.Type,
+ Metadata: map[string]any{
+ "is_private": repo.IsPrivate,
+ "pull_count": repo.PullCount,
+ "star_count": repo.StarCount,
+ },
+ },
+ Permission: analyzers.Permission{
+ // as all permissions are against repo, we assign the highest available permission
+ Value: assignHighestPermission(info.Permissions),
+ },
+ }
+
+ result.Bindings = append(result.Bindings, binding)
+ }
+
+ return &result
+}
+
+// cli print functions
+func printUser(user User) {
+ color.Green("\n[i] User:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"ID", "Username", "Email"})
+ t.AppendRow(table.Row{color.GreenString(user.ID), color.GreenString(user.Username), color.GreenString(user.Email)})
+ t.Render()
+}
+
+func printPermissions(permissions []string) {
+ color.Yellow("[i] Permissions:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Permission"})
+ for _, permission := range permissions {
+ t.AppendRow(table.Row{color.GreenString(permission)})
+ }
+ t.Render()
+}
+
+func printRepositories(repos []Repository) {
+ color.Green("\n[i] Repositories:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Type", "ID(username/repo/repo_type/repo_name)", "Name", "Is Private", "Pull Count", "Star Count"})
+ for _, repo := range repos {
+ t.AppendRow(table.Row{color.GreenString(repo.Type), color.GreenString(repo.ID), color.GreenString(repo.Name),
+ color.GreenString("%t", repo.IsPrivate), color.GreenString("%d", repo.PullCount), color.GreenString("%d", repo.StarCount)})
+ }
+ t.Render()
+}
diff --git a/pkg/analyzer/analyzers/dockerhub/dockerhub_test.go b/pkg/analyzer/analyzers/dockerhub/dockerhub_test.go
new file mode 100644
index 000000000..6cc37749c
--- /dev/null
+++ b/pkg/analyzer/analyzers/dockerhub/dockerhub_test.go
@@ -0,0 +1,88 @@
+package dockerhub
+
+import (
+ _ "embed"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/config"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/common"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+//go:embed result_output.json
+var expectedOutput []byte
+
+func TestAnalyzer_Analyze(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
+ defer cancel()
+ testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors4")
+ if err != nil {
+ t.Fatalf("could not get test secrets from GCP: %s", err)
+ }
+
+ username := testSecrets.MustGetField("DOCKERHUB_USERNAME")
+ pat := testSecrets.MustGetField("DOCKERHUB_PAT")
+
+ tests := []struct {
+ name string
+ username string
+ pat string
+ want []byte // JSON string
+ wantErr bool
+ }{
+ {
+ name: "valid dockerhub credentials",
+ username: username,
+ pat: pat,
+ want: expectedOutput,
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ a := Analyzer{Cfg: &config.Config{}}
+ got, err := a.Analyze(ctx, map[string]string{"username": tt.username, "pat": tt.pat})
+ if (err != nil) != tt.wantErr {
+ t.Errorf("Analyzer.Analyze() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+
+ // Marshal the actual result to JSON
+ gotJSON, err := json.Marshal(got)
+ if err != nil {
+ t.Fatalf("could not marshal got to JSON: %s", err)
+ }
+
+ // Parse the expected JSON string
+ var wantObj analyzers.AnalyzerResult
+ if err := json.Unmarshal([]byte(tt.want), &wantObj); err != nil {
+ t.Fatalf("could not unmarshal want JSON string: %s", err)
+ }
+
+ // Marshal the expected result to JSON (to normalize)
+ wantJSON, err := json.Marshal(wantObj)
+ if err != nil {
+ t.Fatalf("could not marshal want to JSON: %s", err)
+ }
+
+ // Compare the JSON strings
+ if string(gotJSON) != string(wantJSON) {
+ // Pretty-print both JSON strings for easier comparison
+ var gotIndented, wantIndented []byte
+ gotIndented, err = json.MarshalIndent(got, "", " ")
+ if err != nil {
+ t.Fatalf("could not marshal got to indented JSON: %s", err)
+ }
+ wantIndented, err = json.MarshalIndent(wantObj, "", " ")
+ if err != nil {
+ t.Fatalf("could not marshal want to indented JSON: %s", err)
+ }
+ t.Errorf("Analyzer.Analyze() = %s, want %s", gotIndented, wantIndented)
+ }
+ })
+ }
+}
diff --git a/pkg/analyzer/analyzers/dockerhub/helper.go b/pkg/analyzer/analyzers/dockerhub/helper.go
new file mode 100644
index 000000000..bb2f3d81c
--- /dev/null
+++ b/pkg/analyzer/analyzers/dockerhub/helper.go
@@ -0,0 +1,146 @@
+package dockerhub
+
+import (
+ "errors"
+ "fmt"
+ "sort"
+ "time"
+
+ "github.com/golang-jwt/jwt/v4"
+)
+
+// permission hierarchy - always keep from highest permission to lowest
+var permissionHierarchy = []string{"repo:admin", "repo:write", "repo:read", "repo:public_read"}
+
+// precompute a ranking map for the ranking approach.
+// lower index means higher permission.
+var permissionRank = func() map[string]int {
+ rank := make(map[string]int, len(permissionHierarchy))
+ // loop over permissions hierarchy to assign index to each permission
+ // as hierarchy start from highest to lowest, the 0 index will be assigned to highest possible permission and n will be lowest possible permission
+ for i, perm := range permissionHierarchy {
+ rank[perm] = i
+ }
+
+ // return the rank map with indexed permissions
+ return rank
+}()
+
+// decodeTokenToSecretInfo decode the jwt token and add the information to secret info
+func decodeTokenToSecretInfo(jwtToken string, secretInfo *SecretInfo) error {
+ type userClaims struct {
+ ID string `json:"uuid"`
+ Username string `json:"username"`
+ Email string `json:"email"`
+ }
+
+ type hubJwtClaims struct {
+ Scope string `json:"scope"`
+ HubClaims userClaims `json:"https://hub.docker.com"`
+ ExpiresIn int `json:"exp"`
+ jwt.RegisteredClaims
+ }
+
+ parser := jwt.NewParser()
+ token, _, err := parser.ParseUnverified(jwtToken, &hubJwtClaims{})
+ if err != nil {
+ return err
+ }
+
+ if claims, ok := token.Claims.(*hubJwtClaims); ok {
+ secretInfo.User = User{
+ ID: claims.HubClaims.ID,
+ Username: claims.HubClaims.Username,
+ Email: claims.HubClaims.Email,
+ }
+
+ secretInfo.ExpiresIn = humandReadableTime(claims.ExpiresIn)
+
+ secretInfo.Permissions = append(secretInfo.Permissions, claims.Scope)
+ secretInfo.Valid = true
+
+ return nil
+ }
+
+ return errors.New("failed to parse claims")
+}
+
+// repositoriesToSecretInfo translate repositories to secretInfo after sorting them
+func repositoriesToSecretInfo(username string, repos *RepositoriesResponse, secretInfo *SecretInfo) {
+ // sort the repositories first
+ sortRepositories(repos)
+
+ for _, repo := range repos.Result {
+ secretInfo.Repositories = append(secretInfo.Repositories, Repository{
+ // as repositories does not have a unique key, we make one by combining multiple fields
+ ID: fmt.Sprintf("%s/repo/%s/%s", username, repo.Type, repo.Name), // e.g: user123/repo/image/repo1
+ Name: repo.Name,
+ Type: repo.Type,
+ IsPrivate: repo.IsPrivate,
+ StarCount: repo.StarCount,
+ PullCount: repo.PullCount,
+ })
+ }
+}
+
+/*
+sortRepositories sort the repositories as following
+
+private:
+ - pullcount(descending)
+ - starcount(descending)
+
+public:
+ - pullcount(descending)
+ - starcount(descending)
+*/
+func sortRepositories(repos *RepositoriesResponse) {
+ sort.SliceStable(repos.Result, func(i, j int) bool {
+ a, b := repos.Result[i], repos.Result[j]
+
+ // prioritize private repositories over public
+ if a.IsPrivate != b.IsPrivate {
+ return a.IsPrivate
+ }
+
+ // sort by Pull Count (descending)
+ if a.PullCount != b.PullCount {
+ return a.PullCount > b.PullCount
+ }
+
+ // sort by Star Count (descending)
+ return a.StarCount > b.StarCount
+ })
+}
+
+// assignHighestPermission selects the highest available permission
+func assignHighestPermission(permissions []string) string {
+ bestRank := len(permissionHierarchy)
+ bestPerm := ""
+ for _, perm := range permissions {
+ // check in indexes permissions
+ if rank, ok := permissionRank[perm]; ok {
+ // early exit if highest permission is found.
+ if rank == 0 {
+ return perm
+ }
+
+ if rank < bestRank {
+ bestRank = rank
+ bestPerm = perm
+ }
+ }
+ }
+
+ return bestPerm
+
+}
+
+// humandReadableTime converts seconds to days, hours, minutes, or seconds based on the value
+func humandReadableTime(seconds int) string {
+ // Convert Unix timestamp to time.Time object
+ t := time.Unix(int64(seconds), 0)
+
+ // Format the time as "March 2" (Month Day format)
+ return t.Format("January 2, 2006")
+}
diff --git a/pkg/analyzer/analyzers/dockerhub/permissions.go b/pkg/analyzer/analyzers/dockerhub/permissions.go
new file mode 100644
index 000000000..d012c5abb
--- /dev/null
+++ b/pkg/analyzer/analyzers/dockerhub/permissions.go
@@ -0,0 +1,76 @@
+// Code generated by go generate; DO NOT EDIT.
+package dockerhub
+
+import "errors"
+
+type Permission int
+
+const (
+ Invalid Permission = iota
+ RepoRead Permission = iota
+ RepoWrite Permission = iota
+ RepoAdmin Permission = iota
+ RepoPublicRead Permission = iota
+)
+
+var (
+ PermissionStrings = map[Permission]string{
+ RepoRead: "repo:read",
+ RepoWrite: "repo:write",
+ RepoAdmin: "repo:admin",
+ RepoPublicRead: "repo:public_read",
+ }
+
+ StringToPermission = map[string]Permission{
+ "repo:read": RepoRead,
+ "repo:write": RepoWrite,
+ "repo:admin": RepoAdmin,
+ "repo:public_read": RepoPublicRead,
+ }
+
+ PermissionIDs = map[Permission]int{
+ RepoRead: 1,
+ RepoWrite: 2,
+ RepoAdmin: 3,
+ RepoPublicRead: 4,
+ }
+
+ IdToPermission = map[int]Permission{
+ 1: RepoRead,
+ 2: RepoWrite,
+ 3: RepoAdmin,
+ 4: RepoPublicRead,
+ }
+)
+
+// ToString converts a Permission enum to its string representation
+func (p Permission) ToString() (string, error) {
+ if str, ok := PermissionStrings[p]; ok {
+ return str, nil
+ }
+ return "", errors.New("invalid permission")
+}
+
+// ToID converts a Permission enum to its ID
+func (p Permission) ToID() (int, error) {
+ if id, ok := PermissionIDs[p]; ok {
+ return id, nil
+ }
+ return 0, errors.New("invalid permission")
+}
+
+// PermissionFromString converts a string representation to its Permission enum
+func PermissionFromString(s string) (Permission, error) {
+ if p, ok := StringToPermission[s]; ok {
+ return p, nil
+ }
+ return 0, errors.New("invalid permission string")
+}
+
+// PermissionFromID converts an ID to its Permission enum
+func PermissionFromID(id int) (Permission, error) {
+ if p, ok := IdToPermission[id]; ok {
+ return p, nil
+ }
+ return 0, errors.New("invalid permission ID")
+}
diff --git a/pkg/analyzer/analyzers/dockerhub/permissions.yaml b/pkg/analyzer/analyzers/dockerhub/permissions.yaml
new file mode 100644
index 000000000..ca6cafc03
--- /dev/null
+++ b/pkg/analyzer/analyzers/dockerhub/permissions.yaml
@@ -0,0 +1,5 @@
+permissions:
+- repo:read
+- repo:write
+- repo:admin
+- repo:public_read
diff --git a/pkg/analyzer/analyzers/dockerhub/requests.go b/pkg/analyzer/analyzers/dockerhub/requests.go
new file mode 100644
index 000000000..17d95e6e8
--- /dev/null
+++ b/pkg/analyzer/analyzers/dockerhub/requests.go
@@ -0,0 +1,115 @@
+package dockerhub
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+)
+
+// LoginResponse is the successful response from the /login API
+type LoginResponse struct {
+ Token string `json:"token"`
+}
+
+// ErrorLoginResponse is the error response from the /login API
+type ErrorLoginResponse struct {
+ Detail string `json:"detail"`
+ Login2FAToken string `json:"login_2fa_token"` // if login require 2FA authentication
+}
+
+// RepositoriesResponse is the /repositories/<namespace> response
+type RepositoriesResponse struct {
+ Result []struct {
+ Name string `json:"name"`
+ Type string `json:"repository_type"`
+ IsPrivate bool `json:"is_private"`
+ StarCount int `json:"star_count"`
+ PullCount int `json:"pull_count"`
+ } `json:"results"`
+}
+
+// login call the /login api with username and jwt token and if successful retrieve the token string and return
+func login(client *http.Client, username, pat string) (string, error) {
+ payload := strings.NewReader(fmt.Sprintf(`{"username": "%s", "password": "%s"}`, username, pat))
+
+ req, err := http.NewRequest(http.MethodPost, "https://hub.docker.com/v2/users/login", payload)
+ if err != nil {
+ return "", err
+ }
+
+ req.Header.Add("Content-Type", "application/json")
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer func() {
+ _, _ = io.Copy(io.Discard, resp.Body)
+ _ = resp.Body.Close()
+ }()
+
+ switch resp.StatusCode {
+ case http.StatusOK:
+ var token LoginResponse
+ if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
+ return "", err
+ }
+
+ return token.Token, nil
+ case http.StatusUnauthorized:
+ var errorLogin ErrorLoginResponse
+ if err := json.NewDecoder(resp.Body).Decode(&errorLogin); err != nil {
+ return "", err
+ }
+
+ if errorLogin.Login2FAToken != "" {
+ // TODO: handle it more appropriately
+ return "", errors.New("valid credentials; account require 2fa authentication")
+ }
+
+ return "", errors.New(errorLogin.Detail)
+ default:
+ return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ }
+}
+
+// fetchRepositories call /repositories/<user_name> API
+func fetchRepositories(client *http.Client, username, token string, secretInfo *SecretInfo) error {
+ req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("https://hub.docker.com/v2/repositories/%s", username), http.NoBody)
+ if err != nil {
+ return err
+ }
+
+ req.Header.Add("Content-Type", "application/json")
+ req.Header.Add("Authorization", "Bearer "+token)
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ _, _ = io.Copy(io.Discard, resp.Body)
+ _ = resp.Body.Close()
+ }()
+
+ switch resp.StatusCode {
+ case http.StatusOK:
+ var repositories RepositoriesResponse
+
+ if err := json.NewDecoder(resp.Body).Decode(&repositories); err != nil {
+ return err
+ }
+
+ // translate repositories response to secretInfo
+ repositoriesToSecretInfo(username, &repositories, secretInfo)
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ // the token is valid and this shall never happen because the least scope a token can have is repo:public_read.
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d; while fetching repositories information", resp.StatusCode)
+
+ }
+}
diff --git a/pkg/analyzer/analyzers/dockerhub/result_output.json b/pkg/analyzer/analyzers/dockerhub/result_output.json
new file mode 100644
index 000000000..eb8d178dd
--- /dev/null
+++ b/pkg/analyzer/analyzers/dockerhub/result_output.json
@@ -0,0 +1,43 @@
+{
+ "AnalyzerType": 4,
+ "Bindings": [
+ {
+ "Resource": {
+ "Name": "test-private",
+ "FullyQualifiedName": "truffledockerman/repo/image/test-private",
+ "Type": "image",
+ "Metadata": {
+ "is_private": true,
+ "pull_count": 0,
+ "star_count": 0
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "repo:admin",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "test",
+ "FullyQualifiedName": "truffledockerman/repo/image/test",
+ "Type": "image",
+ "Metadata": {
+ "is_private": false,
+ "pull_count": 0,
+ "star_count": 0
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "repo:admin",
+ "Parent": null
+ }
+ }
+ ],
+ "UnboundedResources": null,
+ "Metadata": {
+ "Valid_Key": true
+ }
+}
\ No newline at end of file
diff --git a/pkg/analyzer/cli.go b/pkg/analyzer/cli.go
index f6c8b5977..cc1e12170 100644
--- a/pkg/analyzer/cli.go
+++ b/pkg/analyzer/cli.go
@@ -7,6 +7,7 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/airbrake"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/asana"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/bitbucket"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/dockerhub"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/github"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/gitlab"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/huggingface"
@@ -84,5 +85,7 @@ func Run(keyType string, secretInfo SecretInfo) {
opsgenie.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
case "privatekey":
privatekey.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
+ case "dockerhub":
+ dockerhub.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["username"], secretInfo.Parts["pat"])
}
}
diff --git a/pkg/detectors/dockerhub/v1/dockerhub.go b/pkg/detectors/dockerhub/v1/dockerhub.go
index f2f2b807a..02c9ce800 100644
--- a/pkg/detectors/dockerhub/v1/dockerhub.go
+++ b/pkg/detectors/dockerhub/v1/dockerhub.go
@@ -81,6 +81,12 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
s1.Verified = isVerified
s1.ExtraData = extraData
s1.SetVerificationError(verificationErr)
+ if s1.Verified {
+ s1.AnalysisInfo = map[string]string{
+ "username": username,
+ "pat": token,
+ }
+ }
}
results = append(results, s1)
diff --git a/pkg/detectors/dockerhub/v2/dockerhub.go b/pkg/detectors/dockerhub/v2/dockerhub.go
index 9ed36886d..a108c358c 100644
--- a/pkg/detectors/dockerhub/v2/dockerhub.go
+++ b/pkg/detectors/dockerhub/v2/dockerhub.go
@@ -81,6 +81,12 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
s1.Verified = isVerified
s1.ExtraData = extraData
s1.SetVerificationError(verificationErr)
+ if s1.Verified {
+ s1.AnalysisInfo = map[string]string{
+ "username": username,
+ "pat": token,
+ }
+ }
}
results = append(results, s1)
diff --git a/pkg/detectors/dockerhub/v2/dockerhub_integration_test.go b/pkg/detectors/dockerhub/v2/dockerhub_integration_test.go
index 5f3526fc0..9b59e2570 100644
--- a/pkg/detectors/dockerhub/v2/dockerhub_integration_test.go
+++ b/pkg/detectors/dockerhub/v2/dockerhub_integration_test.go
@@ -6,6 +6,7 @@ package dockerhub
import (
"context"
"fmt"
+ "strings"
"testing"
"time"
@@ -53,6 +54,10 @@ func TestDockerhub_FromChunk(t *testing.T) {
{
DetectorType: detectorspb.DetectorType_Dockerhub,
Verified: true,
+ AnalysisInfo: map[string]string{
+ "username": username,
+ "pat": pat,
+ },
},
},
wantErr: false,
@@ -69,6 +74,10 @@ func TestDockerhub_FromChunk(t *testing.T) {
{
DetectorType: detectorspb.DetectorType_Dockerhub,
Verified: true,
+ AnalysisInfo: map[string]string{
+ "username": strings.Split(email, "-")[0],
+ "pat": pat,
+ },
},
},
wantErr: false,
diff --git a/pkg/tui/pages/analyze_form/analyze_form.go b/pkg/tui/pages/analyze_form/analyze_form.go
index d5c0e0656..a21a0876a 100644
--- a/pkg/tui/pages/analyze_form/analyze_form.go
+++ b/pkg/tui/pages/analyze_form/analyze_form.go
@@ -57,6 +57,17 @@ func New(c common.Common, keyType string) *AnalyzeForm {
Key: "url",
Required: true,
}}
+ case "dockerhub":
+ inputs = []textinputs.InputConfig{{
+ Label: "Username",
+ Key: "username",
+ Required: true,
+ }, {
+ Label: "Token(PAT)",
+ Key: "pat",
+ Required: true,
+ RedactInput: true,
+ }}
default:
inputs = []textinputs.InputConfig{{
Label: "Secret",