Skip to content

Find, verify, and analyze leaked credentials

optimized and updated mailgun analyzer (#3899)

Kashif Khanf3237c5f1eab
diff --git a/pkg/analyzer/analyzers/mailgun/expected_output.json b/pkg/analyzer/analyzers/mailgun/expected_output.json
index 5ed074c14..1d1c6f161 100644
--- a/pkg/analyzer/analyzers/mailgun/expected_output.json
+++ b/pkg/analyzer/analyzers/mailgun/expected_output.json
@@ -1,25 +1,25 @@
{
"AnalyzerType": 8,
"Bindings": [
- {
- "Resource": {
- "Name": "sandbox19e49763d44e498e850589ea7d54bd82.mailgun.org",
- "FullyQualifiedName": "mailgun/6478cb31d026c112819856cd/sandbox19e49763d44e498e850589ea7d54bd82.mailgun.org",
- "Type": "domain",
- "Metadata": {
- "created_at": "Thu, 01 Jun 2023 16:45:37 GMT",
- "is_disabled": false,
- "state": "active",
- "type": "sandbox"
- },
- "Parent": null
- },
- "Permission": {
- "Value": "full_access",
- "Parent": null
- }
- }
+ {
+ "Resource": {
+ "Name": "sandbox19e49763d44e498e850589ea7d54bd82.mailgun.org",
+ "FullyQualifiedName": "mailgun/6478cb31d026c112819856cd/sandbox19e49763d44e498e850589ea7d54bd82.mailgun.org",
+ "Type": "domain",
+ "Metadata": {
+ "created_at": "Thu, 01 Jun 2023 16:45:37 GMT",
+ "is_disabled": false,
+ "state": "active",
+ "type": "sandbox"
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "full_access",
+ "Parent": null
+ }
+ }
],
"UnboundedResources": null,
"Metadata": null
- }
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/pkg/analyzer/analyzers/mailgun/mailgun.go b/pkg/analyzer/analyzers/mailgun/mailgun.go
index 2c499000f..b43bb7204 100644
--- a/pkg/analyzer/analyzers/mailgun/mailgun.go
+++ b/pkg/analyzer/analyzers/mailgun/mailgun.go
@@ -2,10 +2,7 @@
package mailgun
import (
- "encoding/json"
"errors"
- "fmt"
- "net/http"
"os"
"strconv"
@@ -22,6 +19,15 @@ type Analyzer struct {
Cfg *config.Config
}
+type SecretInfo struct {
+ ID string // key id
+ UserName string
+ Type string // type of key
+ Role string // key role
+ ExpiresAt string // key expiry time if any
+ Domains []Domain
+}
+
func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeMailgun }
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
@@ -34,19 +40,20 @@ func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analy
if err != nil {
return nil, err
}
+
return secretInfoToAnalyzerResult(info), nil
}
-func secretInfoToAnalyzerResult(info *DomainsJSON) *analyzers.AnalyzerResult {
+func secretInfoToAnalyzerResult(info *SecretInfo) *analyzers.AnalyzerResult {
if info == nil {
return nil
}
result := analyzers.AnalyzerResult{
AnalyzerType: analyzers.AnalyzerTypeMailgun,
- Bindings: make([]analyzers.Binding, len(info.Items)),
+ Bindings: make([]analyzers.Binding, len(info.Domains)),
}
- for idx, domain := range info.Items {
+ for idx, domain := range info.Domains {
result.Bindings[idx] = analyzers.Binding{
Resource: analyzers.Resource{
Name: domain.URL,
@@ -59,6 +66,7 @@ func secretInfoToAnalyzerResult(info *DomainsJSON) *analyzers.AnalyzerResult {
"is_disabled": domain.IsDisabled,
},
},
+
Permission: analyzers.Permission{
Value: PermissionStrings[FullAccess],
},
@@ -67,87 +75,60 @@ func secretInfoToAnalyzerResult(info *DomainsJSON) *analyzers.AnalyzerResult {
return &result
}
-type Domain struct {
- ID string `json:"id"`
- URL string `json:"name"`
- IsDisabled bool `json:"is_disabled"`
- Type string `json:"type"`
- State string `json:"state"`
- CreatedAt string `json:"created_at"`
-}
-
-type DomainsJSON struct {
- Items []Domain `json:"items"`
- TotalCount int `json:"total_count"`
-}
-
-func getDomains(cfg *config.Config, apiKey string) (DomainsJSON, int, error) {
- var domainsJSON DomainsJSON
-
- client := analyzers.NewAnalyzeClient(cfg)
- req, err := http.NewRequest("GET", "https://api.mailgun.net/v4/domains", nil)
+func AnalyzeAndPrintPermissions(cfg *config.Config, apiKey string) {
+ info, err := AnalyzePermissions(cfg, apiKey)
if err != nil {
- return domainsJSON, -1, err
+ color.Red("[x] %s", err.Error())
+ return
}
- req.SetBasicAuth("api", apiKey)
- resp, err := client.Do(req)
- if err != nil {
- return domainsJSON, -1, err
- }
+ color.Green("[i] Valid Mailgun API key\n\n")
+ printKeyInfo(info)
+ printDomains(info.Domains)
+ color.Yellow("[i] Permissions: Full Access\n\n")
+}
- if resp.StatusCode != 200 {
- return domainsJSON, resp.StatusCode, nil
- }
+func AnalyzePermissions(cfg *config.Config, apiKey string) (*SecretInfo, error) {
+ var secretInfo SecretInfo
- defer resp.Body.Close()
+ var client = analyzers.NewAnalyzeClient(cfg)
- err = json.NewDecoder(resp.Body).Decode(&domainsJSON)
- if err != nil {
- return domainsJSON, resp.StatusCode, err
+ if err := getDomains(client, apiKey, &secretInfo); err != nil {
+ return &secretInfo, err
}
- return domainsJSON, resp.StatusCode, nil
-}
-func AnalyzeAndPrintPermissions(cfg *config.Config, apiKey string) {
- data, err := AnalyzePermissions(cfg, apiKey)
- if err != nil {
- color.Red("[x] %s", err.Error())
- return
+ if err := getKeys(client, apiKey, &secretInfo); err != nil {
+ return &secretInfo, err
}
- printMetadata(data)
+ return &secretInfo, nil
}
-func AnalyzePermissions(cfg *config.Config, apiKey string) (*DomainsJSON, error) {
- // Get the domains associated with the API key
- domains, statusCode, err := getDomains(cfg, apiKey)
- if err != nil {
- return nil, fmt.Errorf("Error getting domains: %s", err)
+func printKeyInfo(info *SecretInfo) {
+ if info.ID == "" {
+ color.Red("[i] Key information not found")
+ return
}
- if statusCode != 200 {
- return nil, fmt.Errorf("Invalid Mailgun API key.")
- }
- color.Green("[i] Valid Mailgun API key\n\n")
- color.Green("[i] Permissions: Full Access\n\n")
-
- return &domains, nil
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Key ID", "UserName/Requester", "Key Type", "Expires At", "Role"})
+ t.AppendRow(table.Row{info.ID, info.UserName, info.Type, info.ExpiresAt, info.Role})
+ t.Render()
}
-
-func printMetadata(domains *DomainsJSON) {
- if domains.TotalCount == 0 {
+func printDomains(domains []Domain) {
+ if len(domains) == 0 {
color.Red("[i] No domains found")
return
}
- color.Yellow("[i] Found %d domain(s)", domains.TotalCount)
+
+ color.Yellow("[i] Found %d domain(s)", len(domains))
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(table.Row{"Domain", "Type", "State", "Created At", "Disabled"})
- for _, domain := range domains.Items {
-
+ for _, domain := range domains {
var colorFunc func(format string, a ...interface{}) string
switch {
case domain.IsDisabled:
@@ -166,5 +147,6 @@ func printMetadata(domains *DomainsJSON) {
colorFunc(strconv.FormatBool(domain.IsDisabled)),
})
}
+
t.Render()
}
diff --git a/pkg/analyzer/analyzers/mailgun/requests.go b/pkg/analyzer/analyzers/mailgun/requests.go
new file mode 100644
index 000000000..ab7da22da
--- /dev/null
+++ b/pkg/analyzer/analyzers/mailgun/requests.go
@@ -0,0 +1,124 @@
+package mailgun
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+)
+
+// DomainsJSON is /domains API response
+type DomainsJSON struct {
+ Items []Domain `json:"items"`
+ TotalCount int `json:"total_count"`
+}
+
+// Domain is a single mailgun domain details
+type Domain struct {
+ ID string `json:"id"`
+ URL string `json:"name"`
+ IsDisabled bool `json:"is_disabled"`
+ Type string `json:"type"`
+ State string `json:"state"`
+ CreatedAt string `json:"created_at"`
+}
+
+// KeysJSON is /v1/keys API response
+type KeysJSON struct {
+ Items []Key `json:"items"`
+ TotalCount int `json:"total_count"`
+}
+
+// Key is a single mailgun Key details
+type Key struct {
+ ID string `json:"id"`
+ Requester string `json:"requestor"`
+ UserName string `json:"user_name"`
+ Role string `json:"role"`
+ Type string `json:"kind"`
+ ExpiresAt string `json:"expires_at"`
+}
+
+// getDomains list all domains
+func getDomains(client *http.Client, apiKey string, secretInfo *SecretInfo) error {
+ var domainsJSON DomainsJSON
+
+ req, err := http.NewRequest("GET", "https://api.mailgun.net/v4/domains", nil)
+ if err != nil {
+ return err
+ }
+
+ req.SetBasicAuth("api", apiKey)
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != 200 {
+ return fmt.Errorf("invalid Mailgun API key")
+ }
+
+ err = json.NewDecoder(resp.Body).Decode(&domainsJSON)
+ if err != nil {
+ return err
+ }
+
+ // populate secretInfo with domains
+ secretInfo.Domains = append(secretInfo.Domains, domainsJSON.Items...)
+
+ return nil
+}
+
+func getKeys(client *http.Client, apiKey string, secretInfo *SecretInfo) error {
+ var keysJSON KeysJSON
+
+ req, err := http.NewRequest("GET", "https://api.mailgun.net/v1/keys", nil)
+ if err != nil {
+ return err
+ }
+
+ req.SetBasicAuth("api", apiKey)
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != 200 {
+ return fmt.Errorf("invalid Mailgun API key")
+ }
+
+ err = json.NewDecoder(resp.Body).Decode(&keysJSON)
+ if err != nil {
+ return err
+ }
+
+ // populate secretInfo with key details
+ for _, key := range keysJSON.Items {
+ // filter the exact key which we are analyzing
+ // ID is actually the suffix of actual apiKeys
+ if strings.Contains(apiKey, key.ID) {
+ keyToSecretInfo(key, secretInfo)
+ }
+ }
+
+ return nil
+}
+
+func keyToSecretInfo(key Key, secretInfo *SecretInfo) {
+ secretInfo.ID = key.ID
+ if key.UserName != "" {
+ secretInfo.UserName = key.UserName
+ } else {
+ secretInfo.UserName = key.Requester
+ }
+
+ secretInfo.Role = key.Role
+ secretInfo.Type = key.Type
+ if secretInfo.ExpiresAt != "" {
+ secretInfo.ExpiresAt = key.ExpiresAt
+ } else {
+ secretInfo.ExpiresAt = "Never"
+ }
+}