-
Notifications
You must be signed in to change notification settings - Fork 1.8k
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
feat [detector]: added hasura detector #3427
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
package hasura | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
"strings" | ||
|
||
regexp "github.com/wasilibs/go-re2" | ||
|
||
"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 = detectors.DetectorHttpClientWithNoLocalAddresses | ||
// Make sure that your group is surrounded in boundary characters such as below to reduce false positives. | ||
domainPat = regexp.MustCompile(`\b([a-zA-Z0-9-]+\.hasura\.app)\b`) | ||
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"hasura"}) + `\b([a-zA-Z0-9]{64})\b`) | ||
) | ||
|
||
// 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{"hasura"} | ||
} | ||
|
||
// FromData will find and optionally verify Hasura 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) | ||
|
||
keyMatches := keyPat.FindAllStringSubmatch(dataStr, -1) | ||
domainMatches := domainPat.FindAllStringSubmatch(dataStr, -1) | ||
|
||
for _, match := range keyMatches { | ||
if len(match) != 2 { | ||
continue | ||
} | ||
key := strings.TrimSpace(match[1]) | ||
|
||
for _, domainMatch := range domainMatches { | ||
if len(domainMatch) != 2 { | ||
continue | ||
} | ||
|
||
domainRes := strings.TrimSpace(domainMatch[1]) | ||
|
||
s1 := detectors.Result{ | ||
DetectorType: detectorspb.DetectorType_Hasura, | ||
Raw: []byte(key), | ||
RawV2: []byte(fmt.Sprintf("%s:%s", domainRes, key)), | ||
} | ||
|
||
if verify { | ||
client := s.client | ||
if client == nil { | ||
client = defaultClient | ||
} | ||
|
||
data := []byte(`{"query":"query { __schema { types { name } } }"}`) | ||
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("https://%s/v1/graphql", domainRes), strings.NewReader(string(data))) | ||
if err != nil { | ||
continue | ||
} | ||
req.Header.Add("Content-Type", "application/json") | ||
req.Header.Add("x-hasura-admin-secret", key) | ||
res, err := client.Do(req) | ||
if err != nil { | ||
s1.SetVerificationError(err, key) | ||
results = append(results, s1) | ||
continue | ||
} | ||
defer res.Body.Close() | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Verify should be a separate function to mitigate issues with defer inside a for loop. |
||
body, err := ioutil.ReadAll(res.Body) | ||
if err != nil { | ||
s1.SetVerificationError(err, key) | ||
results = append(results, s1) | ||
continue | ||
} | ||
|
||
var response struct { | ||
Errors []interface{} `json:"errors"` | ||
} | ||
|
||
err = json.Unmarshal(body, &response) | ||
if err != nil { | ||
s1.SetVerificationError(err, key) | ||
results = append(results, s1) | ||
continue | ||
} | ||
|
||
if res.StatusCode >= 200 && res.StatusCode < 300 && len(response.Errors) == 0 { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Status code check should be specific. Ranges are error-prone. |
||
s1.Verified = true | ||
} else { | ||
if len(response.Errors) > 0 { | ||
err = fmt.Errorf("GraphQL query returned errors") | ||
} else { | ||
err = fmt.Errorf("unexpected HTTP response status %d", res.StatusCode) | ||
} | ||
s1.SetVerificationError(err, key) | ||
} | ||
} | ||
|
||
results = append(results, s1) | ||
} | ||
} | ||
|
||
return results, nil | ||
} | ||
|
||
func (s Scanner) Type() detectorspb.DetectorType { | ||
return detectorspb.DetectorType_Hasura | ||
} | ||
|
||
func (s Scanner) Description() string { | ||
return "Hasura is an open source engine that provides instant GraphQL APIs over PostgreSQL. Hasura admin secrets can be used to access and manage Hasura projects." | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
//go:build detectors | ||
// +build detectors | ||
|
||
package hasura | ||
|
||
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 TestHasura_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) | ||
} | ||
secret := testSecrets.MustGetField("HASURA") | ||
inactiveSecret := testSecrets.MustGetField("HASURA_INACTIVE") | ||
domain := testSecrets.MustGetField("HASURA_DOMAIN") | ||
|
||
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, verified", | ||
s: Scanner{}, | ||
args: args{ | ||
ctx: context.Background(), | ||
data: []byte(fmt.Sprintf("You can find a hasura secret %s within hasura domain %s", secret, domain)), | ||
verify: true, | ||
}, | ||
want: []detectors.Result{ | ||
{ | ||
DetectorType: detectorspb.DetectorType_Hasura, | ||
Verified: true, | ||
}, | ||
}, | ||
wantErr: false, | ||
wantVerificationErr: false, | ||
}, | ||
{ | ||
name: "found, unverified", | ||
s: Scanner{}, | ||
args: args{ | ||
ctx: context.Background(), | ||
data: []byte(fmt.Sprintf("You can find a hasura secret %s within hasura domain %s but not valid", inactiveSecret, domain)), | ||
verify: true, | ||
}, | ||
want: []detectors.Result{ | ||
{ | ||
DetectorType: detectorspb.DetectorType_Hasura, | ||
Verified: false, | ||
}, | ||
}, | ||
wantErr: false, | ||
wantVerificationErr: true, | ||
}, | ||
{ | ||
name: "not found", | ||
s: Scanner{}, | ||
args: args{ | ||
ctx: context.Background(), | ||
data: []byte("You cannot find the secret within"), | ||
verify: true, | ||
}, | ||
want: nil, | ||
wantErr: false, | ||
wantVerificationErr: false, | ||
}, | ||
{ | ||
name: "found, would be verified if not for timeout", | ||
s: Scanner{client: common.SaneHttpClientTimeOut(1 * time.Microsecond)}, | ||
args: args{ | ||
ctx: context.Background(), | ||
data: []byte(fmt.Sprintf("You can find a hasura secret %s within %s", secret, domain)), | ||
verify: true, | ||
}, | ||
want: []detectors.Result{ | ||
{ | ||
DetectorType: detectorspb.DetectorType_Hasura, | ||
Verified: false, | ||
}, | ||
}, | ||
wantErr: false, | ||
wantVerificationErr: true, | ||
}, | ||
{ | ||
name: "found, verified but unexpected api surface", | ||
s: Scanner{client: common.ConstantResponseHttpClient(404, "")}, | ||
args: args{ | ||
ctx: context.Background(), | ||
data: []byte(fmt.Sprintf("You can find a hasura secret %s within %s", secret, domain)), | ||
verify: true, | ||
}, | ||
want: []detectors.Result{ | ||
{ | ||
DetectorType: detectorspb.DetectorType_Hasura, | ||
Verified: false, | ||
}, | ||
}, | ||
wantErr: false, | ||
wantVerificationErr: true, | ||
}, | ||
} | ||
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("Hasura.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()) | ||
} | ||
} | ||
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "verificationError") | ||
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" { | ||
t.Errorf("Hasura.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) | ||
} | ||
} | ||
}) | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would base your implementation on the Alchemy example. This line
len(match) != 2
,strings.TrimSpace
, etc. are old practices that aren't ideal. https://github.com/trufflesecurity/trufflehog/blob/main/pkg/detectors/alchemy/alchemy.goI'd recommend using the steps linked in CONTRIBUTING.md, as it will generate a detector that has solid logic + integration and unit tests.
https://github.com/trufflesecurity/trufflehog/blob/main/CONTRIBUTING.md#adding-new-secret-detectors
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did use that only, which gave me this logic
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, that doesn't make sense. The code in Alchemy is completely different from this, it was changed at least several months ago. 🤔
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah, my bad, I changed the logic from some other detector though, was just talking about the generation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Upon talking with Zach, I got to know that we are deprioritising adding a new detector code as it doesn't qualify for Hacktoberfest