TLS is Transport Layer Security. It used to be called SSL: the Secure Sockets Layer. It has to do with encrypted IP traffic.

Apache SSL steps

  1. Generate a host key: openssl genrsa -out foo.com.key 2048
  2. Generate a CSR from that key: openssl req -new -key foo.com.key -out foo.com.csr

To set up VirtualHosts, follow this template: http://wiki.apache.org/httpd/NameBasedSSLVHosts

Examples

Download a certificate from an https server

get_certificate_from_server() {
  hostname="$1"
  port="${2:-443}"
  ip_address="$(dig +short "$hostname")"
  echo |
    openssl s_client -servername "$hostname" -connect "${ip_address}:${port}" 2>/dev/null |
    sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
}

get_certificate_from_server github.com

Show info about a certificate file

openssl x509 -noout -text -in foo.pem

Validate a keys / cert pair

To validate that a particular key was used to generate a certificate, useful for testing https key/crt files, do the following and make sure the modulus sections match:

openssl rsa  -noout -text -in server.key | grep -i -A9 modulus
openssl x509 -noout -text -in server.crt | grep -i -A9 modulus

Or as a function:

function crt-key-compare {
  if [ ! -f "$1" ] || [ ! -f "$2" ] ; then
    echo "ERROR: check that both files exist."
    return 1
  fi

  if [[ "$1" != *crt* ]] || [[ "$2" != *key* ]] ; then
    echo "usage: crt-key-compare <server.crt> <server.key>" ;
  else
    crt_modulus=$(openssl x509 -in "$1" -modulus | grep Modulus) || return 1
    key_modulus=$(openssl rsa  -in "$2" -modulus | grep Modulus) || return 1

    if diff <(echo "$crt_modulus") <(echo "$key_modulus") ; then
      echo "key and crt match."
    else
      echo "key and crt do not match"
    fi
  fi
}

See some information about a server's certificate

SERVER_NAME=linuxforums.org
SERVER_PORT=443
openssl s_client -connect "${SERVER_NAME}:${SERVER_PORT:-443}"

See just the dates of a webserver's SSL certificate

check-server-cert-dates() {
    test -z "$1" && { echo "Usage: check-server-cert-dates <servername> [port]" ; return 1 ; }
    openssl s_client -connect "${1}:${2:-443}" 2>/dev/null </dev/null |
    openssl x509 -noout -dates
}

Encrypt a file

openssl enc -aes-256-cbc -salt -in yourfile -out yourfile.enc

Decrypt a file

openssl enc -aes-256-cbc -d -in encryptedfile.enc -out decryptedfile

Encrypt / Decrypt bash functions

function encrypt_file() { openssl enc -aes-256-cbc -salt -in "$1" -out "$1.enc" ; }
function decrypt_file() { openssl enc -aes-256-cbc -d -in "$1" -out "$1.dec" ; }

See Also