Skip to content

Find, verify, and analyze leaked credentials

Added DataBricks Analyzer (#4135)

Kashif Khan9a2b2681e220
diff --git a/pkg/analyzer/analyzers/analyzers.go b/pkg/analyzer/analyzers/analyzers.go
index fec29a341..7ed3a2b10 100644
--- a/pkg/analyzer/analyzers/analyzers.go
+++ b/pkg/analyzer/analyzers/analyzers.go
@@ -101,6 +101,7 @@ const (
AnalyzerTypeMux
AnalyzerTypePosthog
AnalyzerTypeDropbox
+ AnalyzerTypeDataBricks
// Add new items here with AnalyzerType prefix
)
@@ -147,6 +148,7 @@ var analyzerTypeStrings = map[AnalyzerType]string{
AnalyzerTypeMux: "Mux",
AnalyzerTypePosthog: "Posthog",
AnalyzerTypeDropbox: "Dropbox",
+ AnalyzerTypeDataBricks: "DataBricks",
// Add new mappings here
}
diff --git a/pkg/analyzer/analyzers/databricks/databricks.go b/pkg/analyzer/analyzers/databricks/databricks.go
new file mode 100644
index 000000000..9ec61d119
--- /dev/null
+++ b/pkg/analyzer/analyzers/databricks/databricks.go
@@ -0,0 +1,180 @@
+//go:generate generate_permissions permissions.yaml permissions.go databricks
+package databricks
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/fatih/color"
+ "github.com/jedib0t/go-pretty/v6/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
+}
+
+func (a Analyzer) Type() analyzers.AnalyzerType {
+ return analyzers.AnalyzerTypeDataBricks
+}
+
+func (a Analyzer) Analyze(ctx context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
+ token, exist := credInfo["token"]
+ if !exist {
+ return nil, fmt.Errorf("key not found in credential info")
+ }
+
+ domain, exist := credInfo["domain"]
+ if !exist {
+ return nil, fmt.Errorf("domain not found in credential info")
+ }
+
+ info, err := AnalyzePermissions(ctx, a.Cfg, domain, token)
+ if err != nil {
+ return nil, err
+ }
+
+ return secretInfoToAnalyzerResult(info), nil
+}
+
+func AnalyzeAndPrintPermissions(cfg *config.Config, domain, token string) {
+ ctx := context.Background()
+
+ info, err := AnalyzePermissions(ctx, cfg, domain, token)
+ 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
+ }
+
+ color.Green("[!] Valid DataBricks Access Token\n\n")
+
+ printUserInfo(info.UserInfo)
+ printTokenInfo(info.Tokens)
+ printPermissions(info.TokenPermissionLevels)
+
+ if len(info.Resources) > 0 {
+ printResources(info.Resources)
+ }
+
+ color.Yellow("\n[i] Expires: %s", "N/A (Refer to Token Information Table)")
+}
+
+func AnalyzePermissions(ctx context.Context, cfg *config.Config, domain, token string) (*SecretInfo, error) {
+ client := analyzers.NewAnalyzeClient(cfg)
+
+ var secretInfo = &SecretInfo{}
+
+ if err := captureUserInfo(ctx, client, domain, token, secretInfo); err != nil {
+ return nil, err
+ }
+
+ if err := captureTokensInfo(ctx, client, domain, token, secretInfo); err != nil {
+ return secretInfo, err
+ }
+
+ if err := captureTokenPermissions(ctx, client, domain, token, secretInfo); err != nil {
+ return secretInfo, err
+ }
+
+ // capture resources
+ if err := captureDataBricksResources(ctx, client, domain, token, secretInfo); err != nil {
+ return secretInfo, err
+ }
+
+ return secretInfo, nil
+}
+
+// secretInfoToAnalyzerResult translate secret info to Analyzer Result
+func secretInfoToAnalyzerResult(info *SecretInfo) *analyzers.AnalyzerResult {
+ if info == nil {
+ return nil
+ }
+
+ result := analyzers.AnalyzerResult{
+ AnalyzerType: analyzers.AnalyzerTypeDataBricks,
+ Metadata: map[string]any{},
+ Bindings: make([]analyzers.Binding, 0),
+ }
+
+ // extract information from resource to create bindings and append to result bindings
+ for _, resource := range info.Resources {
+ binding := analyzers.Binding{
+ Resource: analyzers.Resource{
+ Name: resource.Name,
+ FullyQualifiedName: fmt.Sprintf("databricks/%s/%s", resource.Type, resource.ID), // e.g: netlify/site/123
+ Type: resource.Type,
+ Metadata: map[string]any{}, // to avoid panic
+ },
+ }
+
+ for key, value := range resource.Metadata {
+ binding.Resource.Metadata[key] = value
+ }
+
+ // for each permission add a binding to resource
+ for _, perm := range info.TokenPermissionLevels {
+ binding.Permission = analyzers.Permission{
+ Value: perm,
+ }
+
+ result.Bindings = append(result.Bindings, binding)
+ }
+ }
+
+ return &result
+}
+
+// cli print functions
+func printUserInfo(user User) {
+ color.Yellow("[i] User Information:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"ID", "UserName", "Primary Email"})
+ t.AppendRow(table.Row{color.GreenString(user.ID), color.GreenString(user.UserName), color.GreenString(user.PrimaryEmail)})
+
+ t.Render()
+}
+
+func printTokenInfo(tokens []Token) {
+ color.Yellow("[i] Tokens Information:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Name", "Expiry Time", "Created By", "Last Used At"})
+ for _, token := range tokens {
+ t.AppendRow(table.Row{color.GreenString(token.Name),
+ color.GreenString(token.ExpiryTime), color.GreenString(token.CreatedBy), color.GreenString(token.LastUsedDay)})
+ }
+ t.Render()
+}
+
+func printPermissions(permissions []string) {
+ color.Yellow("[i] Token Permission Levels:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Permission Level"})
+ for _, permission := range permissions {
+ t.AppendRow(table.Row{color.GreenString(permission)})
+ }
+ t.Render()
+}
+
+func printResources(resources []DataBricksResource) {
+ color.Yellow("[i] Resources:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Name", "Type"})
+ for _, resource := range resources {
+ t.AppendRow(table.Row{color.GreenString(resource.Name), color.GreenString(resource.Type)})
+ }
+ t.Render()
+}
diff --git a/pkg/analyzer/analyzers/databricks/databricks_test.go b/pkg/analyzer/analyzers/databricks/databricks_test.go
new file mode 100644
index 000000000..b24afd9be
--- /dev/null
+++ b/pkg/analyzer/analyzers/databricks/databricks_test.go
@@ -0,0 +1,105 @@
+package databricks
+
+import (
+ _ "embed"
+ "encoding/json"
+ "sort"
+ "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", "analyzers1")
+ if err != nil {
+ t.Fatalf("could not get test secrets from GCP: %s", err)
+ }
+
+ token := testSecrets.MustGetField("DATABRICKS_TOKEN")
+ domain := testSecrets.MustGetField("DATABRICKS_DOMAIN")
+
+ tests := []struct {
+ name string
+ domain string
+ token string
+ want []byte // JSON string
+ wantErr bool
+ }{
+ {
+ name: "valid databricks credentials",
+ domain: domain,
+ token: token,
+ 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{"token": tt.token, "domain": tt.domain})
+ if (err != nil) != tt.wantErr {
+ t.Errorf("Analyzer.Analyze() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+
+ // Bindings need to be in the same order to be comparable
+ sortBindings(got.Bindings)
+
+ // 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)
+ }
+
+ // Bindings need to be in the same order to be comparable
+ sortBindings(wantObj.Bindings)
+
+ // 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)
+ }
+ })
+ }
+}
+
+// Helper function to sort bindings
+func sortBindings(bindings []analyzers.Binding) {
+ sort.SliceStable(bindings, func(i, j int) bool {
+ if bindings[i].Resource.Name == bindings[j].Resource.Name {
+ return bindings[i].Permission.Value < bindings[j].Permission.Value
+ }
+ return bindings[i].Resource.Name < bindings[j].Resource.Name
+ })
+}
diff --git a/pkg/analyzer/analyzers/databricks/models.go b/pkg/analyzer/analyzers/databricks/models.go
new file mode 100644
index 000000000..a7be95bd8
--- /dev/null
+++ b/pkg/analyzer/analyzers/databricks/models.go
@@ -0,0 +1,125 @@
+package databricks
+
+type ResourceType string
+
+func (r ResourceType) String() string {
+ return string(r)
+}
+
+const (
+ CurrentUser ResourceType = "User"
+ TokensInfo ResourceType = "Token"
+ TokenPermissions ResourceType = "Token Permission"
+ Repositories ResourceType = "Repository"
+ GitCredentials ResourceType = "Git Credential"
+ Jobs ResourceType = "Job"
+ Clusters ResourceType = "Cluster"
+ Groups ResourceType = "Group"
+ Users ResourceType = "Member"
+)
+
+type SecretInfo struct {
+ UserInfo User
+ TokenPermissionLevels []string
+ Tokens []Token
+ Resources []DataBricksResource
+}
+
+type User struct {
+ ID string
+ UserName string
+ PrimaryEmail string
+}
+
+type Token struct {
+ ID string
+ Name string
+ ExpiryTime string
+ CreatedBy string
+ LastUsedDay string
+}
+
+type DataBricksResource struct {
+ ID string
+ Name string
+ Type string
+ Metadata map[string]string
+}
+
+// API response models
+
+type CurrentUserInfo struct {
+ ID string `json:"id"`
+ UserName string `json:"userName"`
+ Emails []struct {
+ Display string `json:"display"`
+ Value string `json:"value"`
+ Primary bool `json:"primary"`
+ } `json:"emails"`
+}
+
+type Tokens struct {
+ TokensInfo []struct {
+ ID string `json:"token_id"`
+ Name string `json:"comment"`
+ ExpiryTime int `json:"expiry_time"`
+ LastUsedDay int `json:"last_used_day"`
+ CreatedBy string `json:"created_by_username"`
+ } `json:"token_infos"`
+}
+
+type Permissions struct {
+ PermissionLevels []struct {
+ Description string `json:"description"`
+ PermissionLevel string `json:"permission_level"`
+ } `json:"permission_levels"`
+}
+
+type ReposResponse struct {
+ Repositories []struct {
+ ID string `json:"id"`
+ Path string `json:"path"`
+ Provider string `json:"provider"`
+ URL string `json:"url"`
+ } `json:"repos"`
+}
+
+type GitCreds struct {
+ Credentials []struct {
+ ID string `json:"credentials_id"`
+ UserName string `json:"git_username"`
+ Provider string `json:"git_provider"`
+ } `json:"credentials"`
+}
+
+type JobsResponse struct {
+ Jobs []struct {
+ ID string `json:"job_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ } `json:"jobs"`
+}
+
+type ClustersResponse struct {
+ Clusters []struct {
+ ID string `json:"cluster_id"`
+ Name string `json:"cluster_name"`
+ CreatedBy string `json:"creator_user_name"`
+ } `json:"clusters"`
+}
+
+type GroupsResponse struct {
+ Resources []struct {
+ ID string `json:"id"`
+ Name string `json:"displayName"`
+ // TODO: capture members if needed
+ } `json:"Resources"`
+}
+
+type UsersResponse struct {
+ Resources []struct {
+ ID string `json:"id"`
+ UserName string `json:"userName"`
+ Active bool `json:"active"`
+ } `json:"Resources"`
+}
diff --git a/pkg/analyzer/analyzers/databricks/permissions.go b/pkg/analyzer/analyzers/databricks/permissions.go
new file mode 100644
index 000000000..fe7bcff57
--- /dev/null
+++ b/pkg/analyzer/analyzers/databricks/permissions.go
@@ -0,0 +1,66 @@
+// Code generated by go generate; DO NOT EDIT.
+package databricks
+
+import "errors"
+
+type Permission int
+
+const (
+ Invalid Permission = iota
+ CanManage Permission = iota
+ CanUse Permission = iota
+)
+
+var (
+ PermissionStrings = map[Permission]string{
+ CanManage: "CAN_MANAGE",
+ CanUse: "CAN_USE",
+ }
+
+ StringToPermission = map[string]Permission{
+ "CAN_MANAGE": CanManage,
+ "CAN_USE": CanUse,
+ }
+
+ PermissionIDs = map[Permission]int{
+ CanManage: 1,
+ CanUse: 2,
+ }
+
+ IdToPermission = map[int]Permission{
+ 1: CanManage,
+ 2: CanUse,
+ }
+)
+
+// 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/databricks/permissions.yaml b/pkg/analyzer/analyzers/databricks/permissions.yaml
new file mode 100644
index 000000000..7b75a67a1
--- /dev/null
+++ b/pkg/analyzer/analyzers/databricks/permissions.yaml
@@ -0,0 +1,3 @@
+permissions:
+ - CAN_MANAGE
+ - CAN_USE
diff --git a/pkg/analyzer/analyzers/databricks/requests.go b/pkg/analyzer/analyzers/databricks/requests.go
new file mode 100644
index 000000000..823db099e
--- /dev/null
+++ b/pkg/analyzer/analyzers/databricks/requests.go
@@ -0,0 +1,298 @@
+package databricks
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "time"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+var (
+ // ErrUnauthorized is returned when the Databricks API answers with HTTP-401.
+ errUnAuthorized = errors.New("invalid/expired personal access token")
+
+ apiEndpoints = map[ResourceType]string{
+ CurrentUser: "/api/2.0/preview/scim/v2/Me",
+ TokensInfo: "/api/2.0/token-management/tokens",
+ TokenPermissions: "/api/2.0/permissions/authorization/tokens/permissionLevels",
+ Repositories: "/api/2.0/repos",
+ GitCredentials: "/api/2.0/git-credentials",
+ Jobs: "/api/2.2/jobs/list",
+ Clusters: "/api/2.1/clusters/list",
+ Groups: "/api/2.0/preview/scim/v2/Groups",
+ Users: "/api/2.0/preview/scim/v2/Users",
+ /*
+ TODO:
+ - https://docs.databricks.com/api/gcp/workspace/workspace/list (list content inside path)
+ - http://docs.databricks.com/api/gcp/workspace/libraries/allclusterlibrarystatuses (list cluster statuses)
+ */
+ }
+)
+
+// doAndDecode performs an authenticated GET request against the constructed
+// Databricks URL and JSON-decodes the response into the supplied result.
+//
+// The generic type parameter T allows the caller to decide which concrete
+// struct the response should be unmarshalled into:
+func doAndDecode[T any](ctx context.Context, client *http.Client, domain string, rt ResourceType, token string, out *T) error {
+ u := url.URL{
+ Scheme: "https",
+ Host: domain,
+ Path: apiEndpoints[rt],
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), http.NoBody)
+ if err != nil {
+ return fmt.Errorf("building request: %w", err)
+ }
+
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
+ req.Header.Set("Accept", "application/json")
+
+ // Execute request and read / decode body. We stream directly into the
+ // decoder instead of loading the whole response into memory first.
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("performing request: %w", err)
+ }
+ defer func() {
+ _, _ = io.Copy(io.Discard, resp.Body)
+ _ = resp.Body.Close()
+ }()
+
+ switch resp.StatusCode {
+ case http.StatusOK:
+ if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
+ return fmt.Errorf("decoding response: %w", err)
+ }
+
+ return nil
+ case http.StatusUnauthorized:
+ return errUnAuthorized
+ default:
+ return fmt.Errorf("unexpected status code %d for API %s", resp.StatusCode, apiEndpoints[rt])
+ }
+}
+
+func captureDataBricksResources(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ if err := captureRepos(ctx, client, domain, token, secretInfo); err != nil {
+ return err
+ }
+
+ if err := captureGitCreds(ctx, client, domain, token, secretInfo); err != nil {
+ return err
+ }
+
+ if err := captureJobs(ctx, client, domain, token, secretInfo); err != nil {
+ return err
+ }
+
+ if err := captureClusters(ctx, client, domain, token, secretInfo); err != nil {
+ return err
+ }
+
+ if err := captureGroups(ctx, client, domain, token, secretInfo); err != nil {
+ return err
+ }
+
+ if err := captureUsers(ctx, client, domain, token, secretInfo); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func captureUserInfo(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var user CurrentUserInfo
+
+ if err := doAndDecode(ctx, client, domain, CurrentUser, token, &user); err != nil {
+ return err
+ }
+
+ secretInfo.UserInfo = User{
+ ID: user.ID,
+ UserName: user.UserName,
+ }
+
+ for _, email := range user.Emails {
+ if email.Primary {
+ secretInfo.UserInfo.PrimaryEmail = email.Value
+ }
+ }
+
+ return nil
+}
+
+func captureTokensInfo(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var tokens Tokens
+
+ if err := doAndDecode(ctx, client, domain, TokensInfo, token, &tokens); err != nil {
+ return err
+ }
+
+ for _, t := range tokens.TokensInfo {
+ secretInfo.Tokens = append(secretInfo.Tokens, Token{
+ ID: t.ID,
+ Name: t.Name,
+ ExpiryTime: readableTime(t.ExpiryTime),
+ LastUsedDay: readableTime(t.LastUsedDay),
+ CreatedBy: t.CreatedBy,
+ })
+ }
+
+ return nil
+}
+
+func captureTokenPermissions(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var permissions Permissions
+
+ if err := doAndDecode(ctx, client, domain, TokenPermissions, token, &permissions); err != nil {
+ return err
+ }
+
+ for _, item := range permissions.PermissionLevels {
+ secretInfo.TokenPermissionLevels = append(secretInfo.TokenPermissionLevels, item.PermissionLevel)
+ }
+
+ return nil
+}
+
+func captureRepos(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var repos ReposResponse
+
+ if err := doAndDecode(ctx, client, domain, Repositories, token, &repos); err != nil {
+ return err
+ }
+
+ for _, repo := range repos.Repositories {
+ if repo.ID == "" {
+ repo.ID = repo.URL
+ }
+
+ secretInfo.Resources = append(secretInfo.Resources, DataBricksResource{
+ ID: repo.ID,
+ Name: repo.Path,
+ Type: Repositories.String(),
+ Metadata: map[string]string{
+ "provider": repo.Provider,
+ "url": repo.URL,
+ },
+ })
+ }
+
+ return nil
+}
+
+func captureGitCreds(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var creds GitCreds
+
+ if err := doAndDecode(ctx, client, domain, GitCredentials, token, &creds); err != nil {
+ return err
+ }
+
+ for _, credential := range creds.Credentials {
+ secretInfo.Resources = append(secretInfo.Resources, DataBricksResource{
+ ID: credential.ID,
+ Name: credential.UserName,
+ Type: GitCredentials.String(),
+ Metadata: map[string]string{
+ "provider": credential.Provider,
+ },
+ })
+ }
+
+ return nil
+}
+
+func captureJobs(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var jobs JobsResponse
+
+ if err := doAndDecode(ctx, client, domain, Jobs, token, &jobs); err != nil {
+ return err
+ }
+
+ for _, job := range jobs.Jobs {
+ secretInfo.Resources = append(secretInfo.Resources, DataBricksResource{
+ ID: job.ID,
+ Name: job.Name,
+ Type: Jobs.String(),
+ Metadata: map[string]string{
+ "description": job.Description,
+ },
+ })
+ }
+
+ return nil
+}
+
+func captureClusters(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var clusters ClustersResponse
+
+ if err := doAndDecode(ctx, client, domain, Clusters, token, &clusters); err != nil {
+ return err
+ }
+
+ for _, cluster := range clusters.Clusters {
+ secretInfo.Resources = append(secretInfo.Resources, DataBricksResource{
+ ID: cluster.ID,
+ Name: cluster.Name,
+ Type: Clusters.String(),
+ Metadata: map[string]string{
+ "created by": cluster.CreatedBy,
+ },
+ })
+ }
+
+ return nil
+}
+
+func captureGroups(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var groups GroupsResponse
+
+ if err := doAndDecode(ctx, client, domain, Groups, token, &groups); err != nil {
+ return err
+ }
+
+ for _, group := range groups.Resources {
+ secretInfo.Resources = append(secretInfo.Resources, DataBricksResource{
+ ID: group.ID,
+ Name: group.Name,
+ Type: Groups.String(),
+ })
+ }
+
+ return nil
+}
+
+func captureUsers(ctx context.Context, client *http.Client, domain, token string, secretInfo *SecretInfo) error {
+ var users UsersResponse
+
+ if err := doAndDecode(ctx, client, domain, Users, token, &users); err != nil {
+ return err
+ }
+
+ for _, user := range users.Resources {
+ secretInfo.Resources = append(secretInfo.Resources, DataBricksResource{
+ ID: user.ID,
+ Name: user.UserName,
+ Type: Users.String(),
+ Metadata: map[string]string{
+ "active": fmt.Sprintf("%t", user.Active),
+ },
+ })
+ }
+
+ return nil
+}
+
+func readableTime(timestamp int) string {
+ timestampMillis := int64(timestamp)
+ t := time.Unix(timestampMillis/1000, (timestampMillis%1000)*int64(time.Millisecond))
+
+ return t.Format("2006-01-02 15:04:05")
+}
diff --git a/pkg/analyzer/analyzers/databricks/result_output.json b/pkg/analyzer/analyzers/databricks/result_output.json
new file mode 100644
index 000000000..4858fd8f4
--- /dev/null
+++ b/pkg/analyzer/analyzers/databricks/result_output.json
@@ -0,0 +1,119 @@
+{
+ "AnalyzerType": 41,
+ "Bindings": [
+ {
+ "Resource": {
+ "Name": "admins",
+ "FullyQualifiedName": "databricks/Group/601448505198850",
+ "Type": "Group",
+ "Metadata": {},
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_MANAGE",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "admins",
+ "FullyQualifiedName": "databricks/Group/601448505198850",
+ "Type": "Group",
+ "Metadata": {},
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_USE",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "[email protected]",
+ "FullyQualifiedName": "databricks/Member/8639341364955455",
+ "Type": "Member",
+ "Metadata": {
+ "active": "true"
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_MANAGE",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "[email protected]",
+ "FullyQualifiedName": "databricks/Member/8639341364955455",
+ "Type": "Member",
+ "Metadata": {
+ "active": "true"
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_USE",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "kashifkhan",
+ "FullyQualifiedName": "databricks/Git Credential/",
+ "Type": "Git Credential",
+ "Metadata": {
+ "provider": "gitHub"
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_MANAGE",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "kashifkhan",
+ "FullyQualifiedName": "databricks/Git Credential/",
+ "Type": "Git Credential",
+ "Metadata": {
+ "provider": "gitHub"
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_USE",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "users",
+ "FullyQualifiedName": "databricks/Group/1000729253926373",
+ "Type": "Group",
+ "Metadata": {},
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_MANAGE",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "users",
+ "FullyQualifiedName": "databricks/Group/1000729253926373",
+ "Type": "Group",
+ "Metadata": {},
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "CAN_USE",
+ "Parent": null
+ }
+ }
+ ],
+ "UnboundedResources": null,
+ "Metadata": {}
+}
\ No newline at end of file
diff --git a/pkg/analyzer/cli.go b/pkg/analyzer/cli.go
index 322ee3ed1..a1572a29e 100644
--- a/pkg/analyzer/cli.go
+++ b/pkg/analyzer/cli.go
@@ -11,6 +11,7 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/anthropic"
"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/databricks"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/digitalocean"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/dockerhub"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/dropbox"
@@ -142,5 +143,7 @@ func Run(keyType string, secretInfo SecretInfo) {
posthog.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
case "dropbox":
dropbox.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
+ case "databricks":
+ databricks.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["domain"], secretInfo.Parts["token"])
}
}
diff --git a/pkg/detectors/databrickstoken/databrickstoken.go b/pkg/detectors/databrickstoken/databrickstoken.go
index 246921b10..676de74a8 100644
--- a/pkg/detectors/databrickstoken/databrickstoken.go
+++ b/pkg/detectors/databrickstoken/databrickstoken.go
@@ -3,6 +3,7 @@ package databrickstoken
import (
"context"
"fmt"
+ "io"
"net/http"
"strings"
@@ -38,19 +39,21 @@ func (s Scanner) Keywords() []string {
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)
- matches := keyPat.FindAllStringSubmatch(dataStr, -1)
- domainMatches := domain.FindAllStringSubmatch(dataStr, -1)
-
- for _, match := range matches {
- resMatch := strings.TrimSpace(match[1])
+ var uniqueDomains, uniqueTokens = make(map[string]struct{}), make(map[string]struct{})
+ for _, match := range domain.FindAllStringSubmatch(dataStr, -1) {
+ uniqueDomains[strings.TrimSpace(match[1])] = struct{}{}
+ }
- for _, domainmatch := range domainMatches {
- resDomainMatch := strings.TrimSpace(domainmatch[1])
+ for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {
+ uniqueTokens[match[1]] = struct{}{}
+ }
+ for token := range uniqueTokens {
+ for domain := range uniqueDomains {
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_DatabricksToken,
- Raw: []byte(resMatch),
- RawV2: []byte(resMatch + resDomainMatch),
+ Raw: []byte(token),
+ RawV2: []byte(token + domain),
}
if verify {
@@ -58,24 +61,16 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
if client == nil {
client = defaultClient
}
- req, err := http.NewRequestWithContext(ctx, "GET", "https://"+resDomainMatch+"/api/2.0/clusters/list", nil)
- if err != nil {
- continue
- }
- req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", resMatch))
- res, err := client.Do(req)
- if err == nil {
- defer res.Body.Close()
- if res.StatusCode >= 200 && res.StatusCode < 300 {
- s1.Verified = true
- } else if res.StatusCode == 403 {
- // nothing to do here
- } else {
- err = fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
- s1.SetVerificationError(err, resMatch)
+
+ isVerified, verificationErr := verifyDatabricksToken(client, domain, token)
+ s1.Verified = isVerified
+ s1.SetVerificationError(verificationErr)
+
+ if s1.Verified {
+ s1.AnalysisInfo = map[string]string{
+ "token": token,
+ "domain": domain,
}
- } else {
- s1.SetVerificationError(err, resMatch)
}
}
@@ -92,3 +87,30 @@ func (s Scanner) Type() detectorspb.DetectorType {
func (s Scanner) Description() string {
return "Databricks is a cloud data platform. Databricks tokens can be used to authenticate and interact with Databricks services and APIs."
}
+
+func verifyDatabricksToken(client *http.Client, domain, token string) (bool, error) {
+ req, err := http.NewRequest(http.MethodGet, "https://"+domain+"/api/2.0/preview/scim/v2/Me", nil)
+ if err != nil {
+ return false, err
+ }
+
+ req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
+ resp, err := client.Do(req)
+ if err != nil {
+ return false, err
+ }
+
+ defer func() {
+ _, _ = io.Copy(io.Discard, resp.Body)
+ _ = resp.Body.Close()
+ }()
+
+ switch resp.StatusCode {
+ case http.StatusOK:
+ return true, nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return false, nil
+ default:
+ return false, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ }
+}
diff --git a/pkg/detectors/databrickstoken/databrickstoken_integration_test.go b/pkg/detectors/databrickstoken/databrickstoken_integration_test.go
index 80274bdd8..9957dcb0f 100644
--- a/pkg/detectors/databrickstoken/databrickstoken_integration_test.go
+++ b/pkg/detectors/databrickstoken/databrickstoken_integration_test.go
@@ -21,7 +21,7 @@ import (
func TestDatabricksToken_FromChunk(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
- testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors2")
+ testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors5")
if err != nil {
t.Fatalf("could not get test secrets from GCP: %s", err)
}
@@ -138,7 +138,7 @@ func TestDatabricksToken_FromChunk(t *testing.T) {
t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())
}
}
- ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "verificationError")
+ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "verificationError", "AnalysisInfo")
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
t.Errorf("DatabricksToken.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
}
diff --git a/pkg/tui/pages/analyze_form/analyze_form.go b/pkg/tui/pages/analyze_form/analyze_form.go
index 87be5322b..aeea6e943 100644
--- a/pkg/tui/pages/analyze_form/analyze_form.go
+++ b/pkg/tui/pages/analyze_form/analyze_form.go
@@ -106,6 +106,17 @@ func New(c common.Common, keyType string) *AnalyzeForm {
Key: "key",
Required: true,
}}
+ case "databricks":
+ inputs = []textinputs.InputConfig{{
+ Label: "Access Token",
+ Key: "token",
+ Required: true,
+ RedactInput: true,
+ }, {
+ Label: "Domain",
+ Key: "domain",
+ Required: true,
+ }}
default:
inputs = []textinputs.InputConfig{{
Label: "Secret",