Archive: 2015/05/22

Basic認証の落とし穴

とある案件でRESTAPIによる"ユーザ認証"の振舞いを確認しようとして、予てよりApache HTTP Serverに登録してあるユーザアカウントを流用して検証していたのだが、期待とは裏腹に"401:認証エラー"とならない事があった。

具体的には、"PaSsWoRd"というパスワード設定に対して"PaSsWoRdXyZ"を与えたのに「認証OK」と判断されてしまったので、「何か設定しくじってるのかな~?」とググったら、【apache】ベーシック認証で8文字以上の長いパスワードを設定するときの注意というのを発見。

確かにhtpasswd - Manage user files for basic authenticationの「Security Considerations(セキュリティ考慮事項)」には

When using the crypt() algorithm, note that only the first 8 characters of the password are used to form the password. If the supplied password is longer, the extra characters will be silently discarded.
ざっくり意訳すると
crypt()アルゴリズムを使用する場合、パスワードの最初の8文字分しか使用されないことに注意してください。与えられたパスワードが長い場合、余分な文字は黙って破棄されます。
と書いてあったよ。

Windows版の場合はMD5アルゴリズムがデフォルトとなっている事から最初の8文字の呪縛は無いそうなので、Linux版もMD5をデフォルトにしなくちゃダメでしょ、と思ってUbuntu 14.04のhtpasswdを確認したところ

yano@GT110b:~$ htpasswd -nb userhoge password
userhoge:$apr1$UQ0/lsy.$gpZwn.kvveLE5pYxs5eaW.

yano@GT110b:~$ htpasswd -nb userhoge passwordXYZ
userhoge:$apr1$jpjd1bYr$Wv/R7ai0xF6j.v6HAMe4s0

…と異なる結果になったので、「おや?」と思いhelpをみたところ
yano@GT110b:~$ htpasswd --help
Usage:
htpasswd [-cimBdpsDv] [-C cost] passwordfile username
htpasswd -b[cmBdpsDv] [-C cost] passwordfile username password

htpasswd -n[imBdps] [-C cost] username
htpasswd -nb[mBdps] [-C cost] username password
-c Create a new file.
-n Don't update file; display results on stdout.
-b Use the password from the command line rather than prompting for it.
-i Read password from stdin without verification (for script usage).
-m Force MD5 encryption of the password (default).
-B Force bcrypt encryption of the password (very secure).
-C Set the computing time used for the bcrypt algorithm
(higher is more secure but slower, default: 5, valid: 4 to 31).
-d Force CRYPT encryption of the password (8 chars max, insecure).
-s Force SHA encryption of the password (insecure).
-p Do not encrypt the password (plaintext, insecure).
-D Delete the specified user.
-v Verify password for the specified user.
On other systems than Windows and NetWare the '-p' flag will probably not work.
The SHA algorithm does not use a salt and is less secure than the MD5 algorithm.
yano@GT110b:~$
という結果となり、デフォルトMD5になっている事が確認できたので、今回最初の8文字分しか効かなかったのは、10年近くも昔の設定を安易に使い回してきたのが原因のようだ。