Golang 使用 SSL 证书连接到 Postgres

Ale*_*gov 4 postgresql ssl openssl go docker

首先,问题与语言无关。我正在尝试编写一个使用 SSL 连接到 PostgreSQL 的简单应用程序。

  1. 我使用脚本创建了证书:
# Create CA private key
openssl genrsa -des3 -out root.key 4096
#Remove a passphrase
openssl rsa -in root.key -out root.key

# Create a root Certificate Authority (CA)
openssl \
    req -new -x509 \
    -days 365 \
    -subj "/CN=localhost" \
    -key root.key \
    -out root.crt

# Create server key
openssl genrsa -des3 -out server.key 4096
#Remove a passphrase
openssl rsa -in server.key -out server.key

# Create a root certificate signing request
openssl \
    req -new \
    -key server.key \
    -subj "/CN=localhost" \
    -text \
    -out server.csr

# Create server certificate
openssl \
    x509 -req \
    -in server.csr \
    -text \
    -days 365 \
    -CA root.crt \
    -CAkey root.key \
    -CAcreateserial \
    -out server.crt
Run Code Online (Sandbox Code Playgroud)
  1. 我使用以下方法创建了一个数据库:

初始化sql

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE TESTING_DATA (
    ID SERIAL PRIMARY KEY,
    UUID UUID UNIQUE NOT NULL DEFAULT uuid_generate_v4(),
    NAME TEXT NOT NULL,
    INFO NUMERIC(3, 2)
);

INSERT INTO TESTING_DATA (NAME, INFO)
VALUES
    ('Notebook', 1),
    ('Office supplies', 2),
    ('Pencil', 2),
    ('Office supplies', 1),
    ('Eraser', 1),
    ('Coffee', 1),
    ('Cookies', 2),
    ('Puzzles', 5)
;
Run Code Online (Sandbox Code Playgroud)

postgresql.conf

ssl = on
ssl_ca_file = '/etc/postgres/security/root.crt'
ssl_cert_file = '/etc/postgres/security/server.crt'
ssl_key_file = '/etc/postgres/security/server.key'
password_encryption = scram-sha-256
Run Code Online (Sandbox Code Playgroud)

pg_hba.conf

local     all      all                md5
host      all      all  127.0.0.1/32  md5
hostssl   all      all  0.0.0.0/0     cert clientcert=1
Run Code Online (Sandbox Code Playgroud)

Dockerfile

FROM postgres:12-alpine

ENV POSTGRES_USER=pguser
ENV POSTGRES_PASSWORD=pgpassword
ENV POSTGRES_DB=securitylearning

COPY pg_hba.conf postgresql.conf /etc/postgresql/config/
COPY --chown=postgres:postgres root.crt server.crt server.key /etc/postgres/security/
COPY init.sql /docker-entrypoint-initdb.d/
EXPOSE 5432
CMD ["postgres", "-c", "config_file=/etc/postgresql/config/postgresql.conf", "-c", "hba_file=/etc/postgresql/config/pg_hba.conf"]
Run Code Online (Sandbox Code Playgroud)

我启动了一个容器,确保我可以从容器本身连接到数据库并从表中选择某些内容。

  1. 我创建了一个简单的程序: server.go
package main

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

func main() {
    connection := fmt.Sprint(
        " host=localhost",
        " port=5432",
        " user=pguser",
        " dbname=securitylearning",
        " sslmode=verify-full",
        " sslrootcert=root.crt",
        " sslkey=client.key",
        " sslcert=client.crt",
    )
    db, err := sql.Open("postgres", connection)
    defer db.Close()
    if err != nil {
        panic(err)
    }
    err = db.Ping()
    if err != nil {
        panic(err)
    }
    row := db.QueryRow("SELECT * FROM TESTING_DATA")
    fmt.Println(row)
}
Run Code Online (Sandbox Code Playgroud)

我尝试过了:

目前,它不起作用。我随机得到这两个错误之一:

读取:连接被对等方重置

或者

EOF

能否请你帮忙?我在这里缺少什么?或者你能给我指点一些资源吗?提前致谢。

更新 1 感谢评论中的建议,我创建了客户端密钥和证书,使用

# Create client key
openssl genrsa -out client.key 4096
#Remove a passphrase
openssl rsa -in client.key -out client.key

# Create client certificate signing request
openssl \
    req -new \
    -key client.key \
    -subj "/CN=172.17.0.2" \
    -out client.csr

# Create client certificate
openssl \
    x509 -req \
    -in client.csr \
    -CA root.crt \
    -CAkey root.key \
    -CAcreateserial \
    -days 365 \
    -text \
    -out client.crt
Run Code Online (Sandbox Code Playgroud)

我在 CN 中使用 172.17.0.2,因为从 docker 容器的角度来看它是主机 IP。

我都尝试过:

  • 在程序的连接字符串中使用以下键
" sslrootcert=root.crt",
" sslkey=client.key",
" sslcert=client.crt",
Run Code Online (Sandbox Code Playgroud)
  • 复制root.crt, client.key,client.srt~/.postgresql/, 尝试 psql
psql "host=localhost port=5432 user=pguser dbname=securitylearning sslmode=verify-full sslrootcert=root.crt sslkey=client.key sslcert=client.crt"
Run Code Online (Sandbox Code Playgroud)

或没有密码。

两种方式仍然无法连接。在 psql 情况下我收到错误 psql: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.

Ale*_*gov 5

感谢评论中的建议,我设法解决了这个问题。

首先,按照建议,我退后一步,尝试以较小的步骤继续进行。例如,与psql主机安全连接。

错误1

我忘记将以下属性添加到postgresql.conf

listen_addresses = '*'
Run Code Online (Sandbox Code Playgroud)

文档

如果列表为空,则服务器根本不侦听任何 IP 接口,在这种情况下,只能使用 Unix 域套接字来连接它。

错误2

我对证书及其通用名称(CN)陷入了一些误解。以下几点应适用于创建证书的脚本。简而言之:

  • CA 的 CN 可以是任何值,只要与服务器的 CN 不同即可。有关详细信息,请参阅此问题和答案
  • 服务器的 CN 必须是 IP/主机名,我们将通过它从客户端调用服务器(这里是localhost。但是如果数据库位于 cooldatabase.com<- 这将是服务器的 CN)
  • 客户端的 CN 必须是我们连接的用户名(这里是 pguser

当我解决这两个问题时 - 我设法通过 psql 和 go 程序进行连接!另外,默认的 postgresql.conf 信息非常丰富!