#!/bin/bash

# File: sslinfo
#
# Description: This file takes an SSL file and prints
#              useful human-readable information about it.
#
# Package: AniNIX/ShadowArch
# Copyright: WTFPL
#
# Author: DarkFeather <ircs://aninix.net:6697/DarkFeather>

# Sanity checks
set -Eeo pipefail

# Default variables
port=443
option="-text"
unset dump
unset host
unset modulus
unset machinereadable
unset showserial
regex='Subject:|Subject Alt|Issuer:|Not |DNS:|IP Addr|Signature Algorithm'

# Show Usage
function Usage() {
    echo "Usage: $0 [ -p port ] [ -r regex | -a | -s ] -t TARGET"
    echo "       $0 -V"
    echo "       $0 -h"
    echo
    echo "Adding -m will make it machine readable, and -v will increase verbosity."
    echo "The -a will show all output."
    echo "The -s will show the serial for the certificate."
    echo "The -h will show helptext."
    echo "The -V option will show version"
    echo "TARGET can be a hostname, request, or certificate."
}

# Translate output into CSV format.
function machineReadable() {
    grep -E 'After|DNS|Subject:' | sed 's/^\s\+//' | sed 's/Not After : //' | sed 's/Subject: //' | sed 's/DNS://g' | tr '\n' ','
    echo
}

# Parse user options
while getopts 'aDhmMp:r:st:vV' OPTION; do
    case "$OPTION" in
        a) regex="*" ;;
        D) dump=1 ;;
        h) echo Display useful information in a concise format about an SSL object.; Usage; exit 0 ;;
        m) machinereadable=1 ;;
        M) modulus=1 ; option="-modulus" ;;
        p) port="${OPTARG}" ;;
        r) regex="${OPTARG}" ;;
        s) showserial=1 ; option="-serial" ;;
        t) host="${OPTARG}" ;;
        v) set -x ;;
        V) Version ;;
        *) Usage; exit 1 ;;
    esac
done

# Make sure some argument is set.
if [ -z "$host" ] ; then
    echo Need a target.
    Usage
    exit 1;
fi

# Pass it all through OpenSSL
# 1. Get the object
(if [ -f "$host" ]; then
     if [ `grep -c REQUEST "$host"` -gt 1 ]; then
         openssl req -noout -in "$host" $option
     elif [ `grep -c RSA\ PRIVATE\ KEY "$host"` -gt 1 ]; then
         openssl rsa -noout -in "$host" $option
     elif [ `grep -c CERTIFICATE "$host"` -gt 1 ]; then
         openssl x509 -noout -in "$host" $option
     fi
 else
     echo | openssl s_client -connect "$host":"$port" 2>&1 | if [ -z "$dump" ]; then openssl x509 -noout $option; fi
 fi) \
     | (if [ -n "$modulus" ]; then
    cat;
elif [ -n "$showserial" ]; then
    sed 's/^serial=//'
elif [ -n "$dump" ]; then # 2. Parse the object.
    grep -A 99 BEGIN\ CERTIFICATE
else
    grep -E -i "$regex"
fi) \
     | (if [ -z "$machinereadable" ]; then cat; else machineReadable; fi)