Skip to content
Changes

Reference

sonarqube · Oct 16, 2026

What this change means

Atlas added sonarqube to its detector catalog in this update.

pkg/detectors/sonarqube/sonarqube.go+185−0View file
@@ -0,0 +1,185 @@
1added: package sonarqube
2added:
3added: import (
4added: "context"
5added: "encoding/json"
6added: "errors"
7added: "fmt"
8added: "io"
9added: "net/http"
10added: "slices"
11added: "strings"
12added:
13added: regexp "github.com/wasilibs/go-re2"
14added:
15added: "github.com/trufflesecurity/trufflehog/v3/pkg/common"
16added: "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
17added: "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
18added: "github.com/trufflesecurity/trufflehog/v3/pkg/ssrf"
19added: )
20added:
21added: // Scanner finds SonarQube Server tokens: user (squ_), global analysis (sqa_)
22added: // and project analysis (sqp_). A token has no host in it, so it is verified
23added: // against endpoints the user configured and hosts found in the scanned data
24added: // (see findEndpoints).
25added: type Scanner struct {
26added: detectors.DefaultMultiPartCredentialProvider
27added: detectors.EndpointSetter
28added: client *http.Client
29added: }
30added:
31added: // Ensure the Scanner satisfies the interface at compile time.
32added: var _ detectors.Detector = (*Scanner)(nil)
33added: var _ detectors.EndpointCustomizer = (*Scanner)(nil)
34added:
35added: // There is no public SonarQube Server, so there is no cloud endpoint.
36added: func (Scanner) CloudEndpoint() string { return "" }
37added:
38added: var (
39added: defaultClient = common.SaneHttpClient()
40added: keyPat = regexp.MustCompile(`\b(sq[apu]_[0-9a-f]{40})\b`)
41added:
42added: // Host after a sonar config key, any port, for example
43added: // sonar.host.url=https://sonar.example.com or SONAR_HOST_URL: sonar.example.com:8080
44added: hostURLPat = regexp.MustCompile(`(?i)\bsonar[._](?:host[._]url|host|url)\b["'\s:=,>]*((?:https?://)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?)`)
45added: )
46added:
47added: // Keywords are used for efficiently pre-filtering chunks.
48added: func (s Scanner) Keywords() []string {
49added: return []string{"squ_", "sqa_", "sqp_"}
50added: }
51added:
52added: // findEndpoints returns the hosts in the data named by a sonar config key,
53added: // each one once.
54added: func findEndpoints(data string) []string {
55added: var endpoints []string
56added: seen := make(map[string]struct{})
57added: for _, match := range hostURLPat.FindAllStringSubmatch(data, -1) {
58added: if _, ok := seen[match[1]]; !ok {
59added: seen[match[1]] = struct{}{}
60added: endpoints = append(endpoints, match[1])
61added: }
62added: }
63added: return endpoints
64added: }
65added:
66added: // FromData will find and optionally verify SonarQube secrets in a given set of bytes.
67added: func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
68added: uniqueMatches := make(map[string]struct{})
69added: for _, match := range keyPat.FindAllStringSubmatch(string(data), -1) {
70added: uniqueMatches[match[1]] = struct{}{}
71added: }
72added:
73added: configured := s.Endpoints()
74added: endpoints := s.Endpoints(findEndpoints(string(data))...)
75added:
76added: for match := range uniqueMatches {
77added: result := detectors.Result{
78added: DetectorType: detector_typepb.DetectorType_SonarQube,
79added: Raw: []byte(match),
80added: SecretParts: map[string]string{"key": match},
81added: }
82added:
83added: // nowhere to verify, tell the user how to fix that
84added: if len(endpoints) == 0 {
85added: result.ExtraData = map[string]string{
86added: "message": "No SonarQube Server URL was found or configured. To verify this token, set the server URL as a custom endpoint, e.g. --verifier SonarQube=https://sonar.example.com",
87added: }
88added: }
89added:
90added: if verify {
91added: // try each endpoint, stop at the first one that accepts the token
92added: var verifyErr error
93added: for _, endpoint := range endpoints {
94added: // Hosts found in scanned data are not trusted, so they get a client
95added: // that refuses local and private addresses.
96added: client := s.client
97added: if client == nil {
98added: client = s.VerificationClient(defaultClient)
99added: if !slices.Contains(configured, endpoint) {
100added: client = detectors.DetectorHttpClientWithNoLocalAddresses
101added: }
102added: }
103added:
104added: isVerified, extraData, err := verifyMatch(ctx, client, endpoint, match)
105added: // a found host like localhost is the developer's machine, not ours, skip it
106added: if errors.Is(err, ssrf.ErrEgressBlocked) {
107added: continue
108added: }
109added: if err != nil {
110added: verifyErr = err
111added: continue
112added: }
113added: if isVerified {
114added: result.Verified = true
115added: result.ExtraData = extraData
116added: verifyErr = nil
117added: break
118added: }
119added: }
120added: result.SetVerificationError(verifyErr, match)
121added: }
122added:
123added: results = append(results, result)
124added: }
125added:
126added: return
127added: }
128added:
129added: type currentUserResponse struct {
130added: IsLoggedIn bool `json:"isLoggedIn"`
131added: Login string `json:"login"`
132added: }
133added:
134added: // verifyMatch asks the server who the token belongs to.
135added: // The token goes in the basic auth username with an empty password.
136added: // A wrong token gets a 401. We check isLoggedIn too, because a server
137added: // that allows anonymous access answers 200 for any request.
138added: func verifyMatch(ctx context.Context, client *http.Client, endpoint, token string) (bool, map[string]string, error) {
139added: // users pass "host:9000" or "http://host:9000", default to https
140added: if !strings.Contains(endpoint, "://") {
141added: endpoint = "https://" + endpoint
142added: }
143added: url := strings.TrimRight(endpoint, "/") + "/api/users/current"
144added:
145added: req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
146added: if err != nil {
147added: return false, nil, err
148added: }
149added: req.SetBasicAuth(token, "")
150added: req.Header.Set("Accept", "application/json")
151added:
152added: res, err := client.Do(req)
153added: if err != nil {
154added: return false, nil, err
155added: }
156added: defer func() {
157added: _, _ = io.Copy(io.Discard, res.Body)
158added: _ = res.Body.Close()
159added: }()
160added:
161added: switch res.StatusCode {
162added: case http.StatusOK:
163added: var user currentUserResponse
164added: if err := json.NewDecoder(res.Body).Decode(&user); err != nil {
165added: return false, nil, fmt.Errorf("failed to decode response: %w", err)
166added: }
167added: if !user.IsLoggedIn {
168added: return false, nil, nil
169added: }
170added: return true, map[string]string{"endpoint": endpoint, "login": user.Login}, nil
171added: case http.StatusUnauthorized:
172added: // the token is definitely not valid on this server
173added: return false, nil, nil
174added: default:
175added: return false, nil, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
176added: }
177added: }
178added:
179added: func (s Scanner) Type() detector_typepb.DetectorType {
180added: return detector_typepb.DetectorType_SonarQube
181added: }
182added:
183added: func (s Scanner) Description() string {
184added: return "SonarQube Server is a code quality and security analysis platform. Its user, global analysis and project analysis tokens authenticate people and CI pipelines to the SonarQube API."
185added: }