| 1 | #!/usr/bin/env bash |
| 2 | |
| 3 | brt_ssl() { |
| 4 | local host="${1:-}" |
| 5 | local port="${2:-443}" |
| 6 | |
| 7 | if [[ -z "$host" ]]; then |
| 8 | brt_error "Usage: brt -ssl <host> [port]" |
| 9 | exit 1 |
| 10 | fi |
| 11 | |
| 12 | host="${host#https://}" |
| 13 | host="${host#http://}" |
| 14 | host="${host%%/*}" |
| 15 | if [[ "$host" == *:* ]]; then |
| 16 | port="${host##*:}" |
| 17 | host="${host%%:*}" |
| 18 | fi |
| 19 | |
| 20 | brt_require openssl |
| 21 | brt_info "SSL certificate for ${host}:${port}" |
| 22 | |
| 23 | local cert |
| 24 | cert=$(echo | openssl s_client -connect "${host}:${port}" -servername "$host" 2>/dev/null \ |
| 25 | | openssl x509 -noout -subject -issuer -dates -fingerprint -sha256 2>/dev/null) || { |
| 26 | brt_error "Could not retrieve certificate for ${host}:${port}" |
| 27 | exit 1 |
| 28 | } |
| 29 | |
| 30 | echo "$cert" |
| 31 | |
| 32 | local expiry |
| 33 | expiry=$(echo | openssl s_client -connect "${host}:${port}" -servername "$host" 2>/dev/null \ |
| 34 | | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2) |
| 35 | |
| 36 | if [[ -n "$expiry" ]]; then |
| 37 | local exp_epoch now days |
| 38 | exp_epoch=$(date -j -f "%b %d %T %Y %Z" "$expiry" +%s 2>/dev/null || date -d "$expiry" +%s 2>/dev/null) |
| 39 | now=$(date +%s) |
| 40 | days=$(( (exp_epoch - now) / 86400 )) |
| 41 | if (( days < 0 )); then |
| 42 | brt_error "Certificate expired ${days#-} days ago" |
| 43 | elif (( days < 30 )); then |
| 44 | brt_warn "Certificate expires in ${days} days" |
| 45 | else |
| 46 | brt_ok "Certificate valid for ${days} more days" |
| 47 | fi |
| 48 | fi |
| 49 | } |
| 50 | |