Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ var (
errNoHost = errors.New("no such host")
)


func (Scanner) CloudEndpoint() string { return "" }

// Keywords are used for efficiently pre-filtering chunks.
Expand Down
211 changes: 211 additions & 0 deletions pkg/detectors/artifactory/basicauth/artifactorybasicauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
package artifactory

import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"

regexp "github.com/wasilibs/go-re2"

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

type Scanner struct {
client *http.Client
detectors.DefaultMultiPartCredentialProvider
}

type basicArtifactoryCredential struct {
username string
password string
host string
raw string
}

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

defaultClient = detectors.DetectorHttpClientWithNoLocalAddresses

basicAuthURLPattern = regexp.MustCompile(
`(?P<username>[^:@\s\/]+):(?P<password>[^:@\s\/]+)@(?P<host>[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]\.jfrog\.io)(?P<path>/[^\s"'<>]*)?`,
)

invalidHosts = simple.NewCache[struct{}]()

errNoHost = errors.New("no such host")
)


// 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{"artifactory", "jfrog.io"}
}

func (s Scanner) getClient() *http.Client {
if s.client != nil {
return s.client
}
return defaultClient
}

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

// ----------------------------------------
// Basic Auth URI detection & verification
// ----------------------------------------
basicCreds := make(map[string]basicArtifactoryCredential)

for _, match := range basicAuthURLPattern.FindAllStringSubmatch(dataStr, -1) {
if len(match) == 0 {
continue
}
subexpNames := basicAuthURLPattern.SubexpNames()

var username, password, host string
for i, name := range subexpNames {
if i == 0 || name == "" {
continue
}
switch name {
case "username":
username = match[i]
case "password":
password = match[i]
case "host":
host = match[i]
}
}

if username == "" || password == "" || host == "" {
continue
}

key := username + ":" + password + "@" + host
if _, exists := basicCreds[key]; exists {
continue
}

basicCreds[key] = basicArtifactoryCredential{
username: username,
password: password,
host: host,
raw: match[0],
}
}

for _, cred := range basicCreds {
if invalidHosts.Exists(cred.host) {
continue
}

r := detectors.Result{
DetectorType: detectorspb.DetectorType_ArtifactoryBasicAuth,
Raw: []byte(cred.raw),
RawV2: []byte(cred.username + ":" + cred.password + "@" + cred.host),
}

if verify {
isVerified, vErr := verifyArtifactoryBasicAuth(ctx, s.getClient(), cred.host, cred.username, cred.password)
r.Verified = isVerified

if vErr != nil {
if errors.Is(vErr, errNoHost) {
invalidHosts.Set(cred.host, struct{}{})
continue
}
r.SetVerificationError(vErr, cred.username, cred.password)
}

if isVerified {
if r.AnalysisInfo == nil {
r.AnalysisInfo = make(map[string]string)
}
r.AnalysisInfo["domain"] = cred.host
r.AnalysisInfo["username"] = cred.username
r.AnalysisInfo["password"] = cred.password
r.AnalysisInfo["authType"] = "basic"
}
}

results = append(results, r)
}

return results, nil
}

func (s Scanner) IsFalsePositive(_ detectors.Result) (bool, string) {
return false, ""
}

func verifyArtifactoryBasicAuth(ctx context.Context, client *http.Client, host, username, password string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+host+"/artifactory/api/system/ping", nil)
if err != nil {
return false, err
}

// Use HTTP Basic authentication with the parsed username and password.
req.SetBasicAuth(username, password)

resp, err := client.Do(req)
if err != nil {
if strings.Contains(err.Error(), "no such host") {
return false, errNoHost
}

return false, err
}

defer func() {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}()

switch resp.StatusCode {
case http.StatusOK:
body, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}

if strings.TrimSpace(string(body)) == "OK" {
return true, nil
}

return false, nil
case http.StatusForbidden:
body, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}

// Ignore rate-limit / temporary block 403s
if strings.Contains(strings.ToLower(string(body)), "blocked due to recurrent request failures") {
return false, nil
}

return true, nil
case http.StatusUnauthorized, http.StatusFound:
return false, nil
default:
return false, fmt.Errorf("unexpected HTTP response status %d", resp.StatusCode)
}
}

func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_ArtifactoryBasicAuth
}

func (s Scanner) Description() string {
return "Artifactory is a repository manager that supports all major package formats. Artifactory Basic Auth credentials can be used to authenticate and perform operations on repositories."
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
//go:build detectors
// +build detectors

package artifactory

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

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"

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

func TestArtifactory_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)
}
basicAuthValid := testSecrets.MustGetField("ARTIFACTORY_BASIC_AUTH_VALID")
basicAuthInactive := testSecrets.MustGetField("ARTIFACTORY_BASIC_AUTH_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 an Artifactory basic auth URL https://%s/artifactory/api/pypi/pypi/simple",
basicAuthValid,
)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_ArtifactoryBasicAuth,
Verified: true,
},
},
wantErr: false,
},
{
name: "found, unverified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf(
"You can find an Artifactory basic auth URL https://%s/artifactory/api/pypi/pypi/simple but it's not valid",
basicAuthInactive,
)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_ArtifactoryBasicAuth,
Verified: false,
},
},
wantErr: false,
},
{
name: "not found",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("You cannot find any Artifactory basic auth URL within this chunk"),
verify: true,
},
want: nil,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("Artifactory.FromData() error = %v, wantErr %v", err, tt.wantErr)
return
}

if len(tt.want) == 0 {
if len(got) != 0 {
t.Fatalf("expected no results, got %d", len(got))
}
return
}

for i := range got {
if len(got[i].Raw) == 0 && len(got[i].RawV2) == 0 {
t.Fatalf("no raw secret present: \n %+v", got[i])
}
gotErr := ""
if got[i].VerificationError() != nil {
gotErr = got[i].VerificationError().Error()
}
wantErr := ""
if tt.want[i].VerificationError() != nil {
wantErr = tt.want[i].VerificationError().Error()
}
if gotErr != wantErr {
t.Fatalf("wantVerificationError = %v, verification error = %v",
tt.want[i].VerificationError(), got[i].VerificationError())
}
}
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "verificationError", "primarySecret")
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
t.Errorf("Artifactory.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) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_, err := s.FromData(ctx, false, data)
if err != nil {
b.Fatal(err)
}
}
})
}
}
Loading