19.3. Подключения и аутентификация
19.3.1. Параметры подключений
listen_addresses
(string
)Задаёт адреса TCP/IP, по которым сервер будет принимать подключения клиентских приложений. Это значение принимает форму списка, разделённого запятыми, из имён и/или числовых IP-адресов компьютеров. Особый элемент,
*
, обозначает все имеющиеся IP-интерфейсы. Запись0.0.0.0
позволяет задействовать все адреса IPv4, а::
— все адреса IPv6. Если список пуст, сервер не будет привязываться ни к какому IP-интерфейсу, а значит, подключиться к нему можно будет только через Unix-сокеты. По умолчанию этот параметр содержит localhost, что допускает подключение к серверу по TCP/IP только через локальный интерфейс «замыкания». Хотя механизм аутентификации клиентов (см. Главу 20) позволяет гибко управлять доступом пользователей к серверу, параметрlisten_addresses
может ограничить интерфейсы, через которые будут приниматься соединения, что бывает полезно для предотвращения злонамеренных попыток подключения через незащищённые сетевые интерфейсы. Этот параметр можно задать только при запуске сервера.port
(integer
)TCP-порт, открываемый сервером; по умолчанию, 5432. Заметьте, что этот порт используется для всех IP-адресов, через которые сервер принимает подключения. Этот параметр можно задать только при запуске сервера.
max_connections
(integer
)Определяет максимальное число одновременных подключений к серверу БД. По умолчанию обычно это 100 подключений, но это число может быть меньше, если ядро накладывает свои ограничения (это определяется в процессе initdb). Этот параметр можно задать только при запуске сервера.
Для ведомого сервера значение этого параметра должно быть больше или равно значению на ведущем. В противном случае на ведомом сервере не будут разрешены запросы.
superuser_reserved_connections
(integer
)Определяет количество «слотов» подключений, которые PostgreSQL будет резервировать для суперпользователей. При этом всего одновременно активными могут быть максимум max_connections подключений. Когда число активных одновременных подключений больше или равно
max_connections
минусsuperuser_reserved_connections
, принимаются только подключения суперпользователей, а все другие подключения, в том числе подключения для репликации, запрещаются.По умолчанию резервируются три соединения. Это значение должно быть меньше значения
max_connections
. Задать этот параметр можно только при запуске сервера.unix_socket_directories
(string
)Задаёт каталог Unix-сокета, через который сервер будет принимать подключения клиентских приложений. Создать несколько сокетов можно, перечислив в этом значении несколько каталогов через запятую. Пробелы между элементами этого списка игнорируются; если в пути каталога содержатся пробелы, его нужно заключать в двойные кавычки. При пустом значении сервер не будет работать с Unix-сокетами, в этом случае к нему можно будет подключиться только по TCP/IP. Значение по умолчанию обычно
/tmp
, но его можно изменить во время сборки. Задать этот параметр можно только при запуске сервера.Помимо самого файла сокета, который называется
.s.PGSQL.
(гдеnnnn
nnnn
— номер порта сервера), в каждом каталогеunix_socket_directories
создаётся обычный файл.s.PGSQL.
. Ни в коем случае не удаляйте эти файлы вручную.nnnn
.lockЭтот параметр не действует в системе Windows, так как в ней нет Unix-сокетов.
unix_socket_group
(string
)Задаёт группу-владельца Unix-сокетов. (Пользователем-владельцем сокетов всегда будет пользователь, запускающий сервер.) В сочетании с
unix_socket_permissions
данный параметр можно использовать как дополнительный механизм управления доступом к Unix-сокетам. По умолчанию он содержит пустую строку, то есть группой-владельцем становится основная группа пользователя, запускающего сервер. Задать этот параметр можно только при запуске сервера.Этот параметр не действует в системе Windows, так как в ней нет Unix-сокетов.
unix_socket_permissions
(integer
)Задаёт права доступа к Unix-сокетам. Для Unix-сокетов применяется обычный набор разрешений Unix. Значение параметра ожидается в числовом виде, который принимают функции
chmod
иumask
. (Для применения обычного восьмеричного формата число должно начинаться с0
(нуля).)По умолчанию действуют разрешения
0777
, при которых подключаться к сокету могут все. Другие разумные варианты —0770
(доступ имеет только пользователь и группа, см. такжеunix_socket_group
) и0700
(только пользователь). (Заметьте, что для Unix-сокетов требуется только право на запись, так что добавлять или отзывать права на чтение/выполнение не имеет смысла.)Этот механизм управления доступом не зависит от описанного в Главе 20.
Этот параметр можно задать только при запуске сервера.
Данный параметр неприменим для некоторых систем, в частности, Solaris (а именно Solaris 10), которые полностью игнорируют разрешения для сокетов. В таких системах примерно тот же эффект можно получить, указав в параметре
unix_socket_directories
каталог, доступ к которому ограничен должным образом. Этот параметр также неприменим в Windows, где нет Unix-сокетов.bonjour
(boolean
)Включает объявления о существовании сервера посредством Bonjour. По умолчанию выключен. Задать этот параметр можно только при запуске сервера.
bonjour_name
(string
)Задаёт имя службы в среде Bonjour. Если значение этого параметра — пустая строка (
''
) (это значение по умолчанию), в качестве этого имени используется имя компьютера. Этот параметр игнорируется, если сервер был скомпилирован без поддержки Bonjour. Задать этот параметр можно только при запуске сервера.tcp_keepalives_idle
(integer
)Задаёт период неактивности (в секундах), после которого по TCP клиенту должен отправляться сигнал сохранения соединения. При значении 0 действует системный параметр. Этот параметр поддерживается только в системах, воспринимающих параметр сокета
TCP_KEEPIDLE
или равнозначный, а также в Windows; в других системах он должен быть равен нулю. В сеансах, подключённых через Unix-сокеты, он игнорируется и всегда считается равным 0.Примечание
В Windows при нулевом значении этот период устанавливается равным 2 часам, так как Windows не позволяет прочитать системное значение по умолчанию.
tcp_keepalives_interval
(integer
)Задаёт интервал (в секундах), по истечении которого следует повторять сигнал сохранения соединения, если ответ от клиента не был получен. При значении 0 действует системная величина. Этот параметр поддерживается только в системах, воспринимающих параметр сокета
TCP_KEEPINTVL
или равнозначный, а также в Windows; в других системах он должен быть равен нулю. В сеансах, подключённых через Unix-сокеты, он игнорируется и всегда считается равным 0.Примечание
В Windows при нулевом значении этот интервал устанавливается равным 1 секунде, так как Windows не позволяет прочитать системное значение по умолчанию.
tcp_keepalives_count
(integer
)Задаёт число TCP-сигналов сохранения соединения, которые могут быть потеряны до того, как соединение сервера с клиентом будет признано прерванным. При значении 0 действует системная величина. Этот параметр поддерживается только в системах, воспринимающих параметр сокета
TCP_KEEPCNT
или равнозначный; в других системах он должен быть равен нулю. В сеансах, подключённых через Unix-сокеты, он игнорируется и всегда считается равным 0.Примечание
В Windows данный параметр не поддерживается и должен быть равен нулю.
19.3.2. Безопасность и аутентификация
authentication_timeout
(integer
)Максимальное время, за которое должна произойти аутентификация (в секундах). Если потенциальный клиент не сможет пройти проверку подлинности за это время, сервер закроет соединение. Благодаря этому зависшие при подключении клиенты не будут занимать соединения неограниченно долго. Значение этого параметра по умолчанию — одна минута (
1m
). Задать этот параметр можно только вpostgresql.conf
или в командной строке при запуске сервера.ssl
(boolean
)Разрешает SSL-подключения. Прежде чем включать SSL, прочитайте Раздел 18.9. По умолчанию он выключен (
off
). Этот параметр можно задать только при запуске сервера. SSL-подключения поддерживаются только для соединений по TCP/IP.ssl_ca_file
(string
)Задаёт имя файла, содержащего сертификаты центров сертификации (ЦС) для SSL-сервера. По умолчанию этот параметр пуст; то есть информация о ЦС не загружается и проверка клиентских сертификатов не выполняется. (В предыдущих выпусках PostgreSQL это имя было фиксированным:
root.crt
.) При указании относительного пути он рассматривается от каталога данных. Задать этот параметр можно только при запуске сервера.ssl_cert_file
(string
)Задаёт имя файла, содержащего сертификат SSL-сервера. Имя по умолчанию —
server.crt
. При указании относительного пути он рассматривается от каталога данных. Задать этот параметр можно только при запуске сервера.ssl_crl_file
(string
)Задаёт имя файла, содержащего список отзыва сертификатов (CRL) для SSL-сервера. По умолчанию не определён, то есть файл CRL не загружается. (В предыдущих выпусках PostgreSQL это имя было фиксированным:
root.crl
.) При указании относительного пути он рассматривается от каталога данных. Задать этот параметр можно только при запуске сервера.ssl_key_file
(string
)Задаёт имя файла, содержащего закрытый ключ SSL-сервера. По умолчанию имеет значение
server.key
. При указании относительного пути он рассматривается от каталога данных. Задать этот параметр можно только при запуске сервера.ssl_ciphers
(string
)Задаёт список наборов шифров SSL, которые могут применяться для SSL-соединений. Синтаксис этого параметра и список поддерживаемых значений можно найти на странице ciphers руководства по OpenSSL. Этот параметр действует только для подключений TLS версии 1.2 и ниже. Для подключений TLS версии 1.3 возможность выбора шифров в настоящее время отсутствует. Значение по умолчанию —
HIGH:MEDIUM:+3DES:!aNULL
. Обычно оно вполне приемлемо при отсутствии особых требований по безопасности. Задать этот параметр можно только при запуске сервера.Объяснение значения по умолчанию:
HIGH
Наборы шифров, в которых используются шифры из группы высокого уровня (
HIGH
), (например: AES, Camellia, 3DES)MEDIUM
Наборы шифров, в которых используются шифры из группы среднего уровня (
MEDIUM
) (например, RC4, SEED)+3DES
Порядок шифров для группы
HIGH
по умолчанию в OpenSSL определён некорректно. В нём 3DES оказывается выше AES128, что неправильно, так как он считается менее безопасным, чем AES128, и работает гораздо медленнее. Включение+3DES
меняет этот порядок, чтобы данный алгоритм следовал после всех шифров группHIGH
иMEDIUM
.!aNULL
Отключает наборы анонимных шифров, не требующие проверки подлинности. Такие наборы уязвимы для атак с посредником, поэтому использовать их не следует.
Конкретные наборы шифров и их свойства очень различаются от версии к версии OpenSSL. Чтобы получить фактическую информацию о них для текущей установленной версии OpenSSL, выполните команду
openssl ciphers -v 'HIGH:MEDIUM:+3DES:!aNULL'
. Учтите, что этот список фильтруется во время выполнения, в зависимости от типа ключа сервера.ssl_prefer_server_ciphers
(bool
)Определяет, должны ли шифры SSL сервера предпочитаться клиентским. По умолчанию предпочтение отдаётся шифрам сервера. Этот параметр можно задать только при запуске сервера.
В старых версиях PostgreSQL этот параметр отсутствовал и предпочтение отдавалось выбору клиента. Введён этот параметр в основном для обеспечения совместимости с этими версиями. Вообще же обычно лучше использовать конфигурацию сервера, так как в конфигурации на стороне клиента более вероятны ошибки.
ssl_ecdh_curve
(string
)Задаёт имя кривой для использования при обмене ключами ECDH. Эту кривую должны поддерживать все подключающиеся клиенты. Это не обязательно должна быть кривая, с которой был получен ключ сервера. По умолчанию выбирается кривая
prime256v1
. Этот параметр можно задать только при запуске сервера.Наиболее популярные кривые OpenSSL:
prime256v1
(NIST P-256),secp384r1
(NIST P-384) иsecp521r1
(NIST P-521).Полный список доступных кривых можно получить командой
openssl ecparam -list_curves
. Однако не все из них пригодны для TLS.password_encryption
(boolean
)Этот параметр определяет, будет ли пароль шифроваться, когда он передаётся в CREATE USER или ALTER ROLE без указания
ENCRYPTED
илиUNENCRYPTED
. По умолчанию этот параметр установлен (on
), то есть пароль шифруется.krb_server_keyfile
(string
)Задаёт размещение файла ключей для сервера Kerberos. За подробностями обратитесь к Подразделу 20.3.3. Задать этот параметр можно только в
postgresql.conf
или в командной строке при запуске сервера.krb_caseins_users
(boolean
)Определяет, должны ли имена пользователей GSSAPI обрабатываться без учёта регистра. По умолчанию значение этого параметра —
off
(регистр учитывается). Задать этот параметр можно только вpostgresql.conf
или в командной строке при запуске сервера.db_user_namespace
(boolean
)Этот параметр позволяет относить имена пользователей к базам данных. По умолчанию он имеет значение off (выключен). Задать этот параметр можно только в
postgresql.conf
или в командной строке при запуске сервера.Если он включён, имена создаваемых пользователей должны иметь вид
имя_пользователя@база_данных
. Когда подключающийся клиент передаётимя_пользователя
, к этому имени добавляется@
с именем базы данных, и сервер идентифицирует пользователя по этому полному имени. Заметьте, что для создания пользователя с именем, содержащим@
, в среде SQL потребуется заключить это имя в кавычки.Когда этот параметр включён, он не мешает создавать и использовать обычных глобальных пользователей. Чтобы подключиться с таким именем пользователя, достаточно добавить к имени
@
, например так:joe@
. Получив такое имя, сервер отбросит@
, и будет идентифицировать пользователя по начальному имени.Параметр
db_user_namespace
порождает расхождение между именами пользователей на стороне сервера и клиента. Но проверки подлинности всегда выполняются с именем с точки зрения сервера, так что, настраивая аутентификацию, следует указывать серверное представление имени, а не клиентское. Так как метод аутентификацииmd5
подмешивает имя пользователя в качестве соли и на стороне сервера, и на стороне клиента, при включённом параметреdb_user_namespace
использоватьmd5
невозможно.Примечание
Эта возможность предлагается в качестве временной меры, пока не будет найдено полноценное решение. Тогда этот параметр будет ликвидирован.
20.3. Connections and Authentication
20.3.1. Connection Settings
listen_addresses
(string
)Specifies the TCP/IP address(es) on which the server is to listen for connections from client applications. The value takes the form of a comma-separated list of host names and/or numeric IP addresses. The special entry
*
corresponds to all available IP interfaces. The entry0.0.0.0
allows listening for all IPv4 addresses and::
allows listening for all IPv6 addresses. If the list is empty, the server does not listen on any IP interface at all, in which case only Unix-domain sockets can be used to connect to it. If the list is not empty, the server will start if it can listen on at least one TCP/IP address. A warning will be emitted for any TCP/IP address which cannot be opened. The default value is localhost, which allows only local TCP/IP “loopback” connections to be made.While client authentication (Chapter 21) allows fine-grained control over who can access the server,
listen_addresses
controls which interfaces accept connection attempts, which can help prevent repeated malicious connection requests on insecure network interfaces. This parameter can only be set at server start.port
(integer
)The TCP port the server listens on; 5432 by default. Note that the same port number is used for all IP addresses the server listens on. This parameter can only be set at server start.
max_connections
(integer
)Determines the maximum number of concurrent connections to the database server. The default is typically 100 connections, but might be less if your kernel settings will not support it (as determined during initdb). This parameter can only be set at server start.
When running a standby server, you must set this parameter to the same or higher value than on the primary server. Otherwise, queries will not be allowed in the standby server.
superuser_reserved_connections
(integer
)Determines the number of connection “slots” that are reserved for connections by PostgreSQL superusers. At most max_connections connections can ever be active simultaneously. Whenever the number of active concurrent connections is at least
max_connections
minussuperuser_reserved_connections
, new connections will be accepted only for superusers, and no new replication connections will be accepted.The default value is three connections. The value must be less than
max_connections
. This parameter can only be set at server start.unix_socket_directories
(string
)Specifies the directory of the Unix-domain socket(s) on which the server is to listen for connections from client applications. Multiple sockets can be created by listing multiple directories separated by commas. Whitespace between entries is ignored; surround a directory name with double quotes if you need to include whitespace or commas in the name. An empty value specifies not listening on any Unix-domain sockets, in which case only TCP/IP sockets can be used to connect to the server.
A value that starts with
@
specifies that a Unix-domain socket in the abstract namespace should be created (currently supported on Linux only). In that case, this value does not specify a “directory” but a prefix from which the actual socket name is computed in the same manner as for the file-system namespace. While the abstract socket name prefix can be chosen freely, since it is not a file-system location, the convention is to nonetheless use file-system-like values such as@/tmp
.The default value is normally
/tmp
, but that can be changed at build time. On Windows, the default is empty, which means no Unix-domain socket is created by default. This parameter can only be set at server start.In addition to the socket file itself, which is named
.s.PGSQL.
wherennnn
nnnn
is the server's port number, an ordinary file named.s.PGSQL.
will be created in each of thennnn
.lockunix_socket_directories
directories. Neither file should ever be removed manually. For sockets in the abstract namespace, no lock file is created.unix_socket_group
(string
)Sets the owning group of the Unix-domain socket(s). (The owning user of the sockets is always the user that starts the server.) In combination with the parameter
unix_socket_permissions
this can be used as an additional access control mechanism for Unix-domain connections. By default this is the empty string, which uses the default group of the server user. This parameter can only be set at server start.This parameter is not supported on Windows. Any setting will be ignored. Also, sockets in the abstract namespace have no file owner, so this setting is also ignored in that case.
unix_socket_permissions
(integer
)Sets the access permissions of the Unix-domain socket(s). Unix-domain sockets use the usual Unix file system permission set. The parameter value is expected to be a numeric mode specified in the format accepted by the
chmod
andumask
system calls. (To use the customary octal format the number must start with a0
(zero).)The default permissions are
0777
, meaning anyone can connect. Reasonable alternatives are0770
(only user and group, see alsounix_socket_group
) and0700
(only user). (Note that for a Unix-domain socket, only write permission matters, so there is no point in setting or revoking read or execute permissions.)This access control mechanism is independent of the one described in Chapter 21.
This parameter can only be set at server start.
This parameter is irrelevant on systems, notably Solaris as of Solaris 10, that ignore socket permissions entirely. There, one can achieve a similar effect by pointing
unix_socket_directories
to a directory having search permission limited to the desired audience.Sockets in the abstract namespace have no file permissions, so this setting is also ignored in that case.
bonjour
(boolean
)Enables advertising the server's existence via Bonjour. The default is off. This parameter can only be set at server start.
bonjour_name
(string
)Specifies the Bonjour service name. The computer name is used if this parameter is set to the empty string
''
(which is the default). This parameter is ignored if the server was not compiled with Bonjour support. This parameter can only be set at server start.tcp_keepalives_idle
(integer
)Specifies the amount of time with no network activity after which the operating system should send a TCP keepalive message to the client. If this value is specified without units, it is taken as seconds. A value of 0 (the default) selects the operating system's default. This parameter is supported only on systems that support
TCP_KEEPIDLE
or an equivalent socket option, and on Windows; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.Note
On Windows, setting a value of 0 will set this parameter to 2 hours, since Windows does not provide a way to read the system default value.
tcp_keepalives_interval
(integer
)Specifies the amount of time after which a TCP keepalive message that has not been acknowledged by the client should be retransmitted. If this value is specified without units, it is taken as seconds. A value of 0 (the default) selects the operating system's default. This parameter is supported only on systems that support
TCP_KEEPINTVL
or an equivalent socket option, and on Windows; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.Note
On Windows, setting a value of 0 will set this parameter to 1 second, since Windows does not provide a way to read the system default value.
tcp_keepalives_count
(integer
)Specifies the number of TCP keepalive messages that can be lost before the server's connection to the client is considered dead. A value of 0 (the default) selects the operating system's default. This parameter is supported only on systems that support
TCP_KEEPCNT
or an equivalent socket option; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.Note
This parameter is not supported on Windows, and must be zero.
tcp_user_timeout
(integer
)Specifies the amount of time that transmitted data may remain unacknowledged before the TCP connection is forcibly closed. If this value is specified without units, it is taken as milliseconds. A value of 0 (the default) selects the operating system's default. This parameter is supported only on systems that support
TCP_USER_TIMEOUT
; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.Note
This parameter is not supported on Windows, and must be zero.
client_connection_check_interval
(integer
)Sets the time interval between optional checks that the client is still connected, while running queries. The check is performed by polling the socket, and allows long running queries to be aborted sooner if the kernel reports that the connection is closed.
This option is currently available only on systems that support the non-standard
POLLRDHUP
extension to thepoll
system call, including Linux.If the value is specified without units, it is taken as milliseconds. The default value is
0
, which disables connection checks. Without connection checks, the server will detect the loss of the connection only at the next interaction with the socket, when it waits for, receives or sends data.For the kernel itself to detect lost TCP connections reliably and within a known timeframe in all scenarios including network failure, it may also be necessary to adjust the TCP keepalive settings of the operating system, or the tcp_keepalives_idle, tcp_keepalives_interval and tcp_keepalives_count settings of PostgreSQL.
20.3.2. Authentication
authentication_timeout
(integer
)Maximum amount of time allowed to complete client authentication. If a would-be client has not completed the authentication protocol in this much time, the server closes the connection. This prevents hung clients from occupying a connection indefinitely. If this value is specified without units, it is taken as seconds. The default is one minute (
1m
). This parameter can only be set in thepostgresql.conf
file or on the server command line.password_encryption
(enum
)When a password is specified in CREATE ROLE or ALTER ROLE, this parameter determines the algorithm to use to encrypt the password. Possible values are
scram-sha-256
, which will encrypt the password with SCRAM-SHA-256, andmd5
, which stores the password as an MD5 hash. The default isscram-sha-256
.Note that older clients might lack support for the SCRAM authentication mechanism, and hence not work with passwords encrypted with SCRAM-SHA-256. See Section 21.5 for more details.
krb_server_keyfile
(string
)Sets the location of the server's Kerberos key file. The default is
FILE:/usr/local/pgsql/etc/krb5.keytab
(where the directory part is whatever was specified assysconfdir
at build time; usepg_config --sysconfdir
to determine that). If this parameter is set to an empty string, it is ignored and a system-dependent default is used. This parameter can only be set in thepostgresql.conf
file or on the server command line. See Section 21.6 for more information.krb_caseins_users
(boolean
)Sets whether GSSAPI user names should be treated case-insensitively. The default is
off
(case sensitive). This parameter can only be set in thepostgresql.conf
file or on the server command line.db_user_namespace
(boolean
)This parameter enables per-database user names. It is off by default. This parameter can only be set in the
postgresql.conf
file or on the server command line.If this is on, you should create users as
username@dbname
. Whenusername
is passed by a connecting client,@
and the database name are appended to the user name and that database-specific user name is looked up by the server. Note that when you create users with names containing@
within the SQL environment, you will need to quote the user name.With this parameter enabled, you can still create ordinary global users. Simply append
@
when specifying the user name in the client, e.g.,joe@
. The@
will be stripped off before the user name is looked up by the server.db_user_namespace
causes the client's and server's user name representation to differ. Authentication checks are always done with the server's user name so authentication methods must be configured for the server's user name, not the client's. Becausemd5
uses the user name as salt on both the client and server,md5
cannot be used withdb_user_namespace
.Note
This feature is intended as a temporary measure until a complete solution is found. At that time, this option will be removed.
20.3.3. SSL
See Section 19.9 for more information about setting up SSL.
ssl
(boolean
)Enables SSL connections. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isoff
.ssl_ca_file
(string
)Specifies the name of the file containing the SSL server certificate authority (CA). Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default is empty, meaning no CA file is loaded, and client certificate verification is not performed.ssl_cert_file
(string
)Specifies the name of the file containing the SSL server certificate. Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isserver.crt
.ssl_crl_file
(string
)Specifies the name of the file containing the SSL client certificate revocation list (CRL). Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default is empty, meaning no CRL file is loaded (unless ssl_crl_dir is set).ssl_crl_dir
(string
)Specifies the name of the directory containing the SSL client certificate revocation list (CRL). Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default is empty, meaning no CRLs are used (unless ssl_crl_file is set).The directory needs to be prepared with the OpenSSL command
openssl rehash
orc_rehash
. See its documentation for details.When using this setting, CRLs in the specified directory are loaded on-demand at connection time. New CRLs can be added to the directory and will be used immediately. This is unlike ssl_crl_file, which causes the CRL in the file to be loaded at server start time or when the configuration is reloaded. Both settings can be used together.
ssl_key_file
(string
)Specifies the name of the file containing the SSL server private key. Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isserver.key
.ssl_ciphers
(string
)Specifies a list of SSL cipher suites that are allowed to be used by SSL connections. See the ciphers manual page in the OpenSSL package for the syntax of this setting and a list of supported values. Only connections using TLS version 1.2 and lower are affected. There is currently no setting that controls the cipher choices used by TLS version 1.3 connections. The default value is
HIGH:MEDIUM:+3DES:!aNULL
. The default is usually a reasonable choice unless you have specific security requirements.This parameter can only be set in the
postgresql.conf
file or on the server command line.Explanation of the default value:
HIGH
Cipher suites that use ciphers from
HIGH
group (e.g., AES, Camellia, 3DES)MEDIUM
Cipher suites that use ciphers from
MEDIUM
group (e.g., RC4, SEED)+3DES
The OpenSSL default order for
HIGH
is problematic because it orders 3DES higher than AES128. This is wrong because 3DES offers less security than AES128, and it is also much slower.+3DES
reorders it after all otherHIGH
andMEDIUM
ciphers.!aNULL
Disables anonymous cipher suites that do no authentication. Such cipher suites are vulnerable to MITM attacks and therefore should not be used.
Available cipher suite details will vary across OpenSSL versions. Use the command
openssl ciphers -v 'HIGH:MEDIUM:+3DES:!aNULL'
to see actual details for the currently installed OpenSSL version. Note that this list is filtered at run time based on the server key type.ssl_prefer_server_ciphers
(boolean
)Specifies whether to use the server's SSL cipher preferences, rather than the client's. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default ison
.PostgreSQL versions before 9.4 do not have this setting and always use the client's preferences. This setting is mainly for backward compatibility with those versions. Using the server's preferences is usually better because it is more likely that the server is appropriately configured.
ssl_ecdh_curve
(string
)Specifies the name of the curve to use in ECDH key exchange. It needs to be supported by all clients that connect. It does not need to be the same curve used by the server's Elliptic Curve key. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isprime256v1
.OpenSSL names for the most common curves are:
prime256v1
(NIST P-256),secp384r1
(NIST P-384),secp521r1
(NIST P-521). The full list of available curves can be shown with the commandopenssl ecparam -list_curves
. Not all of them are usable in TLS though.ssl_min_protocol_version
(enum
)Sets the minimum SSL/TLS protocol version to use. Valid values are currently:
TLSv1
,TLSv1.1
,TLSv1.2
,TLSv1.3
. Older versions of the OpenSSL library do not support all values; an error will be raised if an unsupported setting is chosen. Protocol versions before TLS 1.0, namely SSL version 2 and 3, are always disabled.The default is
TLSv1.2
, which satisfies industry best practices as of this writing.This parameter can only be set in the
postgresql.conf
file or on the server command line.ssl_max_protocol_version
(enum
)Sets the maximum SSL/TLS protocol version to use. Valid values are as for ssl_min_protocol_version, with addition of an empty string, which allows any protocol version. The default is to allow any version. Setting the maximum protocol version is mainly useful for testing or if some component has issues working with a newer protocol.
This parameter can only be set in the
postgresql.conf
file or on the server command line.ssl_dh_params_file
(string
)Specifies the name of the file containing Diffie-Hellman parameters used for so-called ephemeral DH family of SSL ciphers. The default is empty, in which case compiled-in default DH parameters used. Using custom DH parameters reduces the exposure if an attacker manages to crack the well-known compiled-in DH parameters. You can create your own DH parameters file with the command
openssl dhparam -out dhparams.pem 2048
.This parameter can only be set in the
postgresql.conf
file or on the server command line.ssl_passphrase_command
(string
)Sets an external command to be invoked when a passphrase for decrypting an SSL file such as a private key needs to be obtained. By default, this parameter is empty, which means the built-in prompting mechanism is used.
The command must print the passphrase to the standard output and exit with code 0. In the parameter value,
%p
is replaced by a prompt string. (Write%%
for a literal%
.) Note that the prompt string will probably contain whitespace, so be sure to quote adequately. A single newline is stripped from the end of the output if present.The command does not actually have to prompt the user for a passphrase. It can read it from a file, obtain it from a keychain facility, or similar. It is up to the user to make sure the chosen mechanism is adequately secure.
This parameter can only be set in the
postgresql.conf
file or on the server command line.ssl_passphrase_command_supports_reload
(boolean
)This parameter determines whether the passphrase command set by
ssl_passphrase_command
will also be called during a configuration reload if a key file needs a passphrase. If this parameter is off (the default), thenssl_passphrase_command
will be ignored during a reload and the SSL configuration will not be reloaded if a passphrase is needed. That setting is appropriate for a command that requires a TTY for prompting, which might not be available when the server is running. Setting this parameter to on might be appropriate if the passphrase is obtained from a file, for example.This parameter can only be set in the
postgresql.conf
file or on the server command line.