
Google Authenticator是提供一次性密碼的產生器App, 支援各種智慧型手機作業系統, 例如iOS與Android...等, 運用在二步驗證是極為方便的工具, Google也推出PAM(Pluggable Authentication Modules)的函式庫讓開發者或管理員應用在需要用戶驗證之處, 最多的應用像是SSH登入遠端主機使用Google Authenticator做二步驗證, 就是使用Google Authenticator PAM函式庫來達成。
本文將實作Nginx網站伺服器使用第三方模組ngx_http_auth_pam_module, 來使用Google Authenticator PAM函式庫達成開啟網站的HTTP驗證, 其實Apache網站伺服器早已直接支援Google Authenticator。
我使用VMWare建立一台Debian 8.7 Linux主機, 並且安裝編譯程式所需要工具與函式庫。Nginx的原始碼請到Nginx官方網站下載網頁取得!
下載Nginx
wget https://nginx.org/download/nginx-1.11.8.tar.gz
將原始碼壓縮檔解開, 會在您的下載目錄產生一的名為"nginx-1.11.8"的子目錄
tar zxvf nginx-1.11.8.tar.gz
進入Nginx子目錄
cd nginx-1.11.8
取得ngx_http_auth_pam_module, 官網位於https://github.com/sto/ngx_http_auth_pam_module
wget https://github.com/sto/ngx_http_auth_pam_module/archive/master.zip
將ngx_http_auth_pam_module解壓縮, 會產生"ngx_http_auth_pam_module-master"目錄
unzip master.zip
接著開始編譯Nginx, 也把ngx_http_auth_pam_module編譯進去
./configure --add-module=ngx_http_auth_pam_module-master
make
make install
過程中您可能會遇上缺少函式庫的問題而無法完成configure, 依照缺少的函式庫在Debian網站搜尋與安裝即可解決!
Nginx預設會安裝到/usr/local/nginx目錄下, /usr/local/nginx/conf子目錄下有個nginx.conf是設定檔, 稍後需要更動它, 而網站根目錄則是/usr/local/nginx/html, 請依照您自己的需求修改nginx.conf
安裝Google Authenticator PAM函式庫
apt-get install libpam-google-authenticator
我這裡預先建立了兩個用戶帳號在主機裡, 執行google-authenticator產生QR Code, 請打開Google Authenticator App將QR Code掃進去。

首先是範例用目名"john", 產生他的QR Code


同樣對用戶mary產生QR Code

完成範例兩個帳號, 處理PAM這端的設定
建立驗證檔目錄
mkdir /var/lib/google-authenticator
建立nginx的PAM設定
nano /etc/pam.d/nginx
將以下設定值貼上並儲存/etc/pam.d/nginx
auth required pam_google_authenticator.so nullok user=root secret=/var/lib/google-authenticator/${USER}

把john與mary的".google_authenticator"複製到驗證檔目錄
cd /var/lib/google-authenticator
cp /home/john/.google_authenticator john
cp /home/mary/.google_authenticator mary
檔案必須僅有root可以存取
修改Nginx
nano /usr/local/nginx/conf/nginx.conf
Nginx的執行身分得改成root
user root root;
增加PAM驗證, auth_pam_service_name "nginx"這個設定值就是指/etc/pam.d/nginx檔案
location / {
auth_pam "Secure Zone";
auth_pam_service_name "nginx";
root html;
index index.html index.htm;
}
啟動Nginx網站伺服器
/usr/local/nginx/sbin/nginx

使用瀏覽器開啟網站, 會詢問用戶名稱與密碼, 輸入名稱與Google Authenticator App所產生的密碼

成功的登入了

換另一個帳號mary, 同樣Google Authenticator App所產生的密碼

也能登入!
以上是Nginx + PAM + Google Authenticator用在網站HTTP驗證的方法, 不過還是希望有人會寫Nginx直接支援Google Authenticator的模組, 這種做法實在有點複雜
