Skip to content

Commit f726d02

Browse files
authored
Add new detector for Twitch OAuth Access Tokens (#3756)
* add detector for twitch access tokens * add detector for twitch access tokens
1 parent 4949561 commit f726d02

File tree

7 files changed

+368
-8
lines changed

7 files changed

+368
-8
lines changed

pkg/detectors/twitch/twitch.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ package twitch
33
import (
44
"context"
55
"fmt"
6-
regexp "github.com/wasilibs/go-re2"
76
"net/http"
87
"net/url"
98
"strconv"
109
"strings"
1110

11+
regexp "github.com/wasilibs/go-re2"
12+
1213
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
1314
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
1415
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
@@ -117,5 +118,5 @@ func (s Scanner) Type() detectorspb.DetectorType {
117118
}
118119

119120
func (s Scanner) Description() string {
120-
return "Twitch is a live streaming service. Twitch API keys can be used to access and modify data on the Twitch platform."
121+
return "Twitch is a live streaming service. Twitch client credentials can be used to access and modify data on the Twitch platform."
121122
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package twitchaccesstoken
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"io"
7+
"net/http"
8+
9+
regexp "github.com/wasilibs/go-re2"
10+
11+
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
12+
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
13+
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
14+
)
15+
16+
type Scanner struct {
17+
client *http.Client
18+
}
19+
20+
// Ensure the Scanner satisfies the interface at compile time.
21+
var _ detectors.Detector = (*Scanner)(nil)
22+
23+
var (
24+
defaultClient = common.SaneHttpClient()
25+
// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.
26+
keyPat = regexp.MustCompile(`\b([0-9a-z]{30})\b`)
27+
)
28+
29+
// Keywords are used for efficiently pre-filtering chunks.
30+
// Use identifiers in the secret preferably, or the provider name.
31+
func (s Scanner) Keywords() []string {
32+
return []string{"twitch"}
33+
}
34+
35+
// FromData will find and optionally verify Twitchaccesstoken secrets in a given set of bytes.
36+
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
37+
dataStr := string(data)
38+
39+
uniqueMatches := make(map[string]struct{})
40+
for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {
41+
uniqueMatches[match[1]] = struct{}{}
42+
}
43+
44+
for match := range uniqueMatches {
45+
s1 := detectors.Result{
46+
DetectorType: detectorspb.DetectorType_TwitchAccessToken,
47+
Raw: []byte(match),
48+
}
49+
50+
if verify {
51+
client := s.client
52+
if client == nil {
53+
client = defaultClient
54+
}
55+
56+
isVerified, extraData, verificationErr := verifyMatch(ctx, client, match)
57+
s1.Verified = isVerified
58+
s1.ExtraData = extraData
59+
s1.SetVerificationError(verificationErr, match)
60+
}
61+
62+
results = append(results, s1)
63+
}
64+
65+
return
66+
}
67+
68+
func verifyMatch(ctx context.Context, client *http.Client, token string) (bool, map[string]string, error) {
69+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://id.twitch.tv/oauth2/validate", nil)
70+
if err != nil {
71+
return false, nil, nil
72+
}
73+
74+
req.Header.Add("Authorization", fmt.Sprintf("OAuth %s", token))
75+
res, err := client.Do(req)
76+
if err != nil {
77+
return false, nil, err
78+
}
79+
defer func() {
80+
_, _ = io.Copy(io.Discard, res.Body)
81+
_ = res.Body.Close()
82+
}()
83+
84+
switch res.StatusCode {
85+
case http.StatusOK:
86+
// If the endpoint returns useful information, we can return it as a map.
87+
return true, nil, nil
88+
case http.StatusUnauthorized:
89+
// The secret is determinately not verified (nothing to do)
90+
return false, nil, nil
91+
default:
92+
return false, nil, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
93+
}
94+
}
95+
96+
func (s Scanner) Type() detectorspb.DetectorType {
97+
return detectorspb.DetectorType_TwitchAccessToken
98+
}
99+
100+
func (s Scanner) Description() string {
101+
return "Twitch is a live streaming service. Twitch access tokens can be used to access and modify data on the Twitch platform."
102+
}
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
//go:build detectors
2+
// +build detectors
3+
4+
package twitchaccesstoken
5+
6+
import (
7+
"context"
8+
"fmt"
9+
"testing"
10+
"time"
11+
12+
"github.com/google/go-cmp/cmp"
13+
"github.com/google/go-cmp/cmp/cmpopts"
14+
15+
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
16+
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
17+
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
18+
)
19+
20+
func TestTwitchaccesstoken_FromChunk(t *testing.T) {
21+
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
22+
defer cancel()
23+
testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors5")
24+
if err != nil {
25+
t.Fatalf("could not get test secrets from GCP: %s", err)
26+
}
27+
secret := testSecrets.MustGetField("TWITCHACCESSTOKEN")
28+
inactiveSecret := testSecrets.MustGetField("TWITCHACCESSTOKEN_INACTIVE")
29+
30+
type args struct {
31+
ctx context.Context
32+
data []byte
33+
verify bool
34+
}
35+
tests := []struct {
36+
name string
37+
s Scanner
38+
args args
39+
want []detectors.Result
40+
wantErr bool
41+
wantVerificationErr bool
42+
}{
43+
{
44+
name: "found, verified",
45+
s: Scanner{},
46+
args: args{
47+
ctx: context.Background(),
48+
data: []byte(fmt.Sprintf("You can find a twitchaccesstoken secret %s within", secret)),
49+
verify: true,
50+
},
51+
want: []detectors.Result{
52+
{
53+
DetectorType: detectorspb.DetectorType_TwitchAccessToken,
54+
Verified: true,
55+
},
56+
},
57+
wantErr: false,
58+
wantVerificationErr: false,
59+
},
60+
{
61+
name: "found, unverified",
62+
s: Scanner{},
63+
args: args{
64+
ctx: context.Background(),
65+
data: []byte(fmt.Sprintf("You can find a twitchaccesstoken secret %s within but not valid", inactiveSecret)), // the secret would satisfy the regex but not pass validation
66+
verify: true,
67+
},
68+
want: []detectors.Result{
69+
{
70+
DetectorType: detectorspb.DetectorType_TwitchAccessToken,
71+
Verified: false,
72+
},
73+
},
74+
wantErr: false,
75+
wantVerificationErr: false,
76+
},
77+
{
78+
name: "not found",
79+
s: Scanner{},
80+
args: args{
81+
ctx: context.Background(),
82+
data: []byte("You cannot find the secret within"),
83+
verify: true,
84+
},
85+
want: nil,
86+
wantErr: false,
87+
wantVerificationErr: false,
88+
},
89+
{
90+
name: "found, would be verified if not for timeout",
91+
s: Scanner{client: common.SaneHttpClientTimeOut(1 * time.Microsecond)},
92+
args: args{
93+
ctx: context.Background(),
94+
data: []byte(fmt.Sprintf("You can find a twitchaccesstoken secret %s within", secret)),
95+
verify: true,
96+
},
97+
want: []detectors.Result{
98+
{
99+
DetectorType: detectorspb.DetectorType_TwitchAccessToken,
100+
Verified: false,
101+
},
102+
},
103+
wantErr: false,
104+
wantVerificationErr: true,
105+
},
106+
{
107+
name: "found, verified but unexpected api surface",
108+
s: Scanner{client: common.ConstantResponseHttpClient(404, "")},
109+
args: args{
110+
ctx: context.Background(),
111+
data: []byte(fmt.Sprintf("You can find a twitchaccesstoken secret %s within", secret)),
112+
verify: true,
113+
},
114+
want: []detectors.Result{
115+
{
116+
DetectorType: detectorspb.DetectorType_TwitchAccessToken,
117+
Verified: false,
118+
},
119+
},
120+
wantErr: false,
121+
wantVerificationErr: true,
122+
},
123+
}
124+
for _, tt := range tests {
125+
t.Run(tt.name, func(t *testing.T) {
126+
got, err := tt.s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
127+
if (err != nil) != tt.wantErr {
128+
t.Errorf("Twitchaccesstoken.FromData() error = %v, wantErr %v", err, tt.wantErr)
129+
return
130+
}
131+
for i := range got {
132+
if len(got[i].Raw) == 0 {
133+
t.Fatalf("no raw secret present: \n %+v", got[i])
134+
}
135+
if (got[i].VerificationError() != nil) != tt.wantVerificationErr {
136+
t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())
137+
}
138+
}
139+
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "verificationError")
140+
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
141+
t.Errorf("Twitchaccesstoken.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
142+
}
143+
})
144+
}
145+
}
146+
147+
func BenchmarkFromData(benchmark *testing.B) {
148+
ctx := context.Background()
149+
s := Scanner{}
150+
for name, data := range detectors.MustGetBenchmarkData() {
151+
benchmark.Run(name, func(b *testing.B) {
152+
b.ResetTimer()
153+
for n := 0; n < b.N; n++ {
154+
_, err := s.FromData(ctx, false, data)
155+
if err != nil {
156+
b.Fatal(err)
157+
}
158+
}
159+
})
160+
}
161+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package twitchaccesstoken
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/google/go-cmp/cmp"
8+
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
9+
"github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"
10+
)
11+
12+
func TestTwitchaccesstoken_Pattern(t *testing.T) {
13+
d := Scanner{}
14+
ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})
15+
tests := []struct {
16+
name string
17+
input string
18+
want []string
19+
}{
20+
{
21+
name: "typical pattern",
22+
input: "twitchaccesstoken_token = 'abc123def456ghi789jkl012mno345'",
23+
want: []string{"abc123def456ghi789jkl012mno345"},
24+
},
25+
{
26+
name: "env variable pattern",
27+
input: "'twitch_access_token': 'abc123def456ghi789jkl012mno345'",
28+
want: []string{"abc123def456ghi789jkl012mno345"},
29+
},
30+
{
31+
name: "get request pattern",
32+
input: "curl -X GET 'https://id.twitch.tv/oauth2/validate' -H 'Authorization: OAuth xbc123def456ghi789jkl012mno345'",
33+
want: []string{"xbc123def456ghi789jkl012mno345"},
34+
},
35+
{
36+
name: "finds all matches",
37+
input: "twitchaccesstoken_token1 = 'z9y8x7w6v5u4t3s2r1q0p9o8n7m6l5' twitchaccesstoken_token2 = '123abc456def789ghi012jkl345mno'",
38+
want: []string{"z9y8x7w6v5u4t3s2r1q0p9o8n7m6l5", "123abc456def789ghi012jkl345mno"},
39+
},
40+
{
41+
name: "invald pattern",
42+
input: "twitchaccesstoken_token = '1a2b3c4d'",
43+
want: []string{},
44+
},
45+
}
46+
47+
for _, test := range tests {
48+
t.Run(test.name, func(t *testing.T) {
49+
matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input))
50+
if len(matchedDetectors) == 0 {
51+
t.Errorf("keywords '%v' not matched by: %s", d.Keywords(), test.input)
52+
return
53+
}
54+
55+
results, err := d.FromData(context.Background(), false, []byte(test.input))
56+
if err != nil {
57+
t.Errorf("error = %v", err)
58+
return
59+
}
60+
61+
if len(results) != len(test.want) {
62+
if len(results) == 0 {
63+
t.Errorf("did not receive result")
64+
} else {
65+
t.Errorf("expected %d results, only received %d", len(test.want), len(results))
66+
}
67+
return
68+
}
69+
70+
actual := make(map[string]struct{}, len(results))
71+
for _, r := range results {
72+
if len(r.RawV2) > 0 {
73+
actual[string(r.RawV2)] = struct{}{}
74+
} else {
75+
actual[string(r.Raw)] = struct{}{}
76+
}
77+
}
78+
expected := make(map[string]struct{}, len(test.want))
79+
for _, v := range test.want {
80+
expected[v] = struct{}{}
81+
}
82+
83+
if diff := cmp.Diff(expected, actual); diff != "" {
84+
t.Errorf("%s diff: (-want +got)\n%s", test.name, diff)
85+
}
86+
})
87+
}
88+
}

pkg/engine/defaults/defaults.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,7 @@ import (
739739
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twilio"
740740
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twist"
741741
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitch"
742+
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitchaccesstoken"
742743
twitterv1 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitter/v1"
743744
twitterv2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitter/v2"
744745
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitterconsumerkey"
@@ -1583,6 +1584,7 @@ func buildDetectorList() []detectors.Detector {
15831584
&twilio.Scanner{},
15841585
&twist.Scanner{},
15851586
&twitch.Scanner{},
1587+
&twitchaccesstoken.Scanner{},
15861588
&twitterconsumerkey.Scanner{},
15871589
&twitterv1.Scanner{},
15881590
&twitterv2.Scanner{},

0 commit comments

Comments
 (0)