Skip to content

Find, verify, and analyze leaked credentials

4.6 KB
Raw Blame
package slackwebhook

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

	"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
	"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
	regexp "github.com/wasilibs/go-re2"
)

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

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

var (
	defaultClient = detectors.DetectorHttpClientWithNoLocalAddresses
	// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.
	keyPats = map[string]*regexp.Regexp{
		"Slack Service Web Hook":   regexp.MustCompile(`(https://hooks\.slack\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]{23,25})`),
		"Slack Workflow Web Hook ": regexp.MustCompile(`(https://hooks\.slack\.com/workflows/T[A-Z0-9]+/A[A-Z0-9]+/[0-9]{17,19}/[A-Za-z0-9]{23,25})`),
	}
)

// 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{"hooks.slack.com"}
}

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

	for _, keyPat := range keyPats {
		matches := keyPat.FindAllStringSubmatch(dataStr, -1)

		for _, match := range matches {
			resMatch := strings.TrimSpace(match[1])

			s1 := detectors.Result{
				DetectorType: detector_typepb.DetectorType_SlackWebhook,
				Raw:          []byte(resMatch),
				SecretParts:  map[string]string{"key": resMatch},
			}
			s1.ExtraData = map[string]string{
				"rotation_guide": "https://howtorotate.com/docs/tutorials/slack-webhook/",
			}

			if verify {

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

				isVerified, verificationErr := verifyMatch(ctx, client, resMatch)
				s1.Verified = isVerified
				s1.SetVerificationError(verificationErr, resMatch)
			}

			results = append(results, s1)
		}
	}

	return results, nil
}

func verifyMatch(ctx context.Context, client *http.Client, resMatch string) (bool, error) {
	// We don't want to actually send anything to webhooks we find. To verify them without spamming them, we
	// send an intentionally malformed message and look for a particular expected error message.
	payload := strings.NewReader(`intentionally malformed JSON from TruffleHog scan`)
	req, err := http.NewRequestWithContext(ctx, "POST", resMatch, payload)
	if err != nil {
		return false, err
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		return false, err
	}
	defer func() { _ = res.Body.Close() }()

	bodyBytes, err := io.ReadAll(res.Body)
	if err != nil {
		return false, err
	}

	switch {
	case res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusMultipleChoices:
		// Hopefully this never happens - it means we actually sent something to a channel somewhere. But
		// we at least know the secret is verified.
		return true, nil
	case res.StatusCode == http.StatusBadRequest && bytes.Equal(bodyBytes, []byte("invalid_payload")):
		return true, nil
	case res.StatusCode == http.StatusBadRequest && bytes.Contains(bodyBytes, []byte("invalid_token")):
		// Slack may return the bare error code or embed it in a longer body, hence Contains not Equal.
		// Revoked webhook / gone workspace or channel is determinate verified=false.
		return false, nil
	case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusForbidden:
		// Not a real webhook or the owning app's OAuth token has been revoked or the app has been deleted
		// You might want to handle this case or log it.
		return false, nil
	default:
		return false, fmt.Errorf("unexpected HTTP response status %d: %s", res.StatusCode, bodyBytes)
	}
}

func (s Scanner) Type() detector_typepb.DetectorType {
	return detector_typepb.DetectorType_SlackWebhook
}

func (s Scanner) Description() string {
	return "Slack webhooks are used to send messages from external sources into Slack channels. If compromised, they can be used to send unauthorized messages."
}

func (s Scanner) IsFalsePositive(result detectors.Result) (bool, string) {
	// ignore "https:" as a false positive for slack webhook detector
	if strings.Contains(string(result.Raw), "https:") {
		return false, ""
	}

	// back to the default false positive checks
	return detectors.IsKnownFalsePositive(string(result.Raw), detectors.DefaultFalsePositives, true)

}