浅草橋青空市場

Microsoft Azure のニュースや情報を中心にあれこれと

BASIC認証の代わりにOTPのトークンで認証してみる

せっかくなので、BASIC認証の代わりにOTPのトークンで認証できるように設定してみましょう。

昨日の続きと言えば続き。

asazure.hatenablog.jp

前準備

$ sudo yum install -y httpd httpd-devel
$ sudo yum install -y openssl-devel
$ git clone https://github.com/archiecobbs/mod-authn-otp
$ cd mod-authn-otp
$ ./autogen.sh -c
$ make
$ sudo make install

Apacheにモジュール読み込み

$ sudo vi /etc/httpd/conf.modules.d/00-authn_otp.conf
$ sudo diff /etc/httpd/conf.modules.d/00-authn_otp.conf /etc/httpd/conf.modules.d/00-authn_otp.conf.bak
1,2d0
< LoadModule authn_otp_module   modules/mod_authn_otp.so
$ service httpd configtest
$ sudo systemctl restart httpd

ユーザーファイルを作る

$ vi ~/create_otp_userfile_sh
$ cat ~/create_otp_userfile_sh
#!/bin/bash -e
user=${1:?Usage: $0 username}
issuer=${2:-your_company_name}
secret=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 15 | head -n 1)
secret_base16=$(python -c "import base64; print base64.b16encode('${secret}')")
secret_base32=$(python -c "import base64; print base64.b32encode('${secret}')")
otpauth_uri="otpauth://totp/${issuer}:${user}?secret=${secret_base32}&issuer=${issuer}"
otpauth_uri=$(python -c "import urllib; print urllib.quote('${otpauth_uri}')")
qrcode_url="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=${otpauth_uri}"

file="/var/www/otp/users"
if [ ! -f "${file}" ]; then
  [ -d $(dirname "$file") ] || mkdir -p $(dirname "$file")
  touch ${file}
  chown -R apache:apache $(dirname "$file")
fi
[ -w "${file}" ] || (echo "${file}: Permission denied" && exit 1)

count=$(awk "\$2 ~ /^$user}\$/" ${file} | wc -l)
if [ $count -le 0 ]; then
  echo "HOTP/T30 $(printf '%-12s' $user) - ${secret_base16}" >> ${file}
  echo "$qrcode_url"
else
  echo "User '$user' already exists"
fi
$ sudo ./create_otp_userfile_sh haray2 isaotestweb

出力されたURLにアクセスして、表示されたQRコードをアプリでスキャンして登録。

※ユーザーファイルの生成はこちらからスクリプトを借りました。

qiita.com

「引数にUsernameを指定して実行すると、必要な項目を埋めた行が /var/www/otp/users に追記され、標準出力にGoogle Authenticator登録用のQRコードが表示されるURLが出力されます。」という優しい仕様。ありがとうございます。

BASIC認証の設定

$ sudo vi /etc/httpd/conf/httpd.conf
$ diff /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak
159,170d158
< <Location />
<     AuthType Basic
<     AuthName "Mamoru OTP"
<     AuthBasicProvider OTP
<     Require valid-user
<     OTPAuthUsersFile /var/www/otp/users
<     OTPAuthMaxLinger 3600
<     OTPAuthMaxOTPFailure 20
<     OTPAuthPINAuthProvider file
<     OTPAuthLogoutOnIPChange On
< </Location>
$ service httpd configtest
$ sudo systemctl restart httpd

これで設定終わりです。 ブラウザからアクセスするとBASIC認証のダイアログが表示されるので、「ユーザー名」にはスクリプトで作成したユーザー名を、「パスワード」にはアプリに表示されているOTPを、それぞれ入力します。

f:id:yhara90:20170427211508p:plain