-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathjiradatacenterpat.go
More file actions
151 lines (127 loc) · 4.61 KB
/
jiradatacenterpat.go
File metadata and controls
151 lines (127 loc) · 4.61 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
package jiradatacenterpat
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
regexp "github.com/wasilibs/go-re2"
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
)
type Scanner struct {
client *http.Client
detectors.EndpointSetter
}
// Ensure the Scanner satisfies the interfaces at compile time.
var (
_ detectors.Detector = (*Scanner)(nil)
_ detectors.EndpointCustomizer = (*Scanner)(nil)
)
var (
defaultClient = common.SaneHttpClient()
// PATs are base64-encoded strings of the form <12-digit-id>:<20-random-bytes> (33 bytes, 44 chars, no padding).
// Since the first byte is always an ASCII digit (0x30–0x39), the first base64 character is always M, N, or O.
// This is also verified by generating 25+ tokens.
// The trailing boundary (?:[^A-Za-z0-9+/=]|\z) is used instead of \b to correctly handle tokens ending in + or /.
patPat = regexp.MustCompile(detectors.PrefixRegex([]string{"jira", "atlassian"}) + `\b([MNO][A-Za-z0-9+/]{43})(?:[^A-Za-z0-9+/=]|\z)`)
urlPat = regexp.MustCompile(detectors.PrefixRegex([]string{"jira", "atlassian"}) + `(https?://[A-Za-z0-9][A-Za-z0-9.\-]*(?::\d{1,5})?)`)
)
func (s Scanner) getClient() *http.Client {
if s.client != nil {
return s.client
}
return defaultClient
}
// Keywords are used for efficiently pre-filtering chunks.
func (s Scanner) Keywords() []string {
return []string{"jira", "atlassian"}
}
// FromData will find and optionally verify Jira Data Center PAT 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 tokens []string
for _, match := range patPat.FindAllStringSubmatch(dataStr, -1) {
tokens = append(tokens, match[1])
}
foundURLs := make(map[string]struct{})
for _, match := range urlPat.FindAllStringSubmatch(dataStr, -1) {
foundURLs[match[1]] = struct{}{}
}
uniqueURLs := make([]string, 0, len(foundURLs))
for url := range foundURLs {
uniqueURLs = append(uniqueURLs, url)
}
for _, token := range tokens {
for _, endpoint := range s.Endpoints(uniqueURLs...) {
s1 := detectors.Result{
DetectorType: detector_typepb.DetectorType_JiraDataCenterPAT,
Raw: []byte(token),
RawV2: []byte(token + endpoint),
Redacted: token[:3] + "..." + token[len(token)-3:],
}
if verify {
isVerified, extraData, verificationErr := verifyPAT(ctx, s.getClient(), endpoint, token)
s1.Verified = isVerified
s1.ExtraData = extraData
s1.SetVerificationError(verificationErr, token)
}
results = append(results, s1)
if s1.Verified {
break
}
}
}
return results, nil
}
// verifyPAT checks whether the token is valid by calling the /rest/api/2/myself endpoint,
// which returns the currently authenticated user.
// Docs: https://developer.atlassian.com/server/jira/platform/rest/v10002/api-group-myself/#api-api-2-myself-get
func verifyPAT(ctx context.Context, client *http.Client, baseURL, token string) (bool, map[string]string, error) {
u, err := detectors.ParseURLAndStripPathAndParams(baseURL)
if err != nil {
return false, nil, err
}
u.Path = "/rest/api/2/myself"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), http.NoBody)
if err != nil {
return false, nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := client.Do(req)
if err != nil {
return false, nil, err
}
defer func() {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}()
switch resp.StatusCode {
case http.StatusOK:
var result map[string]any
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
// 200 confirms the token is valid; failing to decode only means we can't extract extra data.
return true, nil, nil
}
extraData := map[string]string{}
if name, ok := result["displayName"].(string); ok {
extraData["display_name"] = name
}
if email, ok := result["emailAddress"].(string); ok {
extraData["email_address"] = email
}
return true, extraData, nil
case http.StatusUnauthorized:
return false, nil, nil
default:
return false, nil, fmt.Errorf("unexpected HTTP response status %d", resp.StatusCode)
}
}
func (s Scanner) Type() detector_typepb.DetectorType {
return detector_typepb.DetectorType_JiraDataCenterPAT
}
func (s Scanner) Description() string {
return "Jira Data Center is a self-hosted version of Jira. Personal Access Tokens (PATs) are used to authenticate API requests to Jira Data Center instances."
}