#!/usr/bin/env bash

# Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#
# Verifies whether FIPS is enabled on Mariner 2.0
#

set -euo pipefail

# Check if FIPS mode is enabled by the kernel (returns 1 if enabled)
fips_enabled=$(sudo cat /proc/sys/crypto/fips_enabled)
if [ "$fips_enabled" != "1" ]; then
    echo "FIPS is not enabled by the kernel: $fips_enabled"
    exit 1
fi

# Check if sysctl is configured (returns crypto.fips_enabled = 1 if enabled)
sysctl_configured=$(sudo sysctl crypto.fips_enabled)
if [ "$sysctl_configured" != "crypto.fips_enabled = 1" ]; then
    echo "sysctl is not configured for FIPS: $sysctl_configured"
    exit 1
fi

# Check if openssl library is running in FIPS mode
# MD5 should fail; the command's output should be similar to:
#   Error setting digest
#   131590634539840:error:060800C8:digital envelope routines:EVP_DigestInit_ex:disabled for FIPS:crypto/evp/digest.c:135:
openssl=$(openssl md5 < /dev/null 2>&1 || true)
if [[ "$openssl" != *"disabled for FIPS"* ]]; then
    echo "openssl is not running in FIPS mode: $openssl"
    exit 1
fi

# Check if dracut-fips is installed (returns dracut-fips-<version>)
dracut_fips=$( (rpm -qa | grep dracut-fips) || true )
if [[ "$dracut_fips" != *"dracut-fips"* ]]; then
    echo "dracut-fips is not installed: $dracut_fips"
    exit 1
fi

echo "FIPS mode is enabled."