IOSのパスワード文字列のハッシュ化について

enable secret などで利用する暗号化を指定したいとき,クリアテキストを入力することができない。

Router(config)#enable secret ?
  0      Specifies an UNENCRYPTED password will follow
  5      Specifies a MD5 HASHED secret will follow
  8      Specifies a PBKDF2 HASHED secret will follow
  9      Specifies a SCRYPT HASHED secret will follow
  <0-9>  Encryption types not explicitly specified
  LINE   The UNENCRYPTED (cleartext) 'enable' secret
  level  Set exec level password


事前にアルゴリズムを指定すれば良いだけなのだが,では,実際にハッシュ化された文字列を予め用意するにはどうしたらよいのだろうと考えた。

Router(config)#enable algorithm-type ?
  md5     Encode the password using the MD5 algorithm
  scrypt  Encode the password using the SCRYPT hashing algorithm
  sha256  Encode the password using the PBKDF2 hashing algorithm

Type5(MD5)

MD5の場合,opensslコマンドで対応できそうだ。オプションは-1がMD5。

$ openssl passwd --help
Usage: passwd [options]
Valid options are:
 -help               Display this summary
 -in infile          Read passwords from file
 -noverify           Never verify when reading password from terminal
 -quiet              No warnings
 -table              Format output as table
 -reverse            Switch table columns
 -salt val           Use provided salt
 -stdin              Read passwords from stdin
 -6                  SHA512-based password algorithm
 -5                  SHA256-based password algorithm
 -apr1               MD5-based password algorithm, Apache variant
 -1                  MD5-based password algorithm
 -aixmd5             AIX MD5-based password algorithm
 -crypt              Standard Unix password algorithm (default)
 -rand val           Load the file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

いざお試し。opensslコマンドで生成。

$ openssl passwd -1 "password"
$1$.cR/0KTx$pPUO/YlCknfEryhGL8vZ7/

ルータへ投入。


Router(config)#enable secret 5 $1$.cR/0KTx$pPUO/YlCknfEryhGL8vZ7/
ERROR: The secret you entered is not a valid encrypted secret.
To enter an UNENCRYPTED secret, do not specify type 5 encryption.
When you properly enter an UNENCRYPTED secret, it will be encrypted.

エラーになる・・・。saltが必要だった。改めて生成。

$ openssl passwd -salt `openssl rand -base64 3`  -1 password
$1$tCLN$fofh2RhTlDmwzXeGUh7x4.

ルータへ投入。MD5はもはや非推奨だぞとアラートが出るが無事に行けた。

Router(config)#enable secret 5 $1$tCLN$fofh2RhTlDmwzXeGUh7x4.
 WARNING: Command has been added to the configuration using a type 5 password. However, type 5 passwords will soon be deprecated. Migrate to a supported password type
Router(config)#
*May 11 06:39:25.460: %AAAA-4-CLI_DEPRECATED: WARNING: Command has been added to the configuration using a type 5 password. However, type 5 passwords will soon be deprecated. Migrate to a supported password type

Type8(PBKDF2)

PBKDF2はSHA256で繰り返しハッシュ化するもの。

opensslではハッシュ化できなさそうなので,pythonでやってみる。Passlibというライブラリがあるのでこれを使う。

なお,Cisco Communityを見ると以下のように記載されている。

Type 8 passwords are what Type 4 was meant to be, an upgraded Type 5!  Type 8 is hashed using PBKDF2, SHA-256, 80-bit salt, 20,000 iterations. While this is good, it is still vulnerable to brute-forcing since AES is easy to implement in (GPU) graphics cards. I have not proven it but I believe it is possible that the popular tool HashCat is able to decrypt these. In the running config standard Type 8 start with $8$.

https://community.cisco.com/t5/networking-documents/understanding-the-differences-between-the-cisco-password-secret/ta-p/3163238

80バイトのSaltということは10文字,2万Iterationで試行。

$ pip install passlib
Collecting passlib
  Downloading passlib-1.7.4-py2.py3-none-any.whl (525 kB)
     |????????????????????????????????| 525 kB 21.2 MB/s
Installing collected packages: passlib
Successfully installed passlib-1.7.4
$ python
>>> from passlib.hash import pbkdf2_sha256
>>> pbkdf2_sha256.using(rounds=20000, salt_size=10).hash("password")
'$pbkdf2-sha256$20000$cm6t9T6n9L73ng$7sCcdbt9sNLWj5h7.Jd.7cdyLwYqoPlFMIWV1..hjFc'
>>> pbkdf2_sha256.verify("password", '$pbkdf2-sha256$20000$cm6t9T6n9L73ng$7sCcdbt9sNLWj5h7.Jd.7cdyLwYqoPlFMIWV1..hjFc')
True
>>>

ハッシュ化成功した模様。salt以降をCiscoに登録。

Router(config)#enable secret 8 $8$cm6t9T6n9L73ng$7sCcdbt9sNLWj5h7.Jd.7cdyLwYqoPlFMIWV1..hjFc
Router(config)#end
Router#disable
Router>en
Password:
Password:
Password:
% Bad secrets

なんでだ・・・。なんどやってもダメで,Cisco側で登録したハッシュを逆にverifyしてもダメだった(方式が違うっぽい)。そこで,こんなの(ciscoPWDhasher)があったのでこれを使ってみることにした。

$ git clone https://github.com/BrettVerney/ciscoPWDhasher.git
$ cd ciscoPWDhasher
$ pip install scrypt passlib backports.pbkdf2
$ python3 ./ciscopwdhasher.py

+------------------------------------------------------------------------+
|    ____ _                 ____                                     _   |
|   / ___(_)___  ___ ___   |  _ \ __ _ ___ _____      _____  _ __ __| |  |
|  | |   | / __|/ __/ _ \  | |_) / _` / __/ __\ \ /\ / / _ \| '__/ _` |  |
|  | |___| \__ \ (_| (_) | |  __/ (_| \__ \__ \\ V  V / (_) | | | (_| |  |
|   \____|_|___/\___\___/  |_|   \__,_|___/___/ \_/\_/ \___/|_|  \__,_|  |
|                                                                        |
|           _   _           _                                            |
|          | | | | __ _ ___| |__   ___ _ __      .--.                    |
|          | |_| |/ _` / __| '_ \ / _ \ '__|    /.-. '----------.        |
|          |  _  | (_| \__ \ | | |  __/ |       \'-' .--"--""-"-'        |
|          |_| |_|\__,_|___/_| |_|\___|_|        '--'                    |
|                                                                        |
|  by: Brett Verney (@WiFiWizardOFOz)                      version: 0.1  |
+------------------------------------------------------------------------+

Select a hashing algorithm:

[1]  Type 5 (MD5)
[2]  Type 7 (XOR Cipher)
[3]  Type 8 (PBKDF2-HMAC-SHA256)
[4]  Type 9 (Scrypt)
[5]  Exit

Your selection: 3

Enter a Plain Text Password to convert: password
Your Cisco type 7 password is:   #これ多分type 8の間違い $8$L7qc2XluRN/CzI$t34L8AK8SWb8LUFeCNVQanveK/JwKozfuAtHuIRH6vc

ルータへ設定。

Router(config)#enable secret 8 
 
Router(config)#end
Router#disa
Router#disable
Router>en
Password:
Router#

無事成功。どうやらbase64のエンコード周りでCisco形式に変換してあげないとダメみたい(良くわからない)。

Type9(Scrypt)

現在推奨の方式。

Select a hashing algorithm:

[1]  Type 5 (MD5)
[2]  Type 7 (XOR Cipher)
[3]  Type 8 (PBKDF2-HMAC-SHA256)
[4]  Type 9 (Scrypt)
[5]  Exit

Your selection: 4

Enter a Plain Text Password to convert: password
Your Cisco type 9 password is: $9$KvAkztzB8xe7Am$n3st6bOSv2hzH7qTG/9RHUInJ0DlbSmtTqOHOtn99UM

同じようにルータへ設定。

Router(config)#$qc2XluRN/CzI$t34L8AK8SWb8LUFeCNVQanveK/JwKozfuAtHuIRH6vc
Router(config)#end
Router#disa
Router#disable
Router>en
Password:
Router#

問題無し!

素直に enable algorithm-type を使えという話だけれど,たまにはこういうことを調べるのも良いね。

TACACS+サーバ構築

概要

宅内環境の認証をTACACS化しようと,まずはTACACS+サーバを2台立てる。構成は次の通り。各機器の管理IFと同じセグメントにTACACSサーバを2台建てる。

OpenStack上にDebianイメージでインスタンスを1つ。冗長化のためESXi上にUbuntuのVMをたてて2号機とする。(なぜOSが違うかというと,ESXi上にDebian10のイメージがなかっただけで特に他意はなし)

TACACS+はtac_plusを利用する。元はこれ(https://www.shrubbery.net/tac_plus/)だと思うのだが,公開が終わっているっぽい。facebookがGithubでforkしたものを公開していたので,Ubuntu側ではここからソースをもってきてコンパイルしてインストールした。’Debianはリポジトリからインストールできた。)

インストール

Debian 10でのインストール方法

aptで一発。

# apt install tacacs+

Debain11でのインストール方法

11にはまだパッケージがなかったためソースからコンパイル。

# apt install git build-essential flex bison libwrap0-dev
$ git clone https://github.com/facebook/tac_plus.git
$ cd tac_plus/tacacs-F4.0.4.28
$ ./configure
$ make
# make install

続いて必要なファイルの準備。

サービス起動ファイル /etc/init.d/tacacs_plus

#!/bin/sh
### BEGIN INIT INFO
# Provides:          tacacs+
# Required-Start:    $network $local_fs $syslog $remote_fs
# Required-Stop:     $network $local_fs $remote_fs
# Should-Start:      $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: TACACS+ authentication daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

DAEMON=/usr/local/sbin/tac_plus
NAME="tacacs+"
DESC="TACACS+ authentication daemon"
LOGDIR=/var/log/
STARTTIME=1

PIDFILE=/var/run/tac_plus.pid

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

# Default options, these can be overriden by the information
# at /etc/default/$NAME
DAEMON_OPTS="-C /etc/tacacs+/tac_plus.conf"          # Additional options given to the server


LOGFILE=$LOGDIR/tac_plus.log  # Server logfile

# Include defaults if available
if [ -f /etc/default/$NAME ] ; then
        . /etc/default/$NAME
fi

# Check that the user exists (if we set a user)
# Does the user exist?
if [ -n "$DAEMONUSER" ] ; then
    if getent passwd | grep -q "^$DAEMONUSER:"; then
        # Obtain the uid and gid
        DAEMONUID=`getent passwd |grep "^$DAEMONUSER:" | awk -F : '{print $3}'`
        DAEMONGID=`getent passwd |grep "^$DAEMONUSER:" | awk -F : '{print $4}'`
    else
        log_failure_msg "The user $DAEMONUSER, required to run $NAME does not exist."
        exit 1
    fi
fi


set -e

running_pid() {
# Check if a given process pid's cmdline matches a given name
    pid=$1
    name=$2
    [ -z "$pid" ] && return 1
    [ ! -d /proc/$pid ] &&  return 1
    cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1 |cut -d : -f 1`
    # Is this the expected server
    [ "$cmd" != "$name" ] &&  return 1
    return 0
}

running() {
# Check if the process is running looking at /proc
# (works for all users)

    # No pidfile, probably no daemon present
    [ ! -f "$PIDFILE" ] && return 1
    pid=`cat $PIDFILE`
    running_pid $pid $DAEMON || return 1
    return 0
}

start_server() {
# Start the process using the wrapper
    if check_config_quiet ; then
         start-stop-daemon --start --quiet --pidfile $PIDFILE \
                --exec $DAEMON -- $DAEMON_OPTS
         errcode=$?
         return $errcode
    else
         return $?
    fi

}

stop_server() {
    killproc -p $PIDFILE $DAEMON
    return $?
}

reload_server() {
    if check_config_quiet ; then
         [ ! -f "$PIDFILE" ] && return 1
         pid=`cat $PIDFILE` # This is the daemon's pid
         # Send a SIGHUP
         kill -1 $pid
         return $?
    else
         return $?
    fi
}

check_config() {
        $DAEMON -P $DAEMON_OPTS
        return $?
}

check_config_quiet() {
        $DAEMON -P $DAEMON_OPTS >/dev/null 2>&1
        return $?
}

force_stop() {
# Force the process to die killing it manually
        [ ! -e "$PIDFILE" ] && return
        if running ; then
                kill -15 $pid
        # Is it really dead?
                sleep "$DIETIME"s
                if running ; then
                        kill -9 $pid
                        sleep "$DIETIME"s
                        if running ; then
                                echo "Cannot kill $NAME (pid=$pid)!"
                                exit 1
                        fi
                fi
        fi
        rm -f $PIDFILE
}


case "$1" in
  start)
        log_daemon_msg "Starting $DESC " "$NAME"
        # Check if it's running first
        if running ;  then
            log_progress_msg "apparently already running"
            log_end_msg 0
            exit 0
        fi
        if start_server ; then
            # NOTE: Some servers might die some time after they start,
            # this code will detect this issue if STARTTIME is set
            # to a reasonable value
            [ -n "$STARTTIME" ] && sleep $STARTTIME # Wait some time
            if  running ;  then
                # It's ok, the server started and is running
                log_end_msg 0
            else
                # It is not running after we did start
                log_end_msg 1
            fi
        else
            # Either we could not start it
            log_end_msg 1
        fi
        ;;
  stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        if running ; then
            # Only stop the server if we see it running
                        errcode=0
            stop_server || errcode=$?
            log_end_msg $errcode
        else
            # If it's not running don't do anything
            log_progress_msg "apparently not running"
            log_end_msg 0
            exit 0
        fi
        ;;
  force-stop)
        # First try to stop gracefully the program
        $0 stop
        if running; then
            # If it's still running try to kill it more forcefully
            log_daemon_msg "Stopping (force) $DESC" "$NAME"
                        errcode=0
            force_stop || errcode=$?
            log_end_msg $errcode
        fi
        ;;
  restart|force-reload)
        log_daemon_msg "Restarting $DESC" "$NAME"
                errcode=0
        stop_server || errcode=$?
        # Wait some sensible amount, some server need this
        [ -n "$DIETIME" ] && sleep $DIETIME
        start_server || errcode=$?
        [ -n "$STARTTIME" ] && sleep $STARTTIME
        running || errcode=$?
        log_end_msg $errcode
        ;;
  status)

        log_daemon_msg "Checking status of $DESC" "$NAME"
        if running ;  then
            log_progress_msg "running"
            log_end_msg 0
        else
            log_progress_msg "apparently not running"
            log_end_msg 1
            exit 1
        fi
        ;;
  # Use this if the daemon cannot reload
  reload)
        log_daemon_msg "Reloading $DESC configuration files" "$NAME"
        if reload_server ; then
                if running ; then
                        log_end_msg 0
                else
                        log_progress_msg "$NAME not running"
                        log_end_msg 1
                fi
        else
                log_progress_msg "Reload failled"
                log_end_msg 1
        fi
        ;;
  check)
        check_config
        if [ X$? = "X0" ]
        then
                log_daemon_msg "Checking $DESC configuration files successful" "$NAME"
        else
                log_daemon_msg "Checking $DESC configuration files failed"
                exit 1
        fi
        ;;
  *)
        N=/etc/init.d/tacacs_plus
        echo "Usage: $N {start|stop|force-stop|restart|reload|force-reload|status|check}" >&2
        exit 1
        ;;
esac

exit 0

アカウンティングログファイル作成

# touch /var/log/tac_plus.acct

tacacs+設定ファイル編集(2台共通)

/etc/tacacs+/tac_plus

以下設定例。今回はとりあえず設定ファイル中にユーザを記述する設定方式をとったが,仕事ではやらないように注意。パスワードのハッシュ化は 「openssl passwd – 5」 (SHA256)で生成。

# アカウンティング用ログファイル指定
accounting file = /var/log/tac_plus.acct


# <サーバと通信するための鍵を記述>
key = tacacs_key

user = networkmanager {
        name = "Network Manager"
        member = admin
        login = des <ハッシュ化パスワード>
        enable = des <ハッシュ化enable>
}

user = networkoperator {
        name = "Read only user"
        member = operator
        login = des <ハッシュ化パスワード>
        enable = des <ハッシュ化enable>
}

# 管理者用グループ。Privilage15。
group = admin {
        default service = permit
        service = exec {
                priv-lvl = 15
        }

# オペレータ用グループ。showコマンドのみ利用可能
group = operator {
        default service = deny
        service = exec {
                priv-lvl = 15
        }
        cmd = show {
                permit .*
        }
        cmd = exit {
                permit .*
        }
}

TACACS+起動

# service tacacs_plus start

以上。

次はNW機器側の設定。

パスワードの定期的変更

総務省が方針変更したというニュースを受けて, その他界隈はどうなっているのかググってみた。

総務省:定期的変更は不要(2018年3月1日に方針変更)
http://www.soumu.go.jp/main_sosiki/joho_tsusin/security/basic/privacy/01-2.html

内閣サイバーセキュリティセンター(NISC):定期的変更は不要(ハンドブック ver3.0)
https://www.nisc.go.jp/security-site/files/handbook-all.pdf

経産省:パスワードは随時変更(定期的とは言っていない)
http://www.meti.go.jp/policy/netsecurity/UAaccessCMG.htm

IPA:定期的変更には意味がある(あくまで予防的?)
https://www.ipa.go.jp/security/personal/onlinegame/index.html

海外ではずいぶん前からパスワードの定期的変更はセキュリティ上問題となりえると言われているようです。
https://www.schneier.com/blog/archives/2016/08/frequent_passwo.html