PostgreSQL支持使用ssl加密连接来增加安全性,要启用这个特性,数据库在编译时必须指定–with-openssl选项
SSL 服务器文件作用
文件 | 内容 | 效果 |
---|---|---|
ssl_cert_file ($PGDATA/server.crt ) | 服务器证书 | 发送给客户端来说明服务器的身份 |
ssl_key_file ($PGDATA/server.key ) | 服务器私钥 | 证明服务器证书是其所有者发送的,并不说明证书所有者是值得信任的 |
ssl_ca_file | 可信的证书颁发机构 | 检查客户端证书是由一个可信的证书颁发机构签名的 |
ssl_crl_file | 被证书授权机构撤销的证书 | 客户端证书不能出现在这个列表上 |
配置步骤
创建自签名证书
openssl req -new -x509 -days 365 -nodes -text -out server.crt \
-keyout server.key -subj "/CN=node1"
修改权限
chmod og-rwx server.key
创建服务器私钥
openssl req -new -nodes -text -out root.csr \
-keyout root.key -subj "/CN=node1"
修改权限
chmod og-rwx root.key
创建根证书
openssl x509 -req -in root.csr -text -days 3650 \
-extfile /etc/pki/tls/openssl.cnf -extensions v3_ca \
-signkey root.key -out root.crt
创建根证书密钥
openssl req -new -nodes -text -out server.csr \
-keyout server.key -subj "/CN=node1"
修改权限
chmod og-rwx server.key
创建由新的根证书颁发机构签名的服务器证书
openssl x509 -req -in server.csr -text -days 365 \
-CA root.crt -CAkey root.key -CAcreateserial \
-out server.crt
复制服务器证书和服务器密钥到$PGDATA
cp /home/pg14/ssl/server.crt /home/pg14/data
cp /home/pg14/ssl/server.key /home/pg14/data
修改参数文件
postgresql.auto.conf参数文件添加下面三行
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
重启数据库
pg_ctl restart -D $PGDATA -l /tmp/logfile
创建ssl扩展
postgres=# create extension sslinfo;
CREATE EXTENSION
postgres=# select ssl_is_used();
ssl_is_used
-------------
f
验证ssl连接
退出重新以远程连接方式连接
psql -d postgres -U postgres -h localhost
psql (14.6)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.
postgres=# select ssl_is_used();
ssl_is_used
-------------
t
(1 row)
错误:
ERROR: could not open extension control file "/home/pg14/soft/share/postgresql/extension/sslinfo.control": No such file or directory
这是因为在指定目录下没有找到sslinfo.control,可以find一下该文件,发现他在/home/pg14/postgresql-14.6/contrib/sslinfo目录下,这是因为编译安装时没有使用world编译,将这个目录下的所有文件都复制到/home/pg14/soft/share/postgresql/extension/下,创建扩展还是报错:
ERROR: could not access file "$libdir/sslinfo": No such file or directory,要先弄清$libdir是哪个目录,执行pg_config --pkglibdir发现$libdir
是/home/pg14/soft/lib/postgresql目录,里面确实没有sslinfo.so文件,于是去/home/pg14/postgresql-14.6/contrib/sslinfo目录下,把sslinfo.c重新编译,make&&make install 把生成的sslinfo.so文件复制到/home/pg14/soft/lib/postgresql目录下,再次创建扩展成功。