#!/bin/bash
# $Id: ovpn_check_clients.bash 1037 2026-03-16 15:07:58Z bertrand $
# Ce script permet de vérifier que les clients de référence ont tous 
# un certificat associé et que celui-ci n'est pas expiré.
# external parameters
profile_name=$1
# internal parameters
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)
# ovpn
ovpn_path="/etc/openvpn"
ovpn_clients="$ovpn_path/client.list"
ovpn_profile="$ovpn_path/server/$profile_name.conf"
# ca
ca_path="$ovpn_path/ca"
ca_pki_path="$ca_path/pki"
ca_issued_path="$ca_pki_path/issued"
ca_private_path="$ca_pki_path/private"
ca_index_path="$ca_pki_path/index.txt"
# tools
openssl_tool=$(which openssl)
openssl_cmdline="$openssl_tool x509"
if [[ -n $profile_name && -f $ovpn_profile && -f $ovpn_clients ]]; then
	today=$(date +%s)
	# Vérifications des clients
	while read client_name; do
		echo -n "checking $client_name"
		#cat $ca_index_path | grep -w "$client_name"
		cert_list=$(grep -w "CN=$client_name" $ca_index_path)
		cert_count=$(echo $cert_list | wc -l)
		if [[ $cert_count > 0 ]]; then
			echo -ne "\t${GREEN}CERT_DB_ENTRY_FOUND${RESET}"
			ca_client_crt_file="$ca_issued_path/$client_name.crt"
			ca_client_pem_file="$ca_issued_path/$client_name.pem"
			ca_client_key_file="$ca_private_path/$client_name.key"
			if [[ -f $ca_client_crt_file && -f $ca_client_key_file ]]; then
				echo -ne "\t${GREEN}CERT_FILE_FOUND${RESET}"
			else
				echo -ne "\t${RED}CERT_FILE_NOT_FOUND${RESET}"
			fi
			if [[ ! -f $ca_client_pem_file ]]; then
				$openssl_cmdline -in $ca_client_crt_file -out $ca_client_pem_file -outform PEM
			fi
			if [[ -f $ca_client_pem_file ]]; then
				not_after=$($openssl_cmdline -dates -noout -in $ca_client_pem_file | grep notAfter | cut -c 10-)
				expiry_date=$(date -d "$not_after" +%s)
				if [[ $expiry_date > $today ]]; then
					echo -ne "\t${GREEN}CERT_DATE_VALID${RESET}"
				else
					echo -ne "\t${RED}CERT_EXPIRED${RESET}"
				fi
				expiry_date=$(date -d "$not_after" +%Y-%m-%d)
				echo " ($expiry_date)"
			else
				echo "\t${RED}PEM_FILE_NOT_FOUND${RESET}"
			fi
		else
			echo " ERR (no certificate found in database)"
		fi
	done < $ovpn_clients
else
	if [[ -n $profile_name ]]; then
		if [[ ! -f $ovpn_profile ]]; then
			echo "${RED}$profile_name does not exist ($ovpn_profile not found)${RESET}"
		fi
	else
		echo "usage: $0 profile_name"
	fi
	if [[ ! -f $ovpn_clients ]]; then
		echo "${RED}$ovpn_clients does not exist${RESET}"
	fi
	if [[ ! -f $openssl_tool ]]; then
		echo "${RED}$openssl_tool does not exist${RESET}"
	fi
fi
