create_client.sh 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 [ "$#" -ne 2 ]; then
  6. echo "Usage: $0 <rsa_dir> <username>"
  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. # Check whether the user already exists
  23. if [ -f "$RSA_DIR/pki/index.txt" ] && grep -q "CN=$USERNAME" "$RSA_DIR/pki/index.txt"; then
  24. log "User $USERNAME already exists"
  25. exit 1
  26. fi
  27. # Change to the PKI directory and create the client
  28. cd "$RSA_DIR" || exit 1
  29. # Generate client key and certificate in batch mode (no prompts)
  30. ./easyrsa --batch build-client-full "$USERNAME" nopass
  31. if [ $? -eq 0 ]; then
  32. log "User $USERNAME created successfully"
  33. chown ${owner_user}:${owner_group} -R "$RSA_DIR/pki/issued/"
  34. chmod 660 "${RSA_DIR}/pki/issued/"*.crt
  35. chown ${owner_user}:${owner_group} -R "$RSA_DIR/pki/private/"
  36. chmod 660 "${RSA_DIR}/pki/private/"*.key
  37. exit 0
  38. else
  39. echo "Failed to create user $USERNAME"
  40. exit 1
  41. fi
  42. exit 0