-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathhashicorpvaultauth.go
More file actions
158 lines (131 loc) · 4.6 KB
/
hashicorpvaultauth.go
File metadata and controls
158 lines (131 loc) · 4.6 KB
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
package hashicorpvaultauth
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
regexp "github.com/wasilibs/go-re2"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)
type Scanner struct {
client *http.Client
detectors.DefaultMultiPartCredentialProvider
detectors.EndpointSetter
}
// Ensure the Scanner satisfies the interface at compile time.
var _ detectors.Detector = (*Scanner)(nil)
var _ detectors.EndpointCustomizer = (*Scanner)(nil)
var (
defaultClient = detectors.DetectorHttpClientWithNoLocalAddresses
roleIdPat = regexp.MustCompile(detectors.PrefixRegex([]string{"role"}) + `\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b`)
secretIdPat = regexp.MustCompile(detectors.PrefixRegex([]string{"secret"}) + `\b([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\b`)
// Vault URL pattern - HashiCorp Cloud or any HTTPS/HTTP Vault endpoint
vaultUrlPat = regexp.MustCompile(`(https?:\/\/[^\s\/]*\.hashicorp\.cloud(?::\d+)?)(?:\/[^\s]*)?`)
)
// Keywords are used for efficiently pre-filtering chunks.
func (s Scanner) Keywords() []string {
return []string{"hashicorp"}
}
// FromData will find and optionally verify HashiCorp Vault AppRole secrets in a given set of bytes.
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)
var uniqueRoleIds = make(map[string]struct{})
for _, match := range roleIdPat.FindAllStringSubmatch(dataStr, -1) {
roleId := strings.TrimSpace(match[1])
uniqueRoleIds[roleId] = struct{}{}
}
var uniqueSecretIds = make(map[string]struct{})
for _, match := range secretIdPat.FindAllStringSubmatch(dataStr, -1) {
secretId := strings.TrimSpace(match[1])
uniqueSecretIds[secretId] = struct{}{}
}
var uniqueVaultUrls = make(map[string]struct{})
for _, match := range vaultUrlPat.FindAllString(dataStr, -1) {
url := strings.TrimSpace(match)
uniqueVaultUrls[url] = struct{}{}
}
// If no roleIds or secrets found, return empty results
if len(uniqueRoleIds) == 0 || len(uniqueSecretIds) == 0 {
return results, nil
}
endpoints := make([]string, 0, len(uniqueVaultUrls))
for endpoint := range uniqueVaultUrls {
endpoints = append(endpoints, endpoint)
}
// create combination results that can be verified
for roleId := range uniqueRoleIds {
for secretId := range uniqueSecretIds {
for _, vaultUrl := range s.Endpoints(endpoints...) {
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_HashiCorpVaultAuth,
Raw: []byte(secretId),
RawV2: []byte(fmt.Sprintf("%s:%s", roleId, secretId)),
ExtraData: map[string]string{
"URL": vaultUrl,
},
}
if verify {
client := s.client
if client == nil {
client = defaultClient
}
isVerified, verificationErr := verifyMatch(ctx, client, roleId, secretId, vaultUrl)
s1.Verified = isVerified
s1.SetVerificationError(verificationErr, roleId, secretId, vaultUrl)
}
results = append(results, s1)
}
}
}
return results, nil
}
func verifyMatch(ctx context.Context, client *http.Client, roleId, secretId, vaultUrl string) (bool, error) {
payload := map[string]string{
"role_id": roleId,
"secret_id": secretId,
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return false, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, vaultUrl+"/v1/auth/approle/login", bytes.NewBuffer(jsonPayload))
if err != nil {
return false, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Vault-Namespace", "admin")
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.StatusBadRequest:
body, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}
if strings.Contains(string(body), "invalid role or secret ID") {
return false, nil
} else {
return false, fmt.Errorf("unexpected HTTP response status %d", resp.StatusCode)
}
default:
return false, fmt.Errorf("unexpected HTTP response status %d", resp.StatusCode)
}
}
func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_HashiCorpVaultAuth
}
func (s Scanner) Description() string {
return "HashiCorp Vault AppRole authentication method uses role_id and secret_id for machine-to-machine authentication. These credentials can be used to authenticate with Vault and obtain tokens for accessing secrets."
}