Skip to content

Commit

Permalink
Add DocuSign detector (#1382)
Browse files Browse the repository at this point in the history
* init

* look for client id and client secret, encode them for basis auth

* add tests

* test without checking the contents of response

* confirm access_token exists

* cleanup test

* explain in code that an undocumented grant_type is used

* remove use of deprecated ioutil, remove dead code, return errors instead of just logging

* directly pull access token

* update error text, remove redundant body close()

* import new detector into defaults
  • Loading branch information
zubairk14 authored Jun 8, 2023
1 parent ce4a1fd commit dfb1a0c
Show file tree
Hide file tree
Showing 5 changed files with 261 additions and 6 deletions.
124 changes: 124 additions & 0 deletions pkg/detectors/docusign/docusign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package docusign

import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/go-errors/errors"
"io"
"net/http"
"regexp"
"strings"

"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)

type Scanner struct{}

type Response struct {
AccessToken string `json:"access_token"`
}

// Ensure the Scanner satisfies the interface at compile time.
var _ detectors.Detector = (*Scanner)(nil)

var (
client = common.SaneHttpClient()

// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.
idPat = regexp.MustCompile(detectors.PrefixRegex([]string{"integration", "id"}) + common.UUIDPattern)
secretPat = regexp.MustCompile(detectors.PrefixRegex([]string{"secret"}) + common.UUIDPattern)
)

// Keywords are used for efficiently pre-filtering chunks.
// Use identifiers in the secret preferably, or the provider name.
func (s Scanner) Keywords() []string {
return []string{"docusign"}
}

// FromData will find and optionally verify Docusign 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)

idMatches := idPat.FindAllStringSubmatch(dataStr, -1)
secretMatches := secretPat.FindAllStringSubmatch(dataStr, -1)

for _, idMatch := range idMatches {
if len(idMatch) != 2 {
continue
}
resIDMatch := strings.TrimSpace(idMatch[1])

for _, secretMatch := range secretMatches {
if len(secretMatch) != 2 {
continue
}
resSecretMatch := strings.TrimSpace(secretMatch[1])

s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_Docusign,
Raw: []byte(resIDMatch),
Redacted: resIDMatch,
RawV2: []byte(resIDMatch + resSecretMatch),
}

// Verify client id and secret pair by using an *undocumented* client_credentials grant type on the oauth2 endpoint.
// If verifier breaks in the future, confirm that the oauth2 endpoint is still accepting the client_credentials grant type.
if verify {
req, err := http.NewRequestWithContext(ctx, "POST", "https://account-d.docusign.com/oauth/token?grant_type=client_credentials", nil)
if err != nil {
continue
}

encodedCredentials := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", resIDMatch, resSecretMatch)))

req.Header.Add("Accept", "application/vnd.docusign+json; version=3")
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCredentials))
res, err := client.Do(req)

if err != nil {
return nil, errors.WrapPrefix(err, "Error making request", 0)
}

// Read the response body
body, err := io.ReadAll(res.Body)

if err != nil {
return nil, errors.WrapPrefix(err, "Error reading response body", 0)
}

// Close the response body
res.Body.Close()

// Parse the response body into a Response struct
var parsedResponse Response
err = json.Unmarshal(body, &parsedResponse)
if err != nil {
return nil, errors.WrapPrefix(err, "Error parsing response", 0)
}

if err == nil {
if res.StatusCode >= 200 && res.StatusCode < 300 && strings.HasPrefix(parsedResponse.AccessToken, "ey") {
s1.Verified = true
} else {
// This function will check false positives for common test words, but also it will make sure the key appears 'random' enough to be a real key.
if detectors.IsKnownFalsePositive(resIDMatch, detectors.DefaultFalsePositives, true) {
continue
}
}
}
}

results = append(results, s1)
}
}

return results, nil
}

func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_Docusign
}
124 changes: 124 additions & 0 deletions pkg/detectors/docusign/docusign_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
//go:build detectors
// +build detectors

package docusign

import (
"context"
"fmt"
"testing"
"time"

"github.com/kylelemons/godebug/pretty"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"

"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)

func TestDocusign_FromChunk(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors5")
if err != nil {
t.Fatalf("could not get test secrets from GCP: %s", err)
}
integrationKey := testSecrets.MustGetField("DOCUSIGN_INTEGRATION_KEY_ACTIVE")
activeSecret := testSecrets.MustGetField("DOCUSIGN_SECRET_ACTIVE")
inactiveSecret := testSecrets.MustGetField("DOCUSIGN_SECRET_INACTIVE")

type args struct {
ctx context.Context
data []byte
verify bool
}
tests := []struct {
name string
s Scanner
args args
want []detectors.Result
wantErr bool
}{
{
name: "found, verified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a docusign id %s and secret %s within", integrationKey, activeSecret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Docusign,
Verified: true,
RawV2: []byte(integrationKey + activeSecret),
Redacted: integrationKey,
},
},
wantErr: false,
},
{
name: "found, unverified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a docusign id %s and secret %s within", integrationKey, inactiveSecret)), // the secret would satisfy the regex but not pass validation
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Docusign,
Verified: false,
RawV2: []byte(integrationKey + inactiveSecret),
Redacted: integrationKey,
},
},
wantErr: false,
},
{
name: "not found",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("You cannot find the secret within"),
verify: true,
},
want: nil,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := Scanner{}
got, err := s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("Docusign.FromData() error = %v, wantErr %v", err, tt.wantErr)
return
}
for i := range got {
if len(got[i].Raw) == 0 {
t.Fatalf("no raw secret present: \n %+v", got[i])
}
got[i].Raw = nil
}
if diff := pretty.Compare(got, tt.want); diff != "" {
t.Errorf("Docusign.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
}
})
}
}

func BenchmarkFromData(benchmark *testing.B) {
ctx := context.Background()
s := Scanner{}
for name, data := range detectors.MustGetBenchmarkData() {
benchmark.Run(name, func(b *testing.B) {
for n := 0; n < b.N; n++ {
_, err := s.FromData(ctx, false, data)
if err != nil {
b.Fatal(err)
}
}
})
}
}
2 changes: 2 additions & 0 deletions pkg/engine/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/dnscheck"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/docparser"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/documo"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/docusign"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/doppler"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/dotmailer"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/dovico"
Expand Down Expand Up @@ -975,6 +976,7 @@ func DefaultDetectors() []detectors.Detector {
&pandadoc.Scanner{},
&juro.Scanner{},
&documo.Scanner{},
&docusign.Scanner{},
&roninapp.Scanner{},
&doppler.Scanner{},
&codacy.Scanner{},
Expand Down
16 changes: 10 additions & 6 deletions pkg/pb/detectorspb/detectors.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions proto/detectors.proto
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,7 @@ enum DetectorType {
NuGetApiKey = 916;
Aiven = 917;
Prefect = 918;
Docusign = 919;
}

message Result {
Expand Down

0 comments on commit dfb1a0c

Please sign in to comment.