在 PostgreSQL 中使用 SSL
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1192
在 PostgreSQL 中使用 SSL/TLS 證書連接資料庫,是為了保障傳輸的安全性。你可以讓客戶端(如 psql、應用程式等)透過 TLS 與伺服器進行加密通信,並驗證伺服器的憑證(以及可選的客戶端憑證)。
以下是如何使用證書連接 PostgreSQL 的詳細步驟:
1. 伺服器端設定 PostgreSQL 使用 TLS(已經啟用可略過)
需要準備以下檔案:
-
server.crt:伺服器的公鑰證書(由 CA 簽署)
-
server.key:伺服器的私鑰
-
root.crt(選擇性):根證書,若使用自簽 CA 需要
-
放置路徑:一般放在 PostgreSQL 的 data 目錄中
修改 postgresql.conf
:
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_ca_file = 'root.crt' # optional
修改 pg_hba.conf
:
hostssl all all 0.0.0.0/0 cert
2. 客戶端連接方式
若只驗證伺服器(常見情況)
所需檔案:
-
root.crt(伺服器端所使用的 CA)
連接方式(psql 為例):
psql "host=myhost port=5432 dbname=mydb user=myuser sslmode=verify-full sslrootcert=path/to/root.crt"
sslmode 說明:
模式 | 說明 |
---|---|
disable | 不使用 SSL |
allow | 優先使用非 SSL,若支援 SSL 則使用 |
prefer | 預設。優先 SSL,不強制 |
require | 強制使用 SSL,但不驗證憑證 |
verify-ca | 強制使用 SSL,且需憑證是可信 CA 簽署 |
verify-full | 最嚴格,還要驗證主機名稱符合憑證 CN |
若同時使用客戶端憑證(雙向驗證)
所需檔案:
-
client.crt:客戶端憑證
-
client.key:客戶端私鑰
-
root.crt:CA 根證書
psql "host=myhost port=5432 dbname=mydb user=myuser sslmode=verify-full sslrootcert=path/to/root.crt sslcert=path/to/client.crt sslkey=path/to/client.key"
檔案權限要求(重要)
在 Unix/Linux 上,私鑰檔案必須設定為只有使用者可讀,否則會報錯。
chmod 600 server.key
chmod 600 client.key
Npgsql(C#)範例(若你是用 .NET)
var connString = new NpgsqlConnectionStringBuilder
{
Host = "myhost",
Port = 5432,
Username = "myuser",
Password = "mypassword",
Database = "mydb",
SslMode = SslMode.VerifyFull,
TrustServerCertificate = false,
RootCertificate = "path/to/root.crt",
ClientCertificate = new X509Certificate2("path/to/client.pfx", "password")
}.ToString();
using var conn = new NpgsqlConnection(connString);
conn.Open();
This article was last edited at