-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathhashicorpvaultbatchtoken.go
More file actions
181 lines (150 loc) · 4.1 KB
/
hashicorpvaultbatchtoken.go
File metadata and controls
181 lines (150 loc) · 4.1 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package hashicorpbatchtoken
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"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
}
var _ detectors.Detector = (*Scanner)(nil)
var _ detectors.EndpointCustomizer = (*Scanner)(nil)
var (
defaultClient = detectors.DetectorHttpClientWithNoLocalAddresses
// Batch tokens: hvb.<50-300 chars>
batchTokenPat = regexp.MustCompile(
`\b(hvb\.[A-Za-z0-9_.-]{50,300})\b`,
)
vaultUrlPat = regexp.MustCompile(`(https?:\/\/[^\s\/]*\.hashicorp\.cloud(?::\d+)?)(?:\/[^\s]*)?`)
)
func (s Scanner) Keywords() []string {
return []string{"hvb."}
}
func (Scanner) CloudEndpoint() string { return "" }
func (s Scanner) Description() string {
return "This detector detects and verifies HashiCorp Vault batch tokens"
}
func (s Scanner) getClient() *http.Client {
if s.client != nil {
return s.client
}
return defaultClient
}
func (s Scanner) FromData(
ctx context.Context,
verify bool,
data []byte,
) (results []detectors.Result, err error) {
dataStr := string(data)
uniqueTokens := make(map[string]struct{})
for _, match := range batchTokenPat.FindAllStringSubmatch(dataStr, -1) {
uniqueTokens[match[1]] = struct{}{}
}
var uniqueVaultUrls = make(map[string]struct{})
for _, match := range vaultUrlPat.FindAllStringSubmatch(dataStr, -1) {
url := strings.TrimSpace(match[1])
uniqueVaultUrls[url] = struct{}{}
}
endpoints := make([]string, 0, len(uniqueVaultUrls))
for endpoint := range uniqueVaultUrls {
endpoints = append(endpoints, endpoint)
}
for _, endpoint := range s.Endpoints(endpoints...) {
for token := range uniqueTokens {
result := detectors.Result{
DetectorType: detectorspb.DetectorType_HashiCorpVaultBatchToken,
Raw: []byte(token),
RawV2: []byte(token + endpoint),
Redacted: token[:8] + "...",
}
if verify {
verified, verificationResp, verificationErr := verifyVaultToken(
ctx,
s.getClient(),
endpoint,
token,
)
result.SetVerificationError(verificationErr, token)
result.Verified = verified
if verificationResp != nil {
result.ExtraData = map[string]string{
"policies": strings.Join(verificationResp.Data.Policies, ", "),
"orphan": fmt.Sprintf("%v", verificationResp.Data.Orphan),
"renewable": fmt.Sprintf("%v", verificationResp.Data.Renewable),
"type": verificationResp.Data.Type,
"entity_id": verificationResp.Data.EntityId,
}
}
}
results = append(results, result)
}
}
return
}
type lookupResponse struct {
Data struct {
DisplayName string `json:"display_name"`
EntityId string `json:"entity_id"`
ExpireTime string `json:"expire_time"`
Orphan bool `json:"orphan"`
Policies []string `json:"policies"`
Renewable bool `json:"renewable"`
Type string `json:"type"`
}
}
func verifyVaultToken(
ctx context.Context,
client *http.Client,
baseUrl string,
token string,
) (bool, *lookupResponse, error) {
url, err := url.JoinPath(baseUrl, "/v1/auth/token/lookup-self")
if err != nil {
return false, nil, err
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodGet,
url,
http.NoBody,
)
if err != nil {
return false, nil, err
}
req.Header.Set("X-Vault-Token", token)
res, err := client.Do(req)
if err != nil {
return false, nil, err
}
defer func() {
_, _ = io.Copy(io.Discard, res.Body)
_ = res.Body.Close()
}()
switch res.StatusCode {
case http.StatusOK:
var resp lookupResponse
if err := json.NewDecoder(res.Body).Decode(&resp); err != nil {
return false, nil, err
}
return true, &resp, nil
case http.StatusForbidden, http.StatusUnauthorized:
return false, nil, nil
default:
return false, nil, fmt.Errorf(
"unexpected HTTP response status %d",
res.StatusCode,
)
}
}
func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_HashiCorpVaultBatchToken
}