show_servers_crt.sh 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/bin/bash
  2. set -o pipefail
  3. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  4. #SCRIPT_DIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"
  5. source "$SCRIPT_DIR/functions.sh"
  6. show_usage() {
  7. echo "Usage: $0 <index.txt>"
  8. echo "Default index.txt: /etc/openvpn/server/server/rsa/pki/index.txt"
  9. exit 1
  10. }
  11. main() {
  12. # Process arguments
  13. [[ $# -lt 1 ]] && show_usage
  14. check_permissions
  15. local index_txt="$1"
  16. local PKI_DIR
  17. PKI_DIR=$(dirname "${index_txt}")
  18. # Validate PKI directory
  19. validate_pki_dir "${PKI_DIR}"
  20. # Find all certificate files in the issued directory
  21. find "${PKI_DIR}/issued/" \( -name "*.crt" -o -name "*.pem" -o -name "*.cer" \) -print0 \
  22. | while IFS= read -r -d '' cert; do
  23. # Extract subject and extensions from certificate
  24. local openssl_output
  25. openssl_output=$(openssl x509 -in "$cert" -subject -noout -ext extendedKeyUsage -purpose 2>/dev/null)
  26. # Username = filename without extension
  27. local username
  28. username=$(basename "${cert}" | sed 's/\.[^.]*$//')
  29. # Extract CN from subject
  30. local CN
  31. CN=$(echo "$openssl_output" | grep 'subject=' | sed 's/.*CN\s*=\s*//;s/,.*//')
  32. # Check if certificate has server authentication usage
  33. if echo "$openssl_output" | grep -q "TLS Web Server Authentication\|serverAuth"; then
  34. echo "$username"
  35. # If CN differs from filename, also print CN
  36. [ "${username}" != "${CN}" ] && echo "$CN"
  37. fi
  38. done
  39. exit 0
  40. }
  41. main "$@"