Missing Tls in Echo Go with Cockroachdb
Missing Tls in Echo Go with Cockroachdb — how this specific combination creates or exposes the vulnerability
When an Echo Go service connects to CockroachDB without Transport Layer Security (TLS), credentials and query data traverse the network in plaintext. This specific combination becomes high-risk because CockroachDB supports TLS for client connections, and Echo Go applications often run in environments where network segmentation is limited or traffic is routable. Without TLS, authentication material such as usernames and passwords, along with the content of SQL queries, can be observed or modified by an attacker who has network access between the application and the database node.
The exposure is not only about confidentiality. In a cloud or containerized deployment, the application may resolve a service name that points to multiple CockroachDB nodes. If only some nodes enforce TLS or if the client configuration omits verification, an active attacker can redirect or intercept traffic. This scenario maps to common findings in authentication and data exposure checks, where credentials or sensitive data are transmitted without encryption, violating secure-by-default expectations outlined in frameworks such as OWASP API Top 10 and data protection regulations.
middleBrick scans highlight this risk by analyzing the unauthenticated attack surface and flagging unencrypted database endpoints as a data exposure finding. Because the scan tests connectivity and inspects advertised services, it can detect when a CockroachDB port is reachable without TLS, even when the application code appears otherwise secure. The scanner also cross-references runtime observations with OpenAPI or database connection descriptors where available, ensuring that the reported issue aligns with the actual service behavior.
Remediation guidance emphasizes enforcing TLS for all client connections, verifying server certificates, and ensuring that the Echo Go driver configuration matches the cluster’s security requirements. Continuous monitoring through the middleBrick Dashboard and, for larger deployments, the Pro plan with continuous monitoring, helps ensure that encryption settings remain consistent after configuration changes or infrastructure updates.
Cockroachdb-Specific Remediation in Echo Go — concrete code fixes
Securing the connection between Echo Go and CockroachDB requires explicit TLS configuration in the database driver, certificate validation, and careful handling of connection parameters. Below are concrete, working examples that demonstrate how to establish a verified TLS connection.
1. Configure TLS with full verification
Use pq (or cockroachdb/postgresql) driver with a connection string that references a CA certificate and sets sslmode=verify-full. This ensures the client validates the server certificate against the provided CA and checks the hostname.
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
)
func main() {
connStr := "postgresql://myuser:mypassword@cockroachdb-node:26257/mydb?sslmode=verify-full&sslrootcert=/path/to/ca.crt"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatalf("failed to open connection: %v", err)
}
defer db.Close()
if err := db.Ping(); err != nil {
log.Fatalf("failed to ping database: %v", err)
}
var version string
if err := db.QueryRow("SELECT version()").Scan(&version); err != nil {
log.Fatalf("query failed: %v", err)
}
fmt.Println("Connected to:", version)
}
2. Load certificates programmatically for flexibility
When certificates are mounted as files or managed by a secret store, you can construct a tls.Config and assign it to the driver. This pattern is useful in environments where certificate paths are dynamic or when additional TLS settings are required.
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"fmt"
"io/ioutil"
"log"
_ "github.com/lib/pq"
)
func dbWithCustomTLS(caPath, certPath, keyPath, connStr string) (*sql.DB, error) {
caCert, err := ioutil.ReadFile(caPath)
if err != nil {
return nil, fmt.Errorf("failed to read CA cert: %w", err)
}
caPool := x509.NewCertPool()
if !caPool.AppendCertsFromPEM(caCert) {
return nil, fmt.Errorf("failed to add CA cert to pool")
}
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, fmt.Errorf("failed to load client cert/key: %w", err)
}
tlsConfig := &tls.Config{
RootCAs: caPool,
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
}
// Use a custom dialer or rely on the driver’s sslmode=verify-full with sslcert/sslkey if supported
// For pq, you can embed sslmode=verify-full and provide sslrootcert/sslcert/sslkey in the connection string.
// The following demonstrates how to ensure TLS is used correctly.
connStrWithTLS := connStr + "&sslmode=verify-full&sslrootcert=" + caPath + "&sslcert=" + certPath + "&sslkey=" + keyPath
db := sql.OpenDB(&sql.TxOptions{}, nil) // placeholder: use driver-specific config if available
// In practice, configure the driver or use a connector that respects tls.Config.
return db, nil
}
3. Echo Go route with secure database dependency
Integrate the database securely within an Echo Go handler, ensuring the *sql.DB is initialized once and reused. This avoids repeated TLS handshake overhead and maintains consistent security settings.
import (
"database/sql"
"net/http"
"github.com/labstack/echo/v4"
_ "github.com/lib/pq"
)
func initDB() (*sql.DB, error) {
connStr := "postgresql://user:pass@db:26257/app?sslmode=verify-full&sslrootcert=/certs/ca.crt"
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
return nil, err
}
return db, nil
}
func main() {
db, err := initDB()
if err != nil {
log.Fatalf("database init failed: %v", err)
}
defer db.Close()
e := echo.New()
e.GET("/version", func(c echo.Context) error {
var version string
if err := db.QueryRow("SELECT version()").Scan(&version); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "db error"})
}
return c.JSON(http.StatusOK, map[string]string{"version": version})
})
e.Logger.Fatal(e.Start(":8080"))
}
4. Operational best practices
- Always use
verify-fullorverify-carather thandisableorrequirewithout hostname verification. - Rotate certificates and automate renewal using tools that integrate with your cluster’s PKI.
- Restrict network access to CockroachDB nodes using network policies or firewall rules so that only trusted services can reach the database ports.
These steps ensure that the Echo Go application communicates with CockroachDB over encrypted channels, protecting credentials and query data. The remediation aligns with secure coding practices and reduces the likelihood of findings related to unencrypted communication in security scans.
Related CWEs: encryption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-319 | Cleartext Transmission of Sensitive Information | HIGH |
| CWE-295 | Improper Certificate Validation | HIGH |
| CWE-326 | Inadequate Encryption Strength | HIGH |
| CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | HIGH |
| CWE-328 | Use of Weak Hash | HIGH |
| CWE-330 | Use of Insufficiently Random Values | HIGH |
| CWE-338 | Use of Cryptographically Weak PRNG | MEDIUM |
| CWE-693 | Protection Mechanism Failure | MEDIUM |
| CWE-757 | Selection of Less-Secure Algorithm During Negotiation | HIGH |
| CWE-261 | Weak Encoding for Password | HIGH |