天天看點

PostgreSQL ident和peer基于作業系統使用者的認證

postgresql支援的認證方法非常多,除了自身的密碼認證以外,還支援很多其他認證服務。

詳見

<a href="https://www.postgresql.org/docs/9.6/static/auth-methods.html">https://www.postgresql.org/docs/9.6/static/auth-methods.html</a>

本文主要給大家講一下ident認證和peer認證。

這兩種認證方法的目的是擷取用戶端連接配接資料庫的作業系統使用者,檢查map中是否存在,判斷是否允許連接配接資料庫。

ident 認證,用戶端和資料庫建立tcp會話後(假設會話的連接配接資訊是client_ip:12345 &lt;-&gt; db_ip:5432),資料庫通過ident協定詢問用戶端所在ip位址的ident server (預設是113監聽端口),詢問内容:使用client_ip:12345端口連接配接db_ip:5432的作業系統使用者是誰?

協定可以參考一下rfc 文檔。

如圖:

PostgreSQL ident和peer基于作業系統使用者的認證

peer認證,目的和ident認證一樣,都是要拿到用戶端的作業系統使用者名,隻不過peer對應的是unix socket連接配接(用戶端和資料庫在同一個作業系統中),是以是通過系統調用來擷取用戶端的使用者名,系統調用是getpeereid().

PostgreSQL ident和peer基于作業系統使用者的認證

在擷取到用戶端的os使用者名之後,postgresql會通過pg_hba.conf中配置的map名與pg_ident.conf中配置的映射關系,以及用戶端提供的資料庫使用者名,判斷是否允許登陸資料庫。

如圖

PostgreSQL ident和peer基于作業系統使用者的認證

我這裡舉一個peer認證的例子

這個配置的含義:

當用戶端使用unix socket連接配接資料庫時,使用ident認證。 當用戶端的os使用者是digoal時,允許它以資料庫使用者postgres連接配接資料庫。

當連接配接的資料庫使用者不在map中時,報錯。

pg_ident.conf還支援規則表達式,具體用法見

<a href="https://www.postgresql.org/docs/9.6/static/auth-username-maps.html">https://www.postgresql.org/docs/9.6/static/auth-username-maps.html</a>

<a href="https://www.postgresql.org/docs/9.6/static/functions-matching.html#posix-syntax-details">https://www.postgresql.org/docs/9.6/static/functions-matching.html#posix-syntax-details</a>

ident的方法略複雜,需要在用戶端部署ident server,可參考以下文檔進行配置

<a href="https://wiki.archlinux.org/index.php/identd_setup">https://wiki.archlinux.org/index.php/identd_setup</a>

ident針對tcp會話,即通過tcp連接配接資料庫時。

peer針對unix socket會話,即通過unix socket 連接配接資料庫時。

如果你的主機是資料庫和其他業務共用,或者你不太相信你的os環境的話,如何加強你的資料庫呢?

假設root使用者是可信任的,啟動資料庫的digoal使用者是可信任的,你可以這樣加強。

禁止所有的trust認證,同時對root和digoal使用者,使用peer認證方法。

其他使用者要連,對不起,不允許,請提供密碼。

(這種加強,僅僅針對不能修改pg_hba.conf的使用者,是以說root和啟動資料庫的使用者必須是可信任的)

例子

.1. 使用某個非啟動資料庫的普通使用者通過unix socket連接配接并監控資料庫。

root 超級使用者

digoal 啟動資料庫的使用者

nobody 某監控使用者(沒有login shell,不允許登陸)

配置

監控腳本示例

以nobody使用者運作監控腳本

<a href="https://www.postgresql.org/docs/9.6/static/auth-methods.html#auth-ident">https://www.postgresql.org/docs/9.6/static/auth-methods.html#auth-ident</a>