From 4763d88628d07194a282ca5ca4baaa93aa0d4cd4 Mon Sep 17 00:00:00 2001 From: likhachevam Date: Fri, 21 Nov 2025 16:10:27 +0300 Subject: [PATCH] MSP-6703 remove unused utils --- service/rqlite/internal/rarchive/gzip.go | 65 ------- service/rqlite/internal/rarchive/targz.go | 111 ------------ service/rqlite/internal/rarchive/zip.go | 86 ---------- service/rqlite/internal/rtls/certs.go | 196 ---------------------- service/rqlite/internal/rtls/config.go | 74 -------- service/rqlite/internal/rtls/reloader.go | 20 --- 6 files changed, 552 deletions(-) delete mode 100644 service/rqlite/internal/rarchive/gzip.go delete mode 100644 service/rqlite/internal/rtls/certs.go diff --git a/service/rqlite/internal/rarchive/gzip.go b/service/rqlite/internal/rarchive/gzip.go deleted file mode 100644 index b68bf4f..0000000 --- a/service/rqlite/internal/rarchive/gzip.go +++ /dev/null @@ -1,65 +0,0 @@ -// nolint -package rarchive - -import ( - "compress/gzip" - "io" - "os" -) - -// Gzip compresses the given file and returns the path to the -// compressed file. It is the caller's responsibility to remove -// the compressed file when it is no longer needed. -func Gzip(file string) (string, error) { - f, err := os.Open(file) - if err != nil { - return "", err - } - defer f.Close() - - tmpFd, err := os.CreateTemp("", "gzip") - if err != nil { - return "", err - } - - gz := gzip.NewWriter(tmpFd) - _, err = io.Copy(gz, f) - if err != nil { - return "", err - } - - err = gz.Close() - if err != nil { - return "", err - } - return tmpFd.Name(), nil -} - -// Gunzip decompresses the given GZIP file and returns the -// path to the decompressed file. It is the caller's responsibility -// to remove the decompressed file when it is no longer needed. -func Gunzip(file string) (string, error) { - f, err := os.Open(file) - if err != nil { - return "", err - } - defer f.Close() - - gz, err := gzip.NewReader(f) - if err != nil { - return "", err - } - defer gz.Close() - - tmpFd, err := os.CreateTemp("", "gunzip") - if err != nil { - return "", err - } - defer tmpFd.Close() - - _, err = io.Copy(tmpFd, gz) - if err != nil { - return "", err - } - return tmpFd.Name(), nil -} diff --git a/service/rqlite/internal/rarchive/targz.go b/service/rqlite/internal/rarchive/targz.go index a8b4ebf..73a789e 100644 --- a/service/rqlite/internal/rarchive/targz.go +++ b/service/rqlite/internal/rarchive/targz.go @@ -2,13 +2,8 @@ package rarchive import ( - "archive/tar" "compress/gzip" - "errors" - "io" "os" - "path/filepath" - "strings" ) // IsTarGzipFile checks if the file at the given path is a gzipped tarball @@ -29,109 +24,3 @@ func IsTarGzipFile(path string) bool { return true } - -// TarGzipHasSubdirectories checks if the gzipped tarball contains any entries that -// represent subdirectories or files within subdirectories. -func TarGzipHasSubdirectories(path string) (bool, error) { - // Open the tar.gz file - file, err := os.Open(path) - if err != nil { - return false, err - } - defer file.Close() - - gzr, err := gzip.NewReader(file) - if err != nil { - return false, err - } - defer gzr.Close() - - tr := tar.NewReader(gzr) - - // Iterate through each file in the tar archive - for { - header, err := tr.Next() - if err == io.EOF { - break // End of tar archive - } - if err != nil { - return false, err - } - - // Check if the file is a directory or if the file path includes a subdirectory - if header.Typeflag == tar.TypeDir || - strings.Contains(header.Name, "/") || strings.Contains(header.Name, "\\") { - return true, nil - } - } - return false, nil -} - -// UntarGzipToDir decompresses the gzipped tarball at the given path into the specified directory. -func UntarGzipToDir(path, dir string) error { - // Open the tar.gz file - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - - gzr, err := gzip.NewReader(file) - if err != nil { - return err - } - defer gzr.Close() - - tr := tar.NewReader(gzr) - - // Ensure the output directory exists - if err := os.MkdirAll(dir, 0755); err != nil { - return err - } - - // Iterate through each file in the tar archive - for { - header, err := tr.Next() - if err == io.EOF { - break // End of tar archive - } - if err != nil { - return err - } - - // Construct the full path for the file - fpath := filepath.Join(dir, header.Name) - - // Check for directory traversal vulnerability - if !strings.HasPrefix(fpath, filepath.Clean(dir)+string(os.PathSeparator)) { - return errors.New("invalid file path") - } - - if header.Typeflag == tar.TypeDir { - // Create the directory - if err := os.MkdirAll(fpath, os.FileMode(header.Mode)); err != nil { - return err - } - } else { - // Create the file - if err := os.MkdirAll(filepath.Dir(fpath), os.FileMode(header.Mode)); err != nil { - return err - } - - outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode)) - if err != nil { - return err - } - - // Copy the file content to the destination - if _, err := io.Copy(outFile, tr); err != nil { - outFile.Close() - return err - } - - outFile.Close() - } - } - - return nil -} diff --git a/service/rqlite/internal/rarchive/zip.go b/service/rqlite/internal/rarchive/zip.go index 51b613b..7364b3c 100644 --- a/service/rqlite/internal/rarchive/zip.go +++ b/service/rqlite/internal/rarchive/zip.go @@ -2,13 +2,8 @@ package rarchive import ( - "archive/zip" "bytes" - "errors" - "io" "os" - "path/filepath" - "strings" ) // IsZipFile checks if the file at the given path is a ZIP file @@ -30,84 +25,3 @@ func IsZipFile(path string) bool { // ZIP files start with "PK\x03\x04" return bytes.Equal(buf, []byte("PK\x03\x04")) } - -// ZipHasSubdirectories checks if the ZIP file contains any entries that -// represent subdirectories or files within subdirectories. -func ZipHasSubdirectories(path string) (bool, error) { - // Open the ZIP file - r, err := zip.OpenReader(path) - if err != nil { - return false, err - } - defer r.Close() - - // Iterate through each file in the ZIP archive - for _, f := range r.File { - if f.FileInfo().IsDir() || - len(f.Name) > 0 && (f.Name[len(f.Name)-1] == '/' || - len(f.Name) > 0 && f.Name != filepath.Base(f.Name)) { - return true, nil - } - } - return false, nil -} - -// UnzipToDir decompresses the ZIP file at the given path into the specified directory. -func UnzipToDir(path, dir string) error { - // Open the ZIP file - r, err := zip.OpenReader(path) - if err != nil { - return err - } - defer r.Close() - - // Ensure the output directory exists - if err := os.MkdirAll(dir, 0755); err != nil { - return err - } - - // Iterate through each file in the ZIP archive - for _, f := range r.File { - // Construct the full path for the file - fpath := filepath.Join(dir, f.Name) - - // Check for directory traversal vulnerability - if !strings.HasPrefix(fpath, filepath.Clean(dir)+string(os.PathSeparator)) { - return errors.New("invalid file path") - } - - if f.FileInfo().IsDir() { - // Create the directory - if err := os.MkdirAll(fpath, f.Mode()); err != nil { - return err - } - } else { - // Create the file - if err := os.MkdirAll(filepath.Dir(fpath), f.Mode()); err != nil { - return err - } - - outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) - if err != nil { - return err - } - - rc, err := f.Open() - if err != nil { - return err - } - - _, err = io.Copy(outFile, rc) - - // Close the file handles - outFile.Close() - rc.Close() - - if err != nil { - return err - } - } - } - - return nil -} diff --git a/service/rqlite/internal/rtls/certs.go b/service/rqlite/internal/rtls/certs.go deleted file mode 100644 index 80bee43..0000000 --- a/service/rqlite/internal/rtls/certs.go +++ /dev/null @@ -1,196 +0,0 @@ -// nolint -package rtls - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" - "net" - "time" -) - -// GenerateCACert generates a new CA certificate and returns the cert and key as PEM-encoded bytes. -func GenerateCACert(subject pkix.Name, validFor time.Duration, keySize int) ([]byte, []byte, error) { - // generate a new private key - key, err := rsa.GenerateKey(rand.Reader, keySize) - if err != nil { - return nil, nil, err - } - - // generate a new certificate - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: subject, - NotBefore: time.Now(), - NotAfter: time.Now().Add(validFor), - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, - IsCA: true, - BasicConstraintsValid: true, - } - - // generate a new certificate - cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) - if err != nil { - return nil, nil, err - } - - // encode the certificate and private key - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) - - return certPEM, keyPEM, nil -} - -// GenerateCert generates a new x509 certificate and returns the cert and key as PEM-encoded bytes. -// The function should take in a subject, a validity period, and a key size. It should optionally -// take in a parent certificate and key. If a parent certificate and key are provided, the new -// certificate should be signed by the parent. If no parent certificate and key are provided, -// the new certificate should be self-signed. -func GenerateCert(subject pkix.Name, validFor time.Duration, keySize int, parent *x509.Certificate, parentKey any) ([]byte, []byte, error) { - // generate a new private key - key, err := rsa.GenerateKey(rand.Reader, keySize) - if err != nil { - return nil, nil, err - } - - // generate a new certificate - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: subject, - NotBefore: time.Now(), - NotAfter: time.Now().Add(validFor), - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, - } - - signerCert := parent - signerKey := parentKey - if signerCert == nil { - signerCert = &template - signerKey = key - } - cert, err := x509.CreateCertificate(rand.Reader, &template, signerCert, &key.PublicKey, signerKey) - if err != nil { - return nil, nil, err - } - - // encode the certificate and private key - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) - - return certPEM, keyPEM, nil -} - -func GenerateCertIPSAN(subject pkix.Name, validFor time.Duration, keySize int, parent *x509.Certificate, parentKey any, san net.IP) ([]byte, []byte, error) { - // generate a new private key - key, err := rsa.GenerateKey(rand.Reader, keySize) - if err != nil { - return nil, nil, err - } - - // generate a new certificate - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: subject, - NotBefore: time.Now(), - NotAfter: time.Now().Add(validFor), - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, - } - - // generate cert template for new certificate suitable for client verification - - // Add IP SAN to the certificate - template.IPAddresses = append(template.IPAddresses, san) - - signerCert := parent - signerKey := parentKey - if signerCert == nil { - signerCert = &template - signerKey = key - } - cert, err := x509.CreateCertificate(rand.Reader, &template, signerCert, &key.PublicKey, signerKey) - if err != nil { - return nil, nil, err - } - - // encode the certificate and private key - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) - - return certPEM, keyPEM, nil -} - -// GenerateSelfSignedCert generates a new self-signed certificate and -// returns the cert and key as PEM-encoded bytes. -func GenerateSelfSignedCert(subject pkix.Name, validFor time.Duration, keySize int) ([]byte, []byte, error) { - // generate a new private key - key, err := rsa.GenerateKey(rand.Reader, keySize) - if err != nil { - return nil, nil, err - } - - // generate a new certificate - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: subject, - NotBefore: time.Now(), - NotAfter: time.Now().Add(validFor), - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, - IsCA: true, - BasicConstraintsValid: true, - } - - // Add IP SAN to the certificate - //template.IPAddresses = append(template.IPAddresses, net.ParseIP("127.0.0.1")) - - cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) - if err != nil { - return nil, nil, err - } - - // encode the certificate and private key - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) - - return certPEM, keyPEM, nil -} - -// GenerateSelfSignedCertIPSAN generates a new self-signed certificate and -// returns the cert and key as PEM-encoded bytes. -func GenerateSelfSignedCertIPSAN(subject pkix.Name, validFor time.Duration, keySize int, san net.IP) ([]byte, []byte, error) { - // generate a new private key - key, err := rsa.GenerateKey(rand.Reader, keySize) - if err != nil { - return nil, nil, err - } - - // generate a new certificate - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: subject, - NotBefore: time.Now(), - NotAfter: time.Now().Add(validFor), - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, - IsCA: true, - BasicConstraintsValid: true, - } - template.IPAddresses = append(template.IPAddresses, san) - - cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) - if err != nil { - return nil, nil, err - } - - // encode the certificate and private key - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) - - return certPEM, keyPEM, nil -} diff --git a/service/rqlite/internal/rtls/config.go b/service/rqlite/internal/rtls/config.go index 5a27ea7..c0f277a 100644 --- a/service/rqlite/internal/rtls/config.go +++ b/service/rqlite/internal/rtls/config.go @@ -10,19 +10,9 @@ import ( "github.com/pkg/errors" ) -const ( - NoCACert = "" - NoServerName = "" -) - // MTLSState indicates whether mutual TLS is enabled or disabled. type MTLSState tls.ClientAuthType -const ( - MTLSStateDisabled MTLSState = MTLSState(tls.NoClientCert) - MTLSStateEnabled MTLSState = MTLSState(tls.RequireAndVerifyClientCert) -) - // CreateClientConfig creates a new tls.Config for use by a client. The certFile and keyFile // parameters are the paths to the client's certificate and key files, which will be used to // authenticate the client to the server if mutual TLS is active. The caCertFile parameter @@ -49,70 +39,6 @@ func CreateClientConfig(certFile, keyFile, caCertFile, serverName string, noveri return config, nil } -// CreateClientConfigWithFunc creates a new tls.Config for use by a client. The certFunc -// parameter is a function that returns the client's certificate and key. The caCertFile -// parameter is the path to the CA certificate file, which the client will use to verify -// any certificate presented by the server. serverName can also be set, informing the client -// which hostname should appear in the returned certificate. If noverify is true, the client -// will not verify the server's certificate. -func CreateClientConfigWithFunc(certFunc func() (*tls.Certificate, error), caCertFile, serverName string, noverify bool) (*tls.Config, error) { - config := createBaseTLSConfig(serverName, noverify) - if certFunc != nil { - config.GetClientCertificate = func(hello *tls.CertificateRequestInfo) (*tls.Certificate, error) { - return certFunc() - } - } - if caCertFile != "" { - if err := setCertPool(caCertFile, &config.RootCAs); err != nil { - return nil, err - } - } - return config, nil -} - -// CreateServerConfig creates a new tls.Config for use by a server. The certFile and keyFile -// parameters are the paths to the server's certificate and key files, which will be used to -// authenticate the server to the client. The caCertFile parameter is the path to the CA -// certificate file, which the server will use to verify any certificate presented by the -// client. If mtls is MTLSStateEnabled, the server will require the client to present a -// valid certificate. -func CreateServerConfig(certFile, keyFile, caCertFile string, mtls MTLSState) (*tls.Config, error) { - var err error - - config := createBaseTLSConfig(NoServerName, false) - config.Certificates = make([]tls.Certificate, 1) - config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return nil, err - } - if caCertFile != "" { - if err := setCertPool(caCertFile, &config.ClientCAs); err != nil { - return nil, err - } - } - config.ClientAuth = tls.ClientAuthType(mtls) - return config, nil -} - -// CreateServerConfigWithFunc creates a new tls.Config for use by a server. The certFunc -// parameter is a function that returns the server's certificate and key. The caCertFile -// parameter is the path to the CA certificate file, which the server will use to verify -// any certificate presented by the client. If mtls is MTLSStateEnabled, the server will -// require the client to present a valid certificate. -func CreateServerConfigWithFunc(certFunc func() (*tls.Certificate, error), caCertFile string, mtls MTLSState) (*tls.Config, error) { - config := createBaseTLSConfig(NoServerName, false) - config.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { - return certFunc() - } - if caCertFile != "" { - if err := setCertPool(caCertFile, &config.ClientCAs); err != nil { - return nil, err - } - } - config.ClientAuth = tls.ClientAuthType(mtls) - return config, nil -} - func createBaseTLSConfig(serverName string, noverify bool) *tls.Config { return &tls.Config{ ServerName: serverName, diff --git a/service/rqlite/internal/rtls/reloader.go b/service/rqlite/internal/rtls/reloader.go index 7e17049..06daa0e 100644 --- a/service/rqlite/internal/rtls/reloader.go +++ b/service/rqlite/internal/rtls/reloader.go @@ -21,26 +21,6 @@ type CertReloader struct { cert *tls.Certificate } -// NewCertReloader creates a new CertReloader instance. -func NewCertReloader(cert, key string) (*CertReloader, error) { - cr := &CertReloader{ - certPath: cert, - keyPath: key, - logger: log.New(os.Stderr, "[cert-reloader] ", log.LstdFlags), - } - pair, err := loadKeyPair(cr.certPath, cr.keyPath) - if err != nil { - return nil, err - } - cr.cert = &pair - latestTime, err := latestModTime(cr.certPath, cr.keyPath) - if err != nil { - return nil, err - } - cr.modTime = latestTime - return cr, nil -} - // GetCertificate returns the current certificate. It reloads the certificate // if it has been modified since the last load. GetCertificate is thread-safe // and if the cert has not changed this function will execute concurrently with