#!/usr/bin/env bash

HOST_IP=$(hostname -i)
LOGFILE="/var/log/cloudstack/management/mold-encryption.log"
MONITORING="/usr/lib/systemd/system/mold-monitoring.service"
systemctl stop cloudstack-management

chmod 777 /etc/cloudstack/management
chmod 777 /etc/cloudstack/management/key

# kek 생성시 필요한 비밀번호 입력
echo "::::: 키 암호화 키(KEK) 생성시 필요한 비밀번호를 입력해주세요.(4자 이상) :::::"

while :
do
        echo -n "비밀번호 : "
        read -s kek_pass
        echo " "

        echo -n "비밀번호 확인 : "
        read -s kek_pass_check
        echo " "

        if [ "$kek_pass" != "$kek_pass_check" ] || [ -z $kek_pass ] || [ ${#kek_pass} -lt 4 ]; then
                echo "비밀번호를 다시 확인해주세요.(4자 이상)"
        else
                break
        fi
done

# 감사기록 저장시 필요한 DBMS 비밀번호 입력
echo "::::: 현재 DBMS 비밀번호를 입력해주세요. :::::"

while :
do
        echo -n "비밀번호 : "
        read -s curdbpass
        echo " "

        mysql -uroot -p$curdbpass -e "select 1 from dual;" > /dev/null
        if [ $? -eq 0 ];then
                break
        else
                echo "DBMS 비밀번호를 다시 확인해주세요."
        fi
done

cd /etc/cloudstack/management

# 주석라인 삭제, 빈라인 삭제
sed -i '/^\#/d' db.properties
sed -i '/^$/d' db.properties

# key(db secretKey) 파일을 암호화하여 저장
openssl enc -aria-256-cbc -a -pbkdf2 -k $kek_pass -saltlen 16 -md sha256 -iter 100000 -in key -out key.enc
# 암호 연산 성공 여부 감사로그 생성
if [[ $? != 0 ]]; then
        UUID=$(cat /proc/sys/kernel/random/uuid)
        mysql -uroot -t cloud -p$curdbpass "use cloud; INSERT INTO event (uuid, type, state, description, user_id, account_id, domain_id, resource_id, created, level, start_id, archived, display, client_ip) VALUES ('$UUID', 'ENCRYPTION.CHECK', 'Completed', 'Cryptographic operation failed : encrypting key file with aria-256-cbc, pbkdf2 algorithm.', '2', '2', '1', '0', DATE_SUB(NOW(), INTERVAL 9 HOUR), 'ERORR', '0', '0', '1', '$HOST_IP');"
        exit 1
fi
# db.properties 파일을 암호화하여 저장
openssl enc -aes-256-cbc -in db.properties -out db.properties.enc -K $(cat key) -pass pass:$kek_pass -saltlen 16 -md sha256 -iter 100000
# 암호 연산 성공 여부 감사로그 생성
if [[ $? != 0 ]]; then
        UUID=$(cat /proc/sys/kernel/random/uuid)
        mysql -uroot -t cloud -p$curdbpass "use cloud; INSERT INTO event (uuid, type, state, description, user_id, account_id, domain_id, resource_id, created, level, start_id, archived, display, client_ip) VALUES ('$UUID', 'ENCRYPTION.CHECK', 'Completed', 'Cryptographic operation failed : encrypting db.properties file with aes-256-cbc algorithm.', '2', '2', '1', '0', DATE_SUB(NOW(), INTERVAL 9 HOUR), 'ERORR', '0', '0', '1', '$HOST_IP');"
        exit 1
fi

# server.properties 파일을 암호화하여 저장
openssl enc -aes-256-cbc -in server.properties -out server.properties.enc -K $(cat key) -pass pass:$kek_pass -saltlen 16 -md sha256 -iter 100000
# 암호 연산 성공 여부 감사로그 생성
if [[ $? != 0 ]]; then
        UUID=$(cat /proc/sys/kernel/random/uuid)
        mysql -uroot -t cloud -p$curdbpass "use cloud; INSERT INTO event (uuid, type, state, description, user_id, account_id, domain_id, resource_id, created, level, start_id, archived, display, client_ip) VALUES ('$UUID', 'ENCRYPTION.CHECK', 'Completed', 'Cryptographic operation failed : encrypting server.properties file with aes-256-cbc algorithm.', '2', '2', '1', '0', DATE_SUB(NOW(), INTERVAL 9 HOUR), 'ERORR', '0', '0', '1', '$HOST_IP');"
        exit 1
fi

# environment.properties 파일을 암호화하여 저장
openssl enc -aes-256-cbc -in environment.properties -out environment.properties.enc -K $(cat key) -pass pass:$kek_pass -saltlen 16 -md sha256 -iter 100000
# 암호 연산 성공 여부 감사로그 생성
if [[ $? != 0 ]]; then
        UUID=$(cat /proc/sys/kernel/random/uuid)
        mysql -uroot -t cloud -p$curdbpass "use cloud; INSERT INTO event (uuid, type, state, description, user_id, account_id, domain_id, resource_id, created, level, start_id, archived, display, client_ip) VALUES ('$UUID', 'ENCRYPTION.CHECK', 'Completed', 'Cryptographic operation failed : encrypting environment.properties file with aes-256-cbc algorithm.', '2', '2', '1', '0', DATE_SUB(NOW(), INTERVAL 9 HOUR), 'ERORR', '0', '0', '1', '$HOST_IP');"
        exit 1
fi

# openssl enc -aria-256-ctr -a -kfile kek -iter 100000 -in key -out key.enc

# 생성된 암호키(DEK), db, server, environment 프로퍼티 파일 삭제 및 메모리를 0, 1 로 덮어쓰기 5회
for var in {1..5} ; do echo 01010101 > key ; done
for var in {1..5} ; do echo 01010101 > db.properties ; done
for var in {1..5} ; do echo 01010101 > server.properties ; done
for var in {1..5} ; do echo 01010101 > environment.properties ; done

# 실제 파일 삭제
rm -rf key db.properties server.properties environment.properties

# 모니터링 서비스 파일에 kek_pass 저장
enc_kek_pass=$(echo $kek_pass | base64)
sed -i "9s/$/ $enc_kek_pass/g" $MONITORING
systemctl daemon-reload

# 관리용 단말기 IP 등록
echo "::::: 관리용 단말기 IP를 입력해주세요.(예시:10.10.1.1) :::::"

while :
do
        echo -n "IP : "
        read admin_manage_ip
        echo " "

        last=$(echo "$admin_manage_ip" | cut -d"." -f4)
        valid=$(echo "$admin_manage_ip" | egrep '^[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}$');

        if [ -z $admin_manage_ip ] || [ ! -n "$valid" ] || [ "$last" = 0 ] || [ "$last" = 255 ] || [ "$admin_manage_ip" = "127.0.0.1" ]; then
                echo "IP 형식에 맞게 다시 입력해주세요."
        else
                break
        fi
done

# 관리용 단말기 IP를 admin 계정의 설정 값 세팅
mysql -uroot -t cloud -p$curdbpass -e "INSERT INTO account_details (account_id, name, value) VALUES (2, 'api.allowed.source.ip', \"$admin_manage_ip\");"
mysql -uroot -t cloud -p$curdbpass -e "INSERT INTO account_details (account_id, name, value) VALUES (2, 'api.allowed.source.cidr', '32');"

rm -rf /opt/ablestack-v4.0-4.0.0/after_setting.sh