0

I have opened a TCP connection with the database server using:

conn, err := net.Dial("tcp", "localhost:5432") Which is successful after that I am running this piece of code:


    _, err = conn.Write([]byte(query))
    if err != nil {
        fmt.Printf("Query failed: %v\n", err)
        return


    // Read the response and print the result in table view
    buf := make([]byte, 50000)
    n, err := conn.Read(buf)
    if err != nil {
        fmt.Printf("Failed to read response: %v\n", err)
        return
    }
    fmt.Printf("Response received: %s\n", string(buf[:n]))

It prints: Response received: N

And log file of server says:

2023-02-22 22:59:49.834 PKT [54802] FATAL: received unencrypted data after SSL request

2023-02-22 22:59:49.834 PKT [54802] DETAIL: This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.

Kamlesh Kumar
  • 351
  • 1
  • 7
  • 3
    Are you building a postgres driver? If not, if all you want is to send SQL queries to the db, then why don't you use a driver and `database/sql`? – mkopriva Feb 22 '23 at 18:26
  • 2
    If you don't want to use a driver and instead you want to speak to the db directly, then you'll have to first learn the [frontend/backend protocol](https://postgresql.org/docs/15/interactive/protocol.html), because plain SQL is not enough to talk to a pg backend. – mkopriva Feb 22 '23 at 18:33
  • 3
    The database expects SSL/TLS. Your code does not meet this expectation. Hence the error. – Steffen Ullrich Feb 22 '23 at 18:41

1 Answers1

1

The PostgreSQL server demands by default that all its clients use an SSL-encrypted connection, so it will always reject your requests.

For testing/dev purposes and aware that your connection will be unsafe, you can work around this with some tricks:

  1. Create a connection with the TLS package and allow it to skip the certificates verification.
  tlsConfig := &tls.Config{
    InsecureSkipVerify: true,
  }
        
  conn, err := tls.Dial("tcp", "localhost:5432", tlsConfig)
  1. If you could, always use the database/sql package, it abstracts all those database vendor specificities to you. Set the sslmode to disable.
  connStr := "user=myuser password=mypassword dbname=mydb host=localhost sslmode=disable"
  db, err := sql.Open("postgres", connStr)
  if err != nil {
      fmt.Printf("Failed to connect to server: %v\n", err)
      return
  }
  defer db.Close()
  1. Find the pg_hba.conf file in your PostgreSQL installation data directory and add the following line to always trust your local host:
    host    postgres   postgres   127.0.0.1/32    trust

Assuming the username is postgres

  1. Find the postgres.conf file in your PostgreSQL installation data directory and set the ssl parameter to off.

Remember that all those are configurations that will still leave your connection unsafe and prone to attacks.

To properly create your connection with SSL you need to set up your certificates. This GIST should help.