Skip to content

Oss 133 new detector vault approle auth for hashicorp #4362

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 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
152 changes: 152 additions & 0 deletions pkg/detectors/hashicorpvaultauth/hashicorpvaultauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package hashicorpvaultauth

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"

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/detectorspb"
)

type Scanner struct {
client *http.Client
}

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

var (
defaultClient = common.SaneHttpClient()

roleIdPat = regexp.MustCompile(detectors.PrefixRegex([]string{"role"}) + `\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b`)

secretIdPat = regexp.MustCompile(detectors.PrefixRegex([]string{"secret"}) + `\b([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\b`)

// Vault URL pattern - HashiCorp Cloud or any HTTPS/HTTP Vault endpoint
vaultUrlPat = regexp.MustCompile(`(https?:\/\/[^\s\/]*\.hashicorp\.cloud(?::\d+)?)(?:\/[^\s]*)?`)
)

// Keywords are used for efficiently pre-filtering chunks.
func (s Scanner) Keywords() []string {
return []string{"hashicorp"}
}

// FromData will find and optionally verify HashiCorp Vault AppRole 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 uniqueRoleIds = make(map[string]struct{})
for _, match := range roleIdPat.FindAllStringSubmatch(dataStr, -1) {
roleId := strings.TrimSpace(match[1])
uniqueRoleIds[roleId] = struct{}{}
}

var uniqueSecretIds = make(map[string]struct{})
for _, match := range secretIdPat.FindAllStringSubmatch(dataStr, -1) {
secretId := strings.TrimSpace(match[1])
uniqueSecretIds[secretId] = struct{}{}
}

var uniqueVaultUrls = make(map[string]struct{})
for _, match := range vaultUrlPat.FindAllString(dataStr, -1) {
url := strings.TrimSpace(match)
uniqueVaultUrls[url] = struct{}{}
}

// If no names or secrets found, return empty results
if len(uniqueRoleIds) == 0 || len(uniqueSecretIds) == 0 || len(uniqueVaultUrls) == 0 {
return results, nil
}

// create combination results that can be verified
for roleId := range uniqueRoleIds {
for secretId := range uniqueSecretIds {
for vaultUrl := range uniqueVaultUrls {
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_HashiCorpVaultAuth,
Raw: []byte(secretId),
RawV2: []byte(fmt.Sprintf("%s:%s", roleId, secretId)),
ExtraData: map[string]string{
"URL": vaultUrl,
},
}

if verify {
client := s.client
if client == nil {
client = defaultClient
}

isVerified, verificationErr := verifyMatch(ctx, client, roleId, secretId, vaultUrl)
s1.Verified = isVerified
s1.SetVerificationError(verificationErr, roleId, secretId, vaultUrl)
}
results = append(results, s1)
}
}
}
return results, nil
}

func verifyMatch(ctx context.Context, client *http.Client, roleId, secretId, vaultUrl string) (bool, error) {
payload := map[string]string{
"role_id": roleId,
"secret_id": secretId,
}

jsonPayload, err := json.Marshal(payload)
if err != nil {
return false, err
}

req, err := http.NewRequestWithContext(ctx, http.MethodPost, vaultUrl+"/v1/auth/approle/login", bytes.NewBuffer(jsonPayload))
if err != nil {
return false, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Vault-Namespace", "admin")

resp, err := client.Do(req)
if err != nil {
return false, err
}

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

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

if strings.Contains(string(body), "invalid role or secret ID") {
return false, nil
} else {
return false, fmt.Errorf("unexpected HTTP response status %d", resp.StatusCode)
}
default:
return false, fmt.Errorf("unexpected HTTP response status %d", resp.StatusCode)
}
}

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

func (s Scanner) Description() string {
return "HashiCorp Vault AppRole authentication method uses role_id and secret_id for machine-to-machine authentication. These credentials can be used to authenticate with Vault and obtain tokens for accessing secrets."
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
//go:build detectors
// +build detectors

package hashicorpvaultauth

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

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"

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

func TestHashiCorpVaultAuth_FromChunk(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors6")
if err != nil {
t.Fatalf("could not get test secrets from GCP: %s", err)
}
roleId := testSecrets.MustGetField("HASHICORPVAULTAUTH_ROLE_ID")
secretId := testSecrets.MustGetField("HASHICORPVAULTAUTH_SECRET_ID")
inactiveRoleId := testSecrets.MustGetField("HASHICORPVAULTAUTH_ROLE_ID_INACTIVE")
inactiveSecretId := testSecrets.MustGetField("HASHICORPVAULTAUTH_SECRET_ID_INACTIVE")
vaultUrl := testSecrets.MustGetField("HASHICORPVAULTAUTH_URL")

type args struct {
ctx context.Context
data []byte
verify bool
}
tests := []struct {
name string
s Scanner
args args
want []detectors.Result
wantErr bool
wantVerificationErr bool
}{
{
name: "found, unverified - complete set with invalid credentials",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("hashicorp config:\nrole_id: %s\nsecret_id: %s\nvault_url: %s", inactiveRoleId, inactiveSecretId, vaultUrl)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_HashiCorpVaultAuth,
Verified: false,
VerificationFromCache: false,
Raw: []byte(inactiveSecretId),
RawV2: []byte(fmt.Sprintf("%s:%s", inactiveRoleId, inactiveSecretId)),
ExtraData: map[string]string{
"URL": vaultUrl,
},
StructuredData: nil,
},
},
wantErr: false,
wantVerificationErr: false,
},
{
name: "found, verified - complete set with valid credentials",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("hashicorp config:\nrole_id: %s\nsecret_id: %s\nvault_url: %s", roleId, secretId, vaultUrl)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_HashiCorpVaultAuth,
Verified: true,
VerificationFromCache: false,
Raw: []byte(secretId),
RawV2: []byte(fmt.Sprintf("%s:%s", roleId, secretId)),
ExtraData: map[string]string{
"URL": vaultUrl,
},
StructuredData: nil,
},
},
wantErr: false,
wantVerificationErr: false,
},
{
name: "found, incomplete set - credentials without vault url",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("vault config:\nrole_id: %s\nsecret_id: %s", roleId, secretId)),
verify: true,
},
want: nil,
wantErr: false,
wantVerificationErr: false,
},
{
name: "found, incomplete set - only role_id",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("vault role_id: %s", roleId)),
verify: true,
},
want: nil,
wantErr: false,
wantVerificationErr: false,
},
{
name: "found, incomplete set - only secret_id",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("vault secret_id: %s", secretId)),
verify: true,
},
want: nil,
wantErr: false,
wantVerificationErr: false,
},
{
name: "not found - no vault context",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("You cannot find the secret within"),
verify: true,
},
want: nil,
wantErr: false,
wantVerificationErr: 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("HashiCorpVaultAuth.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])
}
if (got[i].VerificationError() != nil) != tt.wantVerificationErr {
t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())
}
}
// Fix: Ignore ALL unexported fields using cmpopts.IgnoreUnexported
ignoreOpts := cmpopts.IgnoreUnexported(detectors.Result{})
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
t.Errorf("HashiCorpVaultAuth.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