OpenSSL s_client cheat sheet (BASH)

A quick reference for a number of common tasks using OpenSSL's s_client to connect to a SSL/TLS service, including checking expiry dates etc

Details

  • Language: BASH

Snippet

# Set some variables for convenience
SERVER='myserver.com:443'
SITENAME='myserver.com'

# Sitename is the SNI name, so you can, for example, do
#
# SERVER='myserver.com:443'
# SITENAME='snippets.bentasker.co.uk'
#

# Connect to a server and check the expiry date of the certificate
echo | openssl s_client -connect $SERVER -servername $SITENAME -showcerts 2>&1 | openssl x509 -noout -dates

# Get expiry for comparison in script
expiry=$(date --date="$(echo -n | openssl s_client -connect $SERVER -servername $SITENAME -showcerts 2> /dev/null \
| openssl x509 -dates -noout | grep not | grep -i "notAfter" | cut -d\= -f 2)" +'%s')
echo $expiry

# List Subject Alternate Names
echo | openssl s_client -connect $SERVER -servername $SITENAME -showcerts | openssl x509 -noout -text | grep DNS: | tr ',' '\n'

# Check whether certificate verifies for 'foo.com' (includes SANs)
echo | openssl s_client -connect $SERVER -servername $SITENAME -showcerts -verify_hostname foo.com 2>&1

# Only use sslv3
echo | openssl s_client -connect $SERVER -servername $SITENAME -ssl3

# Only use tls 1.2
echo | openssl s_client -connect $SERVER -servername $SITENAME -tls1_2

# Only Use specific ciphersuite
echo | openssl s_client -connect $SERVER -servername $SITENAME -cipher EDH-DSS-DES-CBC3-SHA

Usage Example

#!/usr/bin/bash
#
# Test remote server support for all ciphersuites supported by local openssl install
#
#
# usage: ./cipher_test.sh [server fqdn/ip]
#

SERVER=$1
DELAY=1
ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g')

echo Obtaining cipher list from $(openssl version).

for cipher in ${ciphers[@]}
do
echo -n Testing $cipher...
result=$(echo -n | openssl s_client -cipher "$cipher" -connect $SERVER 2>&1)
if [[ "$result" =~ ":error:" ]] ; then
  error=$(echo -n $result | cut -d':' -f6)
  echo NO \($error\)
else
  if [[ "$result" =~ "Cipher is ${cipher}" || "$result" =~ "Cipher    :" ]] ; then
    echo YES
  else
    echo UNKNOWN RESPONSE
    echo $result
  fi
fi
sleep $DELAY
done