Skip to content

Commit c3e668f

Browse files
feat: bing subscription key support (#4092)
Co-authored-by: Kashif Khan <[email protected]>
1 parent f6632d0 commit c3e668f

File tree

6 files changed

+348
-7
lines changed

6 files changed

+348
-7
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package bingsubscriptionkey
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+
var _ detectors.Detector = (*Scanner)(nil)
21+
22+
var (
23+
defaultClient = common.SaneHttpClient()
24+
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"bing"}) + `\b([a-fA-F0-9]{32})\b`)
25+
)
26+
27+
func (s Scanner) Keywords() []string {
28+
return []string{"bing"}
29+
}
30+
31+
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
32+
dataStr := string(data)
33+
34+
uniqueMatches := make(map[string]struct{})
35+
for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {
36+
uniqueMatches[match[1]] = struct{}{}
37+
}
38+
39+
for match := range uniqueMatches {
40+
s1 := detectors.Result{
41+
DetectorType: detectorspb.DetectorType_BingSubscriptionKey,
42+
Raw: []byte(match),
43+
}
44+
45+
if verify {
46+
client := s.client
47+
if client == nil {
48+
client = defaultClient
49+
}
50+
51+
isVerified, verificationErr := verifyMatch(ctx, client, match)
52+
s1.Verified = isVerified
53+
s1.SetVerificationError(verificationErr, match)
54+
}
55+
56+
results = append(results, s1)
57+
}
58+
59+
return
60+
}
61+
62+
func verifyMatch(ctx context.Context, client *http.Client, subscriptionKey string) (bool, error) {
63+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.bing.microsoft.com/v7.0/search?q=trufflehog", nil)
64+
if err != nil {
65+
return false, nil
66+
}
67+
68+
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
69+
70+
res, err := client.Do(req)
71+
if err != nil {
72+
return false, err
73+
}
74+
defer func() {
75+
_, _ = io.Copy(io.Discard, res.Body)
76+
_ = res.Body.Close()
77+
}()
78+
79+
switch res.StatusCode {
80+
case http.StatusOK:
81+
return true, nil
82+
case http.StatusUnauthorized:
83+
return false, nil
84+
default:
85+
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
86+
}
87+
}
88+
89+
func (s Scanner) Type() detectorspb.DetectorType {
90+
return detectorspb.DetectorType_BingSubscriptionKey
91+
}
92+
93+
func (s Scanner) Description() string {
94+
return "Bing Subscription Key is a key used to access the Bing Web Search API."
95+
}
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 bingsubscriptionkey
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 TestBingsubscriptionkey_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("BING_SUBSCRIPTION_KEY")
28+
inactiveSecret := testSecrets.MustGetField("BING_SUBSCRIPTION_KEY_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 bing subscription key %s within", secret)),
49+
verify: true,
50+
},
51+
want: []detectors.Result{
52+
{
53+
DetectorType: detectorspb.DetectorType_BingSubscriptionKey,
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 bing subscription key %s within but not valid", inactiveSecret)),
66+
verify: true,
67+
},
68+
want: []detectors.Result{
69+
{
70+
DetectorType: detectorspb.DetectorType_BingSubscriptionKey,
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 key 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 bing subscription key %s within", secret)),
95+
verify: true,
96+
},
97+
want: []detectors.Result{
98+
{
99+
DetectorType: detectorspb.DetectorType_BingSubscriptionKey,
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 bing subscription key %s within", secret)),
112+
verify: true,
113+
},
114+
want: []detectors.Result{
115+
{
116+
DetectorType: detectorspb.DetectorType_BingSubscriptionKey,
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("Bingsubscriptionkey.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("Bingsubscriptionkey.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: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package bingsubscriptionkey
2+
3+
import (
4+
"context"
5+
"github.com/google/go-cmp/cmp"
6+
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
7+
"github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"
8+
"testing"
9+
)
10+
11+
func TestBingsubscriptionkey_Pattern(t *testing.T) {
12+
d := Scanner{}
13+
ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})
14+
tests := []struct {
15+
name string
16+
input string
17+
want []string
18+
}{
19+
{
20+
name: "typical pattern",
21+
input: "bing_subscription_key=89017d414ed64edb9c776d4a52102b9a",
22+
want: []string{"89017d414ed64edb9c776d4a52102b9a"},
23+
},
24+
{
25+
name: "finds all matches",
26+
input: `bing_subscription_key1=89017d414ed64edb9c776d4a52102b9b'
27+
bing_subscription_key2=89017d414ed64edb9c776d4a52102b9c`,
28+
want: []string{"89017d414ed64edb9c776d4a52102b9b", "89017d414ed64edb9c776d4a52102b9c"},
29+
},
30+
{
31+
name: "invalid pattern",
32+
input: "bing_subscription_key=89017d414ed64edb9c776d4a52102b9",
33+
want: []string{},
34+
},
35+
}
36+
37+
for _, test := range tests {
38+
t.Run(test.name, func(t *testing.T) {
39+
matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input))
40+
if len(matchedDetectors) == 0 {
41+
t.Errorf("keywords '%v' not matched by: %s", d.Keywords(), test.input)
42+
return
43+
}
44+
45+
results, err := d.FromData(context.Background(), false, []byte(test.input))
46+
if err != nil {
47+
t.Errorf("error = %v", err)
48+
return
49+
}
50+
51+
if len(results) != len(test.want) {
52+
if len(results) == 0 {
53+
t.Errorf("did not receive result")
54+
} else {
55+
t.Errorf("expected %d results, only received %d", len(test.want), len(results))
56+
}
57+
return
58+
}
59+
60+
actual := make(map[string]struct{}, len(results))
61+
for _, r := range results {
62+
if len(r.RawV2) > 0 {
63+
actual[string(r.RawV2)] = struct{}{}
64+
} else {
65+
actual[string(r.Raw)] = struct{}{}
66+
}
67+
}
68+
expected := make(map[string]struct{}, len(test.want))
69+
for _, v := range test.want {
70+
expected[v] = struct{}{}
71+
}
72+
73+
if diff := cmp.Diff(expected, actual); diff != "" {
74+
t.Errorf("%s diff: (-want +got)\n%s", test.name, diff)
75+
}
76+
})
77+
}
78+
}

pkg/engine/defaults/defaults.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ import (
8888
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/besttime"
8989
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/betterstack"
9090
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/billomat"
91+
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bingsubscriptionkey"
9192
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bitbar"
9293
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bitcoinaverage"
9394
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bitfinex"
@@ -929,6 +930,7 @@ func buildDetectorList() []detectors.Detector {
929930
&besttime.Scanner{},
930931
&betterstack.Scanner{},
931932
&billomat.Scanner{},
933+
&bingsubscriptionkey.Scanner{},
932934
&bitbar.Scanner{},
933935
&bitcoinaverage.Scanner{},
934936
&bitfinex.Scanner{},

0 commit comments

Comments
 (0)