functions.sh 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/bin/bash
  2. owner_user=nobody
  3. owner_group=www-data
  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. else
  36. # Path does not exist or is not a regular file/directory
  37. log "Error: Path does not exist or is not a file/directory: $path"
  38. exit 1
  39. fi
  40. }
  41. validate_pki_dir() {
  42. local pki_dir=$1
  43. if [[ ! -d "${pki_dir}" || ! -f "${pki_dir}/index.txt" ]]; then
  44. log "Error: Invalid PKI directory - missing index.txt"
  45. exit 2
  46. fi
  47. }
  48. find_cert_file() {
  49. local cn=$1 pki_dir=$2
  50. local cert_file
  51. # Try standard location first
  52. cert_file="${pki_dir}/issued/${cn}.crt"
  53. [[ -f "${cert_file}" ]] && echo "${cert_file}" && return 0
  54. # Fallback to serial-based lookup
  55. local serial
  56. serial=$(awk -v cn="${cn}" '$0 ~ "/CN=" cn "/" && $1 == "V" {print $3}' "${pki_dir}/index.txt")
  57. [[ -z "${serial}" ]] && return 1
  58. cert_file="${pki_dir}/certs_by_serial/${serial}.pem"
  59. [[ -f "${cert_file}" ]] && echo "${cert_file}" && return 0
  60. return 1
  61. }
  62. find_key_file() {
  63. local cn=$1 pki_dir=$2 serial=$3
  64. local key_file
  65. # Try standard locations
  66. for candidate in "${pki_dir}/private/${cn}.key" "${pki_dir}/private/${serial}.key"; do
  67. if [[ -f "${candidate}" ]]; then
  68. echo "${candidate}"
  69. return 0
  70. fi
  71. done
  72. return 1
  73. }
  74. mlog "Script called with: $0 $@"