create_client.sh 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/bin/bash
  2. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  3. #SCRIPT_DIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"
  4. source "$SCRIPT_DIR/functions.sh"
  5. if [ "$#" -lt 2 ]; then
  6. echo "Usage: $0 <rsa_dir> <username> [--force]"
  7. exit 1
  8. fi
  9. check_permissions
  10. RSA_DIR="$1"
  11. USERNAME="$2"
  12. # Check that the PKI directory exists
  13. if [ ! -d "$RSA_DIR" ]; then
  14. log "PKI directory not found: $RSA_DIR"
  15. exit 1
  16. fi
  17. # Check that easyrsa exists
  18. if [ ! -f "$RSA_DIR/easyrsa" ]; then
  19. log "easyrsa not found in $RSA_DIR"
  20. exit 1
  21. fi
  22. FORCE=0
  23. if [ "$3" == "--force" ]; then
  24. FORCE=1
  25. fi
  26. # Check whether the user already exists
  27. if [ -f "$RSA_DIR/pki/index.txt" ] && grep -q "CN=$USERNAME" "$RSA_DIR/pki/index.txt"; then
  28. if [ $FORCE -eq 1 ]; then
  29. log "User $USERNAME exists, revoking and recreating..."
  30. cd "$RSA_DIR" || exit 1
  31. ./easyrsa --batch revoke "$USERNAME"
  32. ./easyrsa --batch gen-crl
  33. log "Removing old certificate files for $USERNAME..."
  34. if [ -f "$RSA_DIR/pki/issued/${USERNAME}.crt" ]; then
  35. rm -f "$RSA_DIR/pki/issued/${USERNAME}.crt"
  36. log "Removed: $RSA_DIR/pki/issued/${USERNAME}.crt"
  37. fi
  38. if [ -f "$RSA_DIR/pki/private/${USERNAME}.key" ]; then
  39. rm -f "$RSA_DIR/pki/private/${USERNAME}.key"
  40. log "Removed: $RSA_DIR/pki/private/${USERNAME}.key"
  41. fi
  42. if [ -f "$RSA_DIR/pki/reqs/${USERNAME}.req" ]; then
  43. rm -f "$RSA_DIR/pki/reqs/${USERNAME}.req"
  44. log "Removed: $RSA_DIR/pki/reqs/${USERNAME}.req"
  45. fi
  46. if [ -f "$RSA_DIR/pki/inline/${USERNAME}.inline" ]; then
  47. rm -f "$RSA_DIR/pki/inline/${USERNAME}.inline"
  48. log "Removed: $RSA_DIR/pki/inline/${USERNAME}.inline"
  49. fi
  50. else
  51. log "User $USERNAME already exists (use --force to renew)"
  52. exit 1
  53. fi
  54. fi
  55. # Change to the PKI directory and create the client
  56. cd "$RSA_DIR" || exit 1
  57. # Generate client key and certificate in batch mode (no prompts)
  58. ./easyrsa --batch build-client-full "$USERNAME" nopass
  59. if [ $? -eq 0 ]; then
  60. log "User $USERNAME created successfully"
  61. chown ${owner_user}:${owner_group} -R "$RSA_DIR/pki/issued/"
  62. chmod 660 "${RSA_DIR}/pki/issued/"*.crt
  63. chown ${owner_user}:${owner_group} -R "$RSA_DIR/pki/private/"
  64. chmod 660 "${RSA_DIR}/pki/private/"*.key
  65. exit 0
  66. else
  67. echo "Failed to create user $USERNAME"
  68. exit 1
  69. fi
  70. exit 0