Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
當用戶端應用程序連線到資料庫伺服器時,它將指定要連線的 PostgreSQL 資料庫使用者名稱,這與以特定使用者身份登入到 Unix 伺服器的方式大致相同。在 SQL 環境中,有效的資料庫使用者名確定資料庫物件的存取權限 - 有關詳細訊息,請參閱第 21 章。因此,限制哪些資料庫使用者可以進行連線是非常重要的。
正如第 21 章所描述的,PostgreSQL 實際上是以「角色」的角度來管理權限的。在本章中,我們一直使用資料庫使用者來表示「具有 LOGIN 權限的角色」。
身份驗證是資料庫伺服器建立用戶端身份的過程,延伸確認用戶端應用程序(或執行用戶端應用程序的使用者)是否被允許以請求的資料庫使用者名稱進行連線。
PostgreSQL 提供了許多不同的用戶端身份驗證方法。用於驗證特定用戶端連線的方法可以根據(用戶端)主機位址、資料庫名稱和使用者名稱進行驗證。
PostgreSQL 資料庫使用者名稱在邏輯上與運行服務器的作業系統的使用者名稱是分開的。如果特定伺服器的所有用戶在伺服器的機器上也有帳戶,那麼分配與其作業系統用戶名搭配的資料庫用戶名是有意義的。但是,接受遠端連線的伺服器可能有許多沒有本地作業系統帳戶的資料庫用戶,在這種情況下,資料庫用戶名和作業系統用戶名之間不需要有所關連。
There are several password-based authentication methods. These methods operate similarly but differ in how the users' passwords are stored on the server and how the password provided by a client is sent across the connection.
scram-sha-256
The method scram-sha-256
performs SCRAM-SHA-256 authentication, as described in RFC 7677. It is a challenge-response scheme that prevents password sniffing on untrusted connections and supports storing passwords on the server in a cryptographically hashed form that is thought to be secure.
This is the most secure of the currently provided methods, but it is not supported by older client libraries.
md5
The method md5
uses a custom less secure challenge-response mechanism. It prevents password sniffing and avoids storing passwords on the server in plain text but provides no protection if an attacker manages to steal the password hash from the server. Also, the MD5 hash algorithm is nowadays no longer considered secure against determined attacks.
The md5
method cannot be used with the db_user_namespace feature.
To ease transition from the md5
method to the newer SCRAM method, if md5
is specified as a method in pg_hba.conf
but the user's password on the server is encrypted for SCRAM (see below), then SCRAM-based authentication will automatically be chosen instead.
password
The method password
sends the password in clear-text and is therefore vulnerable to password “sniffing” attacks. It should always be avoided if possible. If the connection is protected by SSL encryption then password
can be used safely, though. (Though SSL certificate authentication might be a better choice if one is depending on using SSL).
PostgreSQL database passwords are separate from operating system user passwords. The password for each database user is stored in the pg_authid
system catalog. Passwords can be managed with the SQL commands CREATE ROLE and ALTER ROLE, e.g., CREATE ROLE foo WITH LOGIN PASSWORD 'secret'
, or the psql command \password
. If no password has been set up for a user, the stored password is null and password authentication will always fail for that user.
The availability of the different password-based authentication methods depends on how a user's password on the server is encrypted (or hashed, more accurately). This is controlled by the configuration parameter password_encryption at the time the password is set. If a password was encrypted using the scram-sha-256
setting, then it can be used for the authentication methods scram-sha-256
and password
(but password transmission will be in plain text in the latter case). The authentication method specification md5
will automatically switch to using the scram-sha-256
method in this case, as explained above, so it will also work. If a password was encrypted using the md5
setting, then it can be used only for the md5
and password
authentication method specifications (again, with the password transmitted in plain text in the latter case). (Previous PostgreSQL releases supported storing the password on the server in plain text. This is no longer possible.) To check the currently stored password hashes, see the system catalog pg_authid
.
To upgrade an existing installation from md5
to scram-sha-256
, after having ensured that all client libraries in use are new enough to support SCRAM, set password_encryption = 'scram-sha-256'
in postgresql.conf
, make all users set new passwords, and change the authentication method specifications in pg_hba.conf
to scram-sha-256
.
When using an external authentication system such as Ident or GSSAPI, the name of the operating system user that initiated the connection might not be the same as the database user (role) that is to be used. In this case, a user name map can be applied to map the operating system user name to a database user. To use user name mapping, specify map
=map-name
in the options field in pg_hba.conf
. This option is supported for all authentication methods that receive external user names. Since different mappings might be needed for different connections, the name of the map to be used is specified in the map-name
parameter in pg_hba.conf
to indicate which map to use for each individual connection.
User name maps are defined in the ident map file, which by default is named pg_ident.conf
and is stored in the cluster's data directory. (It is possible to place the map file elsewhere, however; see the ident_file configuration parameter.) The ident map file contains lines of the general form:
Comments and whitespace are handled in the same way as in pg_hba.conf
. The map-name
is an arbitrary name that will be used to refer to this mapping in pg_hba.conf
. The other two fields specify an operating system user name and a matching database user name. The same map-name
can be used repeatedly to specify multiple user-mappings within a single map.
There is no restriction regarding how many database users a given operating system user can correspond to, nor vice versa. Thus, entries in a map should be thought of as meaning “this operating system user is allowed to connect as this database user”, rather than implying that they are equivalent. The connection will be allowed if there is any map entry that pairs the user name obtained from the external authentication system with the database user name that the user has requested to connect as.
If the system-username
field starts with a slash (/
), the remainder of the field is treated as a regular expression. (See Section 9.7.3.1 for details of PostgreSQL's regular expression syntax.) The regular expression can include a single capture, or parenthesized subexpression, which can then be referenced in the database-username
field as \1
(backslash-one). This allows the mapping of multiple user names in a single line, which is particularly useful for simple syntax substitutions. For example, these entries
will remove the domain part for users with system user names that end with @mydomain.com
, and allow any user whose system name ends with @otherdomain.com
to log in as guest
.
Keep in mind that by default, a regular expression can match just part of a string. It's usually wise to use ^
and $
, as shown in the above example, to force the match to be to the entire system user name.
The pg_ident.conf
file is read on start-up and when the main server process receives a SIGHUP signal. If you edit the file on an active system, you will need to signal the postmaster (using pg_ctl reload
, calling the SQL function pg_reload_conf()
, or using kill -HUP
) to make it re-read the file.
A pg_ident.conf
file that could be used in conjunction with the pg_hba.conf
file in Example 20.1 is shown in Example 20.2. In this example, anyone logged in to a machine on the 192.168 network that does not have the operating system user name bryanh
, ann
, or robert
would not be granted access. Unix user robert
would only be allowed access when he tries to connect as PostgreSQL user bob
, not as robert
or anyone else. ann
would only be allowed to connect as ann
. User bryanh
would be allowed to connect as either bryanh
or as guest1
.
Example 20.2. An Example pg_ident.conf
File
用戶端身份驗證由組態檔案控制,組態檔案通常名稱為 pg_hba.conf,並儲存在資料庫叢集的資料目錄中。 (HBA 代表 host-based authentication。)當 initdb 初始化資料目錄時,將安裝預設的 pg_hba.conf 檔案。但是,可以將身份驗證組態檔案放在其他路徑;請參閱 hba_file 組態參數。
pg_hba.conf 檔案的一般格式是一組記錄,每行一個。空白行將被忽略,# comment 字元後面的任何文字都將被忽略。記錄不能跨行。記錄由許多段落組成,這些段落由空格或 tab 分隔。如果段落的值用了雙引號,則段落可以包含空格。在資料庫,使用者或位址段落(例如,all 或 replication)中括起其中一個關鍵字會使該字失去其特殊含義,並且只是將資料庫,使用者或主機與該名稱相匹配。
每條記錄指定連線類型,用戶端 IP 位址範圍(如果與連線類型相關)、資料庫名稱、使用者名稱以及符合這些參數的連線身份驗證方法。具有符合的連線類型、用戶端位址、要求的資料庫和使用者名稱的第一個記錄用於執行身份驗證。沒有“fall-through”或“replication”:如果選擇了一條記錄而認證失敗,就不再考慮後續記錄。如果沒有記錄匹配,則拒絕存取。
記錄可以是下面的七種格式之一
段落的含義如下:
local
此記錄搭配使用 Unix-domain socket 的連線嘗試。如果沒有此類型的記錄,則不允許使用 Unix-domain socket 連線。
host
此記錄用於使用 TCP/IP 進行的連線嘗試。主機記錄使用 SSL 或非 SSL 連線嘗試.
重要 除非使用 listen_addresses 組態參數的適當值啟動伺服器,否則將無法進行遠端 TCP/IP 連線,因為預設行為是僅在 localhost 上監聽 TCP/IP 連線。
hostssl
此記錄會套用於使用 TCP/IP 進行的連線嘗試,但僅限於使用 SSL 加密進行連線時。
要使用此選項,必須以 SSL 建置伺服器,也必須透過設定 ssl 組態參數來啟用 SSL(有關更多訊息,請參閱第 18.9 節)。否則,將會忽略 hostssl 記錄,除非是為了記錄不能與任何連線相符合的警告。
hostnossl
此記錄類型與 hostssl 具有相反的行為;它僅套用於透過 TCP/IP 且不使用 SSL 的連線嘗試。
database
指定此記錄所要求搭配的資料庫名稱。值 all 使其搭配所有資料庫。如果請求的資料庫與請求的使用者具有相同的名稱,則可以用 sameuser 值來指定。值 samerole 指定所請求的使用者必須是與請求的資料庫同名的角色成員。 ( samegroup 是一個過時但仍然被接受的 samerole 別名。)超級使用者不被認為是同一角色的成員,除非他們直接或間接地明確地成為角色的成員,而不僅僅是作為超級使用者。值 replication 指定在請求 physical replication 連線時的記錄搭配(請注意,複寫連線不指定任何特定資料庫)。否則,這是特定 PostgreSQL 資料庫的名稱。可以透過用逗號分隔它們來設定多個資料庫名稱,也可以透過在檔案名稱前加上 @ 來指定包含資料庫名稱的額外檔案。
user
指定此記錄所限制的資料庫使用者名稱。all 表示所有使用者都適用。否則,它就是是特定資料庫使用者的名稱,要就是帶有 + 的群組名稱。(回想一下,PostgreSQL 中的使用者和群組之間並沒有真正的差別; + 標記實際上表示「符合直接或間接地成為該角色成員的任何角色」,而沒有 + 標記的名稱僅適用該特定角色。 )為此,只有超級使用者直接或間接明確地是角色的成員,而不僅僅是憑藉超級使用者,才將其視為角色的成員。可以使用逗號分隔多個使用者名稱。透過在檔案名稱前面加上 @ 來指定包含使用者名稱的獨立設定檔案。
address
Specifies the client machine address(es) that this record matches. This field can contain either a host name, an IP address range, or one of the special key words mentioned below.
An IP address range is specified using standard numeric notation for the range's starting address, then a slash (/
) and a CIDR mask length. The mask length indicates the number of high-order bits of the client IP address that must match. Bits to the right of this should be zero in the given IP address. There must not be any white space between the IP address, the /
, and the CIDR mask length.
Typical examples of an IPv4 address range specified this way are 172.20.143.89/32
for a single host, or 172.20.143.0/24
for a small network, or 10.6.0.0/16
for a larger one. An IPv6 address range might look like ::1/128
for a single host (in this case the IPv6 loopback address) or fe80::7a31:c1ff:0000:0000/96
for a small network. 0.0.0.0/0
represents all IPv4 addresses, and ::0/0
represents all IPv6 addresses. To specify a single host, use a mask length of 32 for IPv4 or 128 for IPv6. In a network address, do not omit trailing zeroes.
An entry given in IPv4 format will match only IPv4 connections, and an entry given in IPv6 format will match only IPv6 connections, even if the represented address is in the IPv4-in-IPv6 range. Note that entries in IPv6 format will be rejected if the system's C library does not have support for IPv6 addresses.
You can also write all
to match any IP address, samehost
to match any of the server's own IP addresses, or samenet
to match any address in any subnet that the server is directly connected to.
If a host name is specified (anything that is not an IP address range or a special key word is treated as a host name), that name is compared with the result of a reverse name resolution of the client's IP address (e.g., reverse DNS lookup, if DNS is used). Host name comparisons are case insensitive. If there is a match, then a forward name resolution (e.g., forward DNS lookup) is performed on the host name to check whether any of the addresses it resolves to are equal to the client's IP address. If both directions match, then the entry is considered to match. (The host name that is used in pg_hba.conf
should be the one that address-to-name resolution of the client's IP address returns, otherwise the line won't be matched. Some host name databases allow associating an IP address with multiple host names, but the operating system will only return one host name when asked to resolve an IP address.)
以點(.)開頭的主機名稱表示與實際主機名稱的後段比對。因此,.example.com 與 foo.example.com 比較是相符的(不僅限於 example.com)。
當在 pg_hba.conf 中指定了主機名稱時,您應該確保名稱解析足夠快。設定本地名稱解析暫存(例如 nscd)可能是有幫助的。另外,您可能希望啟用配置參數 log_hostname 來查看用戶端的主機名稱,而不是日誌中的 IP 位址。
此欄位僅適用於 host、hostssl 和 hostnossl 規則項目。
使用者有時會想知道為什麼以這種看似複雜的方式來處理主機名稱,並具有兩種名稱解析,其中包括對用戶端 IP 地址的反向查詢。如果未設定用戶端的反向 DNS 項目或設定了某些不良的主機名稱,則會使該功能的使用複雜化。這樣做主要是為了提高效率:透過這種方式,連線嘗試最多需要兩次 DNS 查詢,一次反向查詢和一次正向查詢。如果某個位址存在 DNS 問題,則僅成為該使用者的問題。假設僅執行正向查詢的替代實作方式,必須在每次連線嘗試期間解析 pg_hba.conf 中提到的每個主機名稱。 如果列出了許多名稱,那可能會很慢。而且,如果其中一個主機名稱存在有 DNS 問題,那麼它將成為每個人的問題。
另外,必須執行反向查詢以實作後段樣式比對的功能,因為需要知道實際的用戶端主機名稱,以便將其與樣式進行比對。
請注意,此行為與基於主機名稱的存取控制的其他常見的實作方式一致,例如 Apache HTTP Server 和 TCP Wrappers。
IP-address
IP-mask
These two fields can be used as an alternative to the IP-address
/
mask-length
notation. Instead of specifying the mask length, the actual mask is specified in a separate column. For example, 255.0.0.0
represents an IPv4 CIDR mask length of 8, and 255.255.255.255
represents a CIDR mask length of 32.
These fields only apply to host
, hostssl
, and hostnossl
records.
auth-method
Specifies the authentication method to use when a connection matches this record. The possible choices are summarized here; details are in Section 20.3.
trust
無條件地允許連線。此方法允許可以連線到 PostgreSQL 資料庫伺服器的任何人以他們希望的任何 PostgreSQL 使用者身份登入,而毌需密碼或任何其他身份驗證。有關詳細資訊,請參閱第 20.3.1 節。
reject
無條件地拒絕連線。這對於「過濾」群組網路中的某些主機很有用。例如拒絕阻止特定主機的連接,而更前面的規則則允許特定網路中的其餘主機進行連線。
scram-sha-256
Perform SCRAM-SHA-256 authentication to verify the user's password. See Section 20.3.2 for details.
md5
Perform SCRAM-SHA-256 or MD5 authentication to verify the user's password. See Section 20.3.2 for details.
password
Require the client to supply an unencrypted password for authentication. Since the password is sent in clear text over the network, this should not be used on untrusted networks. See Section 20.3.2 for details.
gss
Use GSSAPI to authenticate the user. This is only available for TCP/IP connections. See Section 20.3.3 for details.
sspi
Use SSPI to authenticate the user. This is only available on Windows. See Section 20.3.4 for details.
ident
Obtain the operating system user name of the client by contacting the ident server on the client and check if it matches the requested database user name. Ident authentication can only be used on TCP/IP connections. When specified for local connections, peer authentication will be used instead. See Section 20.3.5 for details.
peer
Obtain the client's operating system user name from the operating system and check if it matches the requested database user name. This is only available for local connections. See Section 20.3.6 for details.
ldap
Authenticate using an LDAP server. See Section 20.3.7 for details.
radius
Authenticate using a RADIUS server. See Section 20.3.8 for details.
cert
Authenticate using SSL client certificates. See Section 20.3.9 for details.
pam
Authenticate using the Pluggable Authentication Modules (PAM) service provided by the operating system. See Section 20.3.10 for details.
bsd
Authenticate using the BSD Authentication service provided by the operating system. See Section 20.3.11 for details.
auth-options
After the auth-method
field, there can be field(s) of the form name
=
value
that specify options for the authentication method. Details about which options are available for which authentication methods appear below.
In addition to the method-specific options listed below, there is one method-independent authentication option clientcert
, which can be specified in any hostssl
record. When set to 1
, this option requires the client to present a valid (trusted) SSL certificate, in addition to the other requirements of the authentication method.
@ 語法結構包含的檔案會被入為名稱列表,可以用空格或逗號分隔。就像在 pg_hba.conf 中一樣,註釋由 # 引入,並且允許巢狀式的 @ 結構。除非 @ 之後的檔案名稱是絕對路徑,否則它將被視為相對於包含引用檔案的目錄。
Since the pg_hba.conf
records are examined sequentially for each connection attempt, the order of the records is significant. Typically, earlier records will have tight connection match parameters and weaker authentication methods, while later records will have looser match parameters and stronger authentication methods. For example, one might wish to use trust
authentication for local TCP/IP connections but require a password for remote TCP/IP connections. In this case a record specifying trust
authentication for connections from 127.0.0.1 would appear before a record specifying password authentication for a wider range of allowed client IP addresses.
The pg_hba.conf
file is read on start-up and when the main server process receives a SIGHUP signal. If you edit the file on an active system, you will need to signal the postmaster (using pg_ctl reload
or kill -HUP
) to make it re-read the file.
前面的宣告在 Microsoft Windows 上是不正確的:在 Windows,pg_hba.conf 檔案中的任何變更都會在後續的新連線立即適用。
系統檢視表 pg_hba_file_rules 有助於預先測試對 pg_hba.conf 檔案的變更,或者在檔案載入未達到預期效果時診斷問題。檢視表中帶有非空白錯誤欄位會指示檔案相應規則項目中的問題。
要連線到特定的資料庫,使用者不僅必須通過 pg_hba.conf 檢查,而且必須具有資料庫的 CONNECT 權限。如果您希望限制哪些使用者可以連接到哪些資料庫,通常比設定 pg_hba.conf 項目更容易,透過授權/撤銷 CONNECT 權限來控制。
Some examples of pg_hba.conf
entries are shown in Example 20.1. See the next section for details on the different authentication methods.
Example 20.1. Example pg_hba.conf
Entries
This authentication method operates similarly to password
except that it uses PAM (Pluggable Authentication Modules) as the authentication mechanism. The default PAM service name is postgresql
. PAM is used only to validate user name/password pairs and optionally the connected remote host name or IP address. Therefore the user must already exist in the database before PAM can be used for authentication. For more information about PAM, please read the Linux-PAM Page.
The following configuration options are supported for PAM:
pamservice
PAM service name.
pam_use_hostname
Determines whether the remote IP address or the host name is provided to PAM modules through the PAM_RHOST
item. By default, the IP address is used. Set this option to 1 to use the resolved host name instead. Host name resolution can lead to login delays. (Most PAM configurations don't use this information, so it is only necessary to consider this setting if a PAM configuration was specifically created to make use of it.)
If PAM is set up to read /etc/shadow
, authentication will fail because the PostgreSQL server is started by a non-root user. However, this is not an issue when PAM is configured to use LDAP or other authentication methods.
此身份驗證方法使用 SSL 用戶端憑證進行身份驗證。因此,它僅適用於 SSL 連線。使用此身份驗證方法時,伺服器將要求用戶端提供有效可信任的憑證。不會有密碼提示發送給用戶端。憑證的 cn(Common Name)屬性將與請求連線的資料庫使用者名稱進行比較,如果符合,則允許登錄。使用者名稱對應可用於允許 cn 與資料庫使用者名稱不同。
SSL 憑證身份驗證支援以下配置選項:
map
允許在系統使用者名稱和資料庫使用者名稱之間進行對應。相關詳細資訊,請參閱。
在指定憑證認證的 pg_hba.conf 記錄中,憑證選項 clientcert 被假設為 verify-ca 或 verify-full,由於此方法需要用戶端憑證,因此無法將其關閉。 cert 方法增加了基本 clientcert 憑證有效性測試的方法是檢查 cn 屬性是否與資料庫使用者名稱相符。
The following subsections describe the authentication methods in more detail.
When trust
authentication is specified, PostgreSQL assumes that anyone who can connect to the server is authorized to access the database with whatever database user name they specify (even superuser names). Of course, restrictions made in the database
and user
columns still apply. This method should only be used when there is adequate operating-system-level protection on connections to the server.
trust
authentication is appropriate and very convenient for local connections on a single-user workstation. It is usually not appropriate by itself on a multiuser machine. However, you might be able to use trust
even on a multiuser machine, if you restrict access to the server's Unix-domain socket file using file-system permissions. To do this, set the unix_socket_permissions
(and possibly unix_socket_group
) configuration parameters as described in Section 19.3. Or you could set the unix_socket_directories
configuration parameter to place the socket file in a suitably restricted directory.
Setting file-system permissions only helps for Unix-socket connections. Local TCP/IP connections are not restricted by file-system permissions. Therefore, if you want to use file-system permissions for local security, remove the host ... 127.0.0.1 ...
line from pg_hba.conf
, or change it to a non-trust
authentication method.
trust
authentication is only suitable for TCP/IP connections if you trust every user on every machine that is allowed to connect to the server by the pg_hba.conf
lines that specify trust
. It is seldom reasonable to use trust
for any TCP/IP connections other than those from localhost (127.0.0.1).
There are several password-based authentication methods. These methods operate similarly but differ in how the users' passwords are stored on the server and how the password provided by a client is sent across the connection.scram-sha-256
The method scram-sha-256
performs SCRAM-SHA-256 authentication, as described in RFC 7677. It is a challenge-response scheme that prevents password sniffing on untrusted connections and supports storing passwords on the server in a cryptographically hashed form that is thought to be secure.
This is the most secure of the currently provided methods, but it is not supported by older client libraries.md5
The method md5
uses a custom less secure challenge-response mechanism. It prevents password sniffing and avoids storing passwords on the server in plain text but provides no protection if an attacker manages to steal the password hash from the server. Also, the MD5 hash algorithm is nowadays no longer considered secure against determined attacks.
The md5
method cannot be used with the db_user_namespace feature.
To ease transition from the md5
method to the newer SCRAM method, if md5
is specified as a method in pg_hba.conf
but the user's password on the server is encrypted for SCRAM (see below), then SCRAM-based authentication will automatically be chosen instead.password
The method password
sends the password in clear-text and is therefore vulnerable to password “sniffing” attacks. It should always be avoided if possible. If the connection is protected by SSL encryption then password
can be used safely, though. (Though SSL certificate authentication might be a better choice if one is depending on using SSL).
PostgreSQL database passwords are separate from operating system user passwords. The password for each database user is stored in the pg_authid
system catalog. Passwords can be managed with the SQL commands CREATE USER and ALTER ROLE, e.g., CREATE USER foo WITH PASSWORD 'secret'
, or the psql command \password
. If no password has been set up for a user, the stored password is null and password authentication will always fail for that user.
The availability of the different password-based authentication methods depends on how a user's password on the server is encrypted (or hashed, more accurately). This is controlled by the configuration parameter password_encryption at the time the password is set. If a password was encrypted using the scram-sha-256
setting, then it can be used for the authentication methods scram-sha-256
and password
(but password transmission will be in plain text in the latter case). The authentication method specification md5
will automatically switch to using the scram-sha-256
method in this case, as explained above, so it will also work. If a password was encrypted using the md5
setting, then it can be used only for the md5
and password
authentication method specifications (again, with the password transmitted in plain text in the latter case). (Previous PostgreSQL releases supported storing the password on the server in plain text. This is no longer possible.) To check the currently stored password hashes, see the system catalog pg_authid
.
To upgrade an existing installation from md5
to scram-sha-256
, after having ensured that all client libraries in use are new enough to support SCRAM, set password_encryption = 'scram-sha-256'
in postgresql.conf
, make all users set new passwords, and change the authentication method specifications in pg_hba.conf
to scram-sha-256
.
GSSAPI is an industry-standard protocol for secure authentication defined in RFC 2743. PostgreSQL supports GSSAPI with Kerberos authentication according to RFC 1964. GSSAPIprovides automatic authentication (single sign-on) for systems that support it. The authentication itself is secure, but the data sent over the database connection will be sent unencrypted unless SSL is used.
GSSAPI support has to be enabled when PostgreSQL is built; see Chapter 16 for more information.
When GSSAPI uses Kerberos, it uses a standard principal in the format servicename
/hostname
@realm
. The PostgreSQL server will accept any principal that is included in the keytab used by the server, but care needs to be taken to specify the correct principal details when making the connection from the client using the krbsrvname
connection parameter. (See also Section 33.1.2.) The installation default can be changed from the default postgres
at build time using ./configure --with-krb-srvnam=
whatever
. In most environments, this parameter never needs to be changed. Some Kerberos implementations might require a different service name, such as Microsoft Active Directory which requires the service name to be in upper case (POSTGRES
).
hostname
is the fully qualified host name of the server machine. The service principal's realm is the preferred realm of the server machine.
Client principals can be mapped to different PostgreSQL database user names with pg_ident.conf
. For example, pgusername@realm
could be mapped to just pgusername
. Alternatively, you can use the full username@realm
principal as the role name in PostgreSQL without any mapping.
PostgreSQL also supports a parameter to strip the realm from the principal. This method is supported for backwards compatibility and is strongly discouraged as it is then impossible to distinguish different users with the same user name but coming from different realms. To enable this, set include_realm
to 0. For simple single-realm installations, doing that combined with setting the krb_realm
parameter (which checks that the principal's realm matches exactly what is in the krb_realm
parameter) is still secure; but this is a less capable approach compared to specifying an explicit mapping in pg_ident.conf
.
Make sure that your server keytab file is readable (and preferably only readable, not writable) by the PostgreSQL server account. (See also Section 18.1.) The location of the key file is specified by the krb_server_keyfile configuration parameter. The default is /usr/local/pgsql/etc/krb5.keytab
(or whatever directory was specified as sysconfdir
at build time). For security reasons, it is recommended to use a separate keytab just for the PostgreSQL server rather than opening up permissions on the system keytab file.
The keytab file is generated by the Kerberos software; see the Kerberos documentation for details. The following example is for MIT-compatible Kerberos 5 implementations:
When connecting to the database make sure you have a ticket for a principal matching the requested database user name. For example, for database user name fred
, principalfred@EXAMPLE.COM
would be able to connect. To also allow principal fred/users.example.com@EXAMPLE.COM
, use a user name map, as described in Section 20.2.
The following configuration options are supported for GSSAPI:include_realm
If set to 0, the realm name from the authenticated user principal is stripped off before being passed through the user name mapping (Section 20.2). This is discouraged and is primarily available for backwards compatibility, as it is not secure in multi-realm environments unless krb_realm
is also used. It is recommended to leave include_realm
set to the default (1) and to provide an explicit mapping in pg_ident.conf
to convert principal names to PostgreSQL user names.map
Allows for mapping between system and database user names. See Section 20.2 for details. For a GSSAPI/Kerberos principal, such as username@EXAMPLE.COM
(or, less commonly,username/hostbased@EXAMPLE.COM
), the user name used for mapping is username@EXAMPLE.COM
(or username/hostbased@EXAMPLE.COM
, respectively), unless include_realm
has been set to 0, in which case username
(or username/hostbased
) is what is seen as the system user name when mapping.krb_realm
Sets the realm to match user principal names against. If this parameter is set, only users of that realm will be accepted. If it is not set, users of any realm can connect, subject to whatever user name mapping is done.
SSPI is a Windows technology for secure authentication with single sign-on. PostgreSQL will use SSPI in negotiate
mode, which will use Kerberos when possible and automatically fall back to NTLM in other cases. SSPI authentication only works when both server and client are running Windows, or, on non-Windows platforms, when GSSAPI is available.
When using Kerberos authentication, SSPI works the same way GSSAPI does; see Section 20.3.3 for details.
The following configuration options are supported for SSPI:include_realm
If set to 0, the realm name from the authenticated user principal is stripped off before being passed through the user name mapping (Section 20.2). This is discouraged and is primarily available for backwards compatibility, as it is not secure in multi-realm environments unless krb_realm
is also used. It is recommended to leave include_realm
set to the default (1) and to provide an explicit mapping in pg_ident.conf
to convert principal names to PostgreSQL user names.compat_realm
If set to 1, the domain's SAM-compatible name (also known as the NetBIOS name) is used for the include_realm
option. This is the default. If set to 0, the true realm name from the Kerberos user principal name is used.
Do not disable this option unless your server runs under a domain account (this includes virtual service accounts on a domain member system) and all clients authenticating through SSPI are also using domain accounts, or authentication will fail.upn_username
If this option is enabled along with compat_realm
, the user name from the Kerberos UPN is used for authentication. If it is disabled (the default), the SAM-compatible user name is used. By default, these two names are identical for new user accounts.
Note that libpq uses the SAM-compatible name if no explicit user name is specified. If you use libpq or a driver based on it, you should leave this option disabled or explicitly specify user name in the connection string.map
Allows for mapping between system and database user names. See Section 20.2 for details. For a SSPI/Kerberos principal, such as username@EXAMPLE.COM
(or, less commonly,username/hostbased@EXAMPLE.COM
), the user name used for mapping is username@EXAMPLE.COM
(or username/hostbased@EXAMPLE.COM
, respectively), unless include_realm
has been set to 0, in which case username
(or username/hostbased
) is what is seen as the system user name when mapping.krb_realm
Sets the realm to match user principal names against. If this parameter is set, only users of that realm will be accepted. If it is not set, users of any realm can connect, subject to whatever user name mapping is done.
The ident authentication method works by obtaining the client's operating system user name from an ident server and using it as the allowed database user name (with an optional user name mapping). This is only supported on TCP/IP connections.
When ident is specified for a local (non-TCP/IP) connection, peer authentication (see Section 20.3.6) will be used instead.
The following configuration options are supported for ident:map
Allows for mapping between system and database user names. See Section 20.2 for details.
The “Identification Protocol” is described in RFC 1413. Virtually every Unix-like operating system ships with an ident server that listens on TCP port 113 by default. The basic functionality of an ident server is to answer questions like “What user initiated the connection that goes out of your port X
and connects to my port Y
?”. Since PostgreSQL knows both X
_and Y
_ when a physical connection is established, it can interrogate the ident server on the host of the connecting client and can theoretically determine the operating system user for any given connection.
The drawback of this procedure is that it depends on the integrity of the client: if the client machine is untrusted or compromised, an attacker could run just about any program on port 113 and return any user name they choose. This authentication method is therefore only appropriate for closed networks where each client machine is under tight control and where the database and system administrators operate in close contact. In other words, you must trust the machine running the ident server. Heed the warning:
Some ident servers have a nonstandard option that causes the returned user name to be encrypted, using a key that only the originating machine's administrator knows. This option must not be used when using the ident server with PostgreSQL, since PostgreSQL does not have any way to decrypt the returned string to determine the actual user name.
The peer authentication method works by obtaining the client's operating system user name from the kernel and using it as the allowed database user name (with optional user name mapping). This method is only supported on local connections.
The following configuration options are supported for peer:map
Allows for mapping between system and database user names. See Section 20.2 for details.
Peer authentication is only available on operating systems providing the getpeereid()
function, the SO_PEERCRED
socket parameter, or similar mechanisms. Currently that includes Linux, most flavors of BSD including macOS, and Solaris.
This authentication method operates similarly to password
except that it uses LDAP as the password verification method. LDAP is used only to validate the user name/password pairs. Therefore the user must already exist in the database before LDAP can be used for authentication.
LDAP authentication can operate in two modes. In the first mode, which we will call the simple bind mode, the server will bind to the distinguished name constructed as prefix
usernamesuffix
. Typically, the prefix
parameter is used to specify cn=
, or DOMAIN
\
in an Active Directory environment. suffix
is used to specify the remaining part of the DN in a non-Active Directory environment.
In the second mode, which we will call the search+bind mode, the server first binds to the LDAP directory with a fixed user name and password, specified with ldapbinddn
and ldapbindpasswd
, and performs a search for the user trying to log in to the database. If no user and password is configured, an anonymous bind will be attempted to the directory. The search will be performed over the subtree at ldapbasedn
, and will try to do an exact match of the attribute specified in ldapsearchattribute
. Once the user has been found in this search, the server disconnects and re-binds to the directory as this user, using the password specified by the client, to verify that the login is correct. This mode is the same as that used by LDAP authentication schemes in other software, such as Apache mod_authnz_ldap
and pam_ldap
. This method allows for significantly more flexibility in where the user objects are located in the directory, but will cause two separate connections to the LDAP server to be made.
The following configuration options are used in both modes:ldapserver
Names or IP addresses of LDAP servers to connect to. Multiple servers may be specified, separated by spaces.ldapport
Port number on LDAP server to connect to. If no port is specified, the LDAP library's default port setting will be used.ldaptls
Set to 1 to make the connection between PostgreSQL and the LDAP server use TLS encryption. Note that this only encrypts the traffic to the LDAP server — the connection to the client will still be unencrypted unless SSL is used.
The following options are used in simple bind mode only:ldapprefix
String to prepend to the user name when forming the DN to bind as, when doing simple bind authentication.ldapsuffix
String to append to the user name when forming the DN to bind as, when doing simple bind authentication.
The following options are used in search+bind mode only:ldapbasedn
Root DN to begin the search for the user in, when doing search+bind authentication.ldapbinddn
DN of user to bind to the directory with to perform the search when doing search+bind authentication.ldapbindpasswd
Password for user to bind to the directory with to perform the search when doing search+bind authentication.ldapsearchattribute
Attribute to match against the user name in the search when doing search+bind authentication. If no attribute is specified, the uid
attribute will be used.ldapurl
An RFC 4516 LDAP URL. This is an alternative way to write some of the other LDAP options in a more compact and standard form. The format is
scope
must be one of base
, one
, sub
, typically the latter. Only one attribute is used, and some other components of standard LDAP URLs such as filters and extensions are not supported.
For non-anonymous binds, ldapbinddn
and ldapbindpasswd
must be specified as separate options.
To use encrypted LDAP connections, the ldaptls
option has to be used in addition to ldapurl
. The ldaps
URL scheme (direct SSL connection) is not supported.
LDAP URLs are currently only supported with OpenLDAP, not on Windows.
It is an error to mix configuration options for simple bind with options for search+bind.
Here is an example for a simple-bind LDAP configuration:
When a connection to the database server as database user someuser
is requested, PostgreSQL will attempt to bind to the LDAP server using the DN cn=someuser, dc=example, dc=net
and the password provided by the client. If that connection succeeds, the database access is granted.
Here is an example for a search+bind configuration:
When a connection to the database server as database user someuser
is requested, PostgreSQL will attempt to bind anonymously (since ldapbinddn
was not specified) to the LDAP server, perform a search for (uid=someuser)
under the specified base DN. If an entry is found, it will then attempt to bind using that found information and the password supplied by the client. If that second connection succeeds, the database access is granted.
Here is the same search+bind configuration written as a URL:
Some other software that supports authentication against LDAP uses the same URL format, so it will be easier to share the configuration.
Since LDAP often uses commas and spaces to separate the different parts of a DN, it is often necessary to use double-quoted parameter values when configuring LDAP options, as shown in the examples.
This authentication method operates similarly to password
except that it uses RADIUS as the password verification method. RADIUS is used only to validate the user name/password pairs. Therefore the user must already exist in the database before RADIUS can be used for authentication.
When using RADIUS authentication, an Access Request message will be sent to the configured RADIUS server. This request will be of type Authenticate Only
, and include parameters for user name
, password
(encrypted) and NAS Identifier
. The request will be encrypted using a secret shared with the server. The RADIUS server will respond to this server with either Access Accept
or Access Reject
. There is no support for RADIUS accounting.
Multiple RADIUS servers can be specified, in which case they will be tried sequentially. If a negative response is received from a server, the authentication will fail. If no response is received, the next server in the list will be tried. To specify multiple servers, put the names within quotes and separate the server names with a comma. If multiple servers are specified, all other RADIUS options can also be given as a comma separate list, to apply individual values to each server. They can also be specified as a single value, in which case this value will apply to all servers.
The following configuration options are supported for RADIUS:radiusservers
The name or IP addresses of the RADIUS servers to connect to. This parameter is required.radiussecrets
The shared secrets used when talking securely to the RADIUS server. This must have exactly the same value on the PostgreSQL and RADIUS servers. It is recommended that this be a string of at least 16 characters. This parameter is required.
The encryption vector used will only be cryptographically strong if PostgreSQL is built with support for OpenSSL. In other cases, the transmission to the RADIUS server should only be considered obfuscated, not secured, and external security measures should be applied if necessary.radiusports
The port number on the RADIUS servers to connect to. If no port is specified, the default port 1812
will be used.radiusidentifiers
The string used as NAS Identifier
in the RADIUS requests. This parameter can be used as a second parameter identifying for example which database user the user is attempting to authenticate as, which can be used for policy matching on the RADIUS server. If no identifier is specified, the default postgresql
will be used.
This authentication method uses SSL client certificates to perform authentication. It is therefore only available for SSL connections. When using this authentication method, the server will require that the client provide a valid, trusted certificate. No password prompt will be sent to the client. The cn
(Common Name) attribute of the certificate will be compared to the requested database user name, and if they match the login will be allowed. User name mapping can be used to allow cn
to be different from the database user name.
The following configuration options are supported for SSL certificate authentication:map
Allows for mapping between system and database user names. See Section 20.2 for details.
In a pg_hba.conf
record specifying certificate authentication, the authentication option clientcert
is assumed to be 1
, and it cannot be turned off since a client certificate is necessary for this method. What the cert
method adds to the basic clientcert
certificate validity test is a check that the cn
attribute matches the database user name.
This authentication method operates similarly to password
except that it uses PAM (Pluggable Authentication Modules) as the authentication mechanism. The default PAM service name is postgresql
. PAM is used only to validate user name/password pairs and optionally the connected remote host name or IP address. Therefore the user must already exist in the database before PAM can be used for authentication. For more information about PAM, please read the Linux-PAM Page.
The following configuration options are supported for PAM:pamservice
PAM service name.pam_use_hostname
Determines whether the remote IP address or the host name is provided to PAM modules through the PAM_RHOST
item. By default, the IP address is used. Set this option to 1 to use the resolved host name instead. Host name resolution can lead to login delays. (Most PAM configurations don't use this information, so it is only necessary to consider this setting if a PAM configuration was specifically created to make use of it.)
If PAM is set up to read /etc/shadow
, authentication will fail because the PostgreSQL server is started by a non-root user. However, this is not an issue when PAM is configured to use LDAP or other authentication methods.
This authentication method operates similarly to password
except that it uses BSD Authentication to verify the password. BSD Authentication is used only to validate user name/password pairs. Therefore the user's role must already exist in the database before BSD Authentication can be used for authentication. The BSD Authentication framework is currently only available on OpenBSD.
BSD Authentication in PostgreSQL uses the auth-postgresql
login type and authenticates with the postgresql
login class if that's defined in login.conf
. By default that login class does not exist, and PostgreSQL will use the default login class.
To use BSD Authentication, the PostgreSQL user account (that is, the operating system user running the server) must first be added to the auth
group. The auth
group exists by default on OpenBSD systems.
The Identification Protocol is not intended as an authorization or access control protocol.
--RFC 1413