Skip to content

Commit cce1764

Browse files
authored
chore(go): introduce gosec linter (#4501)
1 parent 49ab3f3 commit cce1764

File tree

22 files changed

+66
-68
lines changed

22 files changed

+66
-68
lines changed

.golangci.yaml

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ linters:
1717
#- gocyclo
1818
#- godot
1919
- gofumpt
20-
#- gosec
20+
- gosec
2121
- gosimple
2222
- govet
2323
- ineffassign
@@ -85,6 +85,12 @@ linters-settings:
8585
- style
8686
gofumpt:
8787
extra-rules: true
88+
gosec:
89+
excludes:
90+
- G110
91+
- G115
92+
- G204
93+
- G306
8894
lll:
8995
line-length: 150
9096

cmd/gitops-server/cmd/cmd.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -293,8 +293,9 @@ func runCmd(cmd *cobra.Command, args []string) error {
293293

294294
addr := net.JoinHostPort(options.Host, options.Port)
295295
srv := &http.Server{
296-
Addr: addr,
297-
Handler: handler,
296+
Addr: addr,
297+
Handler: handler,
298+
ReadHeaderTimeout: 5 * time.Second,
298299
}
299300

300301
go func() {
@@ -318,8 +319,9 @@ func runCmd(cmd *cobra.Command, args []string) error {
318319
metricsMux.Handle("/metrics", promhttp.HandlerFor(gatherers, promhttp.HandlerOpts{}))
319320

320321
metricsServer = &http.Server{
321-
Addr: options.MetricsAddress,
322-
Handler: metricsMux,
322+
Addr: options.MetricsAddress,
323+
Handler: metricsMux,
324+
ReadHeaderTimeout: 5 * time.Second,
323325
}
324326

325327
go func() {
@@ -375,6 +377,7 @@ func listenAndServe(log logr.Logger, srv *http.Server, options Options) error {
375377
srv.TLSConfig = &tls.Config{
376378
ClientCAs: caCertPool,
377379
ClientAuth: tls.RequireAndVerifyClientCert,
380+
MinVersion: tls.VersionTLS12,
378381
}
379382
} else {
380383
log.Info("Using TLS", "cert_file", options.TLSCertFile, "key_file", options.TLSKeyFile)

cmd/gitops/root/cmd.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ package root
33
import (
44
"fmt"
55
"log"
6+
"math/rand/v2"
67
"os"
78
"strings"
8-
"time"
99

1010
"github.com/manifoldco/promptui"
1111
"github.com/spf13/cobra"
@@ -121,10 +121,8 @@ func RootCmd() *cobra.Command {
121121
enableAnalytics = true
122122
}
123123

124-
seed := time.Now().UnixNano()
125-
126124
gitopsConfig = &config.GitopsCLIConfig{
127-
UserID: config.GenerateUserID(10, seed),
125+
UserID: config.GenerateUserID(10, rand.Uint64()), // #nosec G404
128126
Analytics: enableAnalytics,
129127
}
130128

cmd/gitops/set/config/cmd.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ package config
22

33
import (
44
"fmt"
5+
"math/rand/v2"
56
"os"
67
"strconv"
78
"strings"
8-
"time"
99

1010
"github.com/spf13/cobra"
1111

@@ -77,9 +77,7 @@ func setConfigCommandRunE(opts *cfg.Options) func(*cobra.Command, []string) erro
7777
gitopsConfig.Analytics = analyticsValue
7878

7979
if gitopsConfig.UserID == "" {
80-
seed := time.Now().UnixNano()
81-
82-
gitopsConfig.UserID = config.GenerateUserID(10, seed)
80+
gitopsConfig.UserID = config.GenerateUserID(10, rand.Uint64()) // #nosec G404
8381
}
8482

8583
log.Actionf("Saving GitOps CLI config ...")

core/server/inventory.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -479,7 +479,7 @@ func parseInventoryFromUnstructured(obj *unstructured.Unstructured) ([]*unstruct
479479
return objects, nil
480480
}
481481

482-
const helmSecretNameFmt = "sh.helm.release.v1.%s.v%v"
482+
const helmSecretNameFmt = "sh.helm.release.v1.%s.v%v" // #nosec G101
483483

484484
func secretNameFromHelmRelease(helmRelease *helmv2.HelmRelease) *client.ObjectKey {
485485
if latest := helmRelease.Status.History.Latest(); latest != nil {

pkg/analytics/analytics.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ const (
2626
app = "cli"
2727
analyticsType = "track"
2828
trackEventURL = "https://app.pendo.io/data/track"
29-
trackEventSecret = "bf6ab33e-cd70-46e7-4b77-279f54cac447"
29+
trackEventSecret = "bf6ab33e-cd70-46e7-4b77-279f54cac447" // #nosec G101
3030
)
3131

3232
type analyticsRequestBody struct {

pkg/config/config.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"fmt"
77
"io"
88
"io/fs"
9-
"math/rand"
9+
"math/rand/v2"
1010
"os"
1111
"path/filepath"
1212
)
@@ -188,12 +188,12 @@ func parseConfig(data []byte, config *GitopsCLIConfig) error {
188188
}
189189

190190
// GenerateUserID generates a string of specified length made of random characters and encodes it in base64 format
191-
func GenerateUserID(numChars int, seed int64) string {
192-
srand := rand.New(rand.NewSource(seed))
191+
func GenerateUserID(numChars int, seed uint64) string {
192+
srand := rand.New(rand.NewPCG(seed, 0)) // #nosec G404
193193

194194
b := make([]byte, numChars)
195195
for i := range b {
196-
b[i] = letters[srand.Intn(len(letters))]
196+
b[i] = letters[srand.IntN(len(letters))]
197197
}
198198

199199
return string(b)

pkg/config/config_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,6 @@ var _ = Describe("GenerateUserID", func() {
2525
It("generates user ID", func() {
2626
userID := GenerateUserID(10, 1024)
2727

28-
Expect(userID).To(Equal("2Q2MsgBDSV"))
28+
Expect(userID).To(Equal("ULhi8C5Ti1"))
2929
})
3030
})

pkg/http/server.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net"
99
"net/http"
1010
"sync"
11+
"time"
1112
)
1213

1314
// MultiServer lets you create and run an HTTP server that serves over both, HTTP and HTTPS. It is a convenience wrapper around net/http and crypto/tls.
@@ -59,7 +60,7 @@ func createTLSListener(port int, certFile, keyFile string) (net.Listener, error)
5960
return nil, fmt.Errorf("unable to load TLS key pair: %w", err)
6061
}
6162

62-
listener, err := tls.Listen("tcp", fmt.Sprintf(":%d", port), &tls.Config{Certificates: []tls.Certificate{cert}})
63+
listener, err := tls.Listen("tcp", fmt.Sprintf(":%d", port), &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12})
6364
if err != nil {
6465
return nil, fmt.Errorf("unable to start TLS listener: %w", err)
6566
}
@@ -69,8 +70,9 @@ func createTLSListener(port int, certFile, keyFile string) (net.Listener, error)
6970

7071
func startServer(ctx context.Context, hndlr http.Handler, listener net.Listener, logger *log.Logger) {
7172
srv := http.Server{
72-
Addr: listener.Addr().String(),
73-
Handler: hndlr,
73+
Addr: listener.Addr().String(),
74+
Handler: hndlr,
75+
ReadHeaderTimeout: 5 * time.Second,
7476
}
7577
logger.Printf("https://%s", srv.Addr)
7678

pkg/http/server_test.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"fmt"
88
"io"
99
"log"
10-
"math/rand"
10+
"math/rand/v2"
1111
"net/http"
1212
"os"
1313
"testing"
@@ -43,11 +43,11 @@ func TestMultiServerWithoutTLSConfigFailsToStart(t *testing.T) {
4343
func TestMultiServerServesOverBothProtocols(t *testing.T) {
4444
g := NewGomegaWithT(t)
4545

46-
httpPort := rand.Intn(49151-1024) + 1024
47-
httpsPort := rand.Intn(49151-1024) + 1024
46+
httpPort := rand.N(49151-1024) + 1024 // #nosec G404
47+
httpsPort := rand.N(49151-1024) + 1024 // #nosec G404
4848

4949
for httpPort == httpsPort {
50-
httpsPort = rand.Intn(49151-1024) + 1024
50+
httpsPort = rand.N(49151-1024) + 1024 // #nosec G404
5151
}
5252

5353
srv := wegohttp.MultiServer{
@@ -93,7 +93,8 @@ func TestMultiServerServesOverBothProtocols(t *testing.T) {
9393

9494
tr := &http.Transport{
9595
TLSClientConfig: &tls.Config{
96-
RootCAs: rootCAs,
96+
RootCAs: rootCAs,
97+
MinVersion: tls.VersionTLS12,
9798
},
9899
}
99100
c := http.Client{

pkg/kube/kube_suite_test.go

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
package kube_test
22

33
import (
4-
"math/rand"
54
"testing"
6-
"time"
75

86
. "github.com/onsi/ginkgo/v2"
97
. "github.com/onsi/gomega"
@@ -39,7 +37,3 @@ var _ = BeforeSuite(func() {
3937
var _ = AfterSuite(func() {
4038
cleanupK8s()
4139
})
42-
43-
func init() {
44-
rand.New(rand.NewSource(time.Now().UnixNano()))
45-
}

pkg/names/names.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package names
22

33
import (
4-
"crypto/md5"
4+
"crypto/sha256"
55
"fmt"
66
"strings"
77

@@ -43,7 +43,7 @@ func hashNameIfTooLong(name string) string {
4343
return name
4444
}
4545

46-
return fmt.Sprintf("wego-%x", md5.Sum([]byte(name)))
46+
return fmt.Sprintf("wego-%x", sha256.Sum224([]byte(name)))
4747
}
4848

4949
func ApplicationNameTooLong(name string) bool {

pkg/oidc/check/flow_test.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,16 @@ func (tp TestProvider) genToken() string {
3838
}
3939

4040
func (tp *TestProvider) Start() error {
41-
listener, err := net.Listen("tcp", ":8765")
41+
listener, err := net.Listen("tcp", "127.0.0.1:8765")
4242
if err != nil {
4343
return fmt.Errorf("failed starting listener: %w", err)
4444
}
4545

4646
tp.URL = fmt.Sprintf("http://%s", listener.Addr().String())
4747
mux := http.ServeMux{}
4848
tp.srv = &http.Server{
49-
Handler: &mux,
49+
Handler: &mux,
50+
ReadHeaderTimeout: 5 * time.Second,
5051
}
5152

5253
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
@@ -160,7 +161,7 @@ func TestGetClaimsWithSecret(t *testing.T) {
160161
SecretName: "test-oidc",
161162
SecretNamespace: "flux-system",
162163
OpenURL: func(u string) error {
163-
http.Get(u)
164+
http.Get(u) // #nosec: G107
164165
return nil
165166
},
166167
InsecureSkipSignatureCheck: true,
@@ -311,7 +312,7 @@ func TestGetClaimsWithoutSecret(t *testing.T) {
311312

312313
if tt.opts.OpenURL == nil {
313314
tt.opts.OpenURL = func(u string) error {
314-
http.Get(u)
315+
http.Get(u) // #nosec: G107
315316
return nil
316317
}
317318
}

pkg/oidc/check/server.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ var errorHTML string
2727
func retrieveIDToken(log logger.Logger, oauth2Config oauth2.Config, verifier *oidc.IDTokenVerifier) (*oidc.IDToken, error) {
2828
mux := http.ServeMux{}
2929
srv := http.Server{
30-
Handler: &mux,
30+
Handler: &mux,
31+
ReadHeaderTimeout: 5 * time.Second,
3132
}
3233
var idToken *oidc.IDToken
3334
var handleErr error
@@ -70,7 +71,7 @@ func retrieveIDToken(log logger.Logger, oauth2Config oauth2.Config, verifier *oi
7071
fmt.Fprint(w, successHTML)
7172
})
7273

73-
listener, err := net.Listen("tcp", ":9876")
74+
listener, err := net.Listen("tcp", ":9876") // #nosec G102
7475
if err != nil {
7576
return nil, fmt.Errorf("failed starting listener: %w", err)
7677
}

pkg/s3/auth_middleware_test.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@ import (
44
"bytes"
55
"fmt"
66
"io"
7-
"math/rand"
7+
"math/rand/v2"
88
"net/http"
99
"net/http/httptest"
1010
"testing"
11-
"time"
1211

1312
"github.com/minio/minio-go/v7/pkg/signer"
1413
. "github.com/onsi/gomega"
@@ -19,11 +18,9 @@ func generateRandomBody(method string) io.Reader {
1918
return nil
2019
}
2120

22-
srand := rand.New(rand.NewSource(time.Now().UnixNano()))
23-
24-
size := srand.Intn(2000) + 2000
21+
size := rand.N(2000) + 2000 // #nosec G404
2522
buf := make([]byte, size)
26-
srand.Read(buf)
23+
_, _ = rand.NewChaCha8([32]byte{}).Read(buf)
2724

2825
return bytes.NewReader(buf)
2926
}

pkg/s3/secret_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ import (
44
"fmt"
55
"io"
66
"math/big"
7-
"math/rand"
7+
"math/rand/v2"
88
"testing"
99

1010
. "github.com/onsi/gomega"
1111
)
1212

13-
func deterministicRandInt(seed int64, err error) RandIntFunc {
13+
func deterministicRandInt(seed uint64, err error) RandIntFunc {
1414
var srand *rand.Rand
1515

1616
return func(_ io.Reader, max *big.Int) (*big.Int, error) {
@@ -19,10 +19,10 @@ func deterministicRandInt(seed int64, err error) RandIntFunc {
1919
}
2020

2121
if srand == nil {
22-
srand = rand.New(rand.NewSource(seed))
22+
srand = rand.New(rand.NewPCG(seed, 0)) // #nosec G404
2323
}
2424

25-
return big.NewInt(int64(srand.Intn(int(max.Int64())))), nil
25+
return big.NewInt(srand.Int64N(max.Int64())), nil // #nosec G404
2626
}
2727
}
2828

@@ -38,7 +38,7 @@ func TestGenerators(t *testing.T) {
3838
name: "GenerateAccessKey generates a deterministic access key",
3939
generator: GenerateAccessKey,
4040
randIntFunc: deterministicRandInt(100, nil),
41-
expected: "AKIA5UQA4UZJM3",
41+
expected: "AKIATBK3988IAG",
4242
expectedErr: false,
4343
},
4444
{
@@ -52,7 +52,7 @@ func TestGenerators(t *testing.T) {
5252
name: "GenerateSecretKey generates a deterministic secret key",
5353
generator: GenerateSecretKey,
5454
randIntFunc: deterministicRandInt(512, nil),
55-
expected: "Fg5n9W6CwTfnMu4FzEk8xuTomwk2OpFe0yLcLMAL",
55+
expected: "0aEEdyKByGEXsQUh1af86o6HON4Ig468I6DhJH1C",
5656
expectedErr: false,
5757
},
5858
{

pkg/server/auth/auth.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ package auth
22

33
import (
44
"context"
5-
"crypto/md5"
65
"crypto/rand"
6+
"crypto/sha256"
77
"encoding/base64"
88
"encoding/hex"
99
"fmt"
@@ -106,7 +106,7 @@ func (p *UserPrincipal) String() string {
106106

107107
// Hash returns a unique string using user id,token and groups.
108108
func (p *UserPrincipal) Hash() string {
109-
hash := md5.Sum([]byte(fmt.Sprintf("%s/%s/%v", p.ID, p.Token(), p.Groups)))
109+
hash := sha256.Sum224([]byte(fmt.Sprintf("%s/%s/%v", p.ID, p.Token(), p.Groups)))
110110
return hex.EncodeToString(hash[:])
111111
}
112112

0 commit comments

Comments
 (0)