functions.sh 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/bin/bash
  2. owner_user=nobody
  3. owner_group=nogroup
  4. # Name of the current script (without path)
  5. script_name="$(basename "${BASH_SOURCE[0]}")"
  6. log() {
  7. logger -t "$script_name" -p user.info "$1"
  8. echo "$1"
  9. }
  10. mlog() {
  11. logger -t "$script_name" -p user.info "$1"
  12. }
  13. # Check permissions (must be root)
  14. check_permissions() {
  15. if [[ $EUID -ne 0 ]]; then
  16. log "Error: This script must be run as root"
  17. exit 1
  18. fi
  19. }
  20. # Validate that the path is a file or directory and is writable
  21. check_ccd_path() {
  22. local path="$1"
  23. if [[ -d "$path" ]]; then
  24. # It's a directory — check write permission
  25. if [[ ! -w "$path" ]]; then
  26. log "Error: No write permission for directory: $path"
  27. exit 1
  28. fi
  29. elif [[ -f "$path" ]]; then
  30. # It's a file — check write permission
  31. if [[ ! -w "$path" ]]; then
  32. log "Error: No write permission for file: $path"
  33. exit 1
  34. fi
  35. fi
  36. }
  37. validate_pki_dir() {
  38. local pki_dir=$1
  39. if [[ ! -d "${pki_dir}" || ! -f "${pki_dir}/index.txt" ]]; then
  40. log "Error: Invalid PKI directory - missing index.txt"
  41. exit 2
  42. fi
  43. }
  44. find_cert_file() {
  45. local cn=$1 pki_dir=$2
  46. local cert_file
  47. # Try standard location first
  48. cert_file="${pki_dir}/issued/${cn}.crt"
  49. [[ -f "${cert_file}" ]] && echo "${cert_file}" && return 0
  50. # Fallback to serial-based lookup
  51. local serial
  52. serial=$(awk -v cn="${cn}" '$0 ~ "/CN=" cn "/" && $1 == "V" {print $3}' "${pki_dir}/index.txt")
  53. [[ -z "${serial}" ]] && return 1
  54. cert_file="${pki_dir}/certs_by_serial/${serial}.pem"
  55. [[ -f "${cert_file}" ]] && echo "${cert_file}" && return 0
  56. return 1
  57. }
  58. find_key_file() {
  59. local cn=$1 pki_dir=$2 serial=$3
  60. local key_file
  61. # Try standard locations
  62. for candidate in "${pki_dir}/private/${cn}.key" "${pki_dir}/private/${serial}.key"; do
  63. if [[ -f "${candidate}" ]]; then
  64. echo "${candidate}"
  65. return 0
  66. fi
  67. done
  68. return 1
  69. }
  70. #mlog "Script called with: $0 $@"