Skip to content

Instantly share code, notes, and snippets.

@randomoracle
Last active February 23, 2020 22:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randomoracle/7b44b0b5a30a95367b84b6e5984ecb9f to your computer and use it in GitHub Desktop.
Save randomoracle/7b44b0b5a30a95367b84b6e5984ecb9f to your computer and use it in GitHub Desktop.
OpenSSL based server with TLS client-authentication enabled
#!/bin/bash
set -euo pipefail
PRIVATE_KEY="server_key.key"
PUBLIC_KEY="server_public.pem"
SERVER_CERTIFICATE="server_certificate.pem"
BIND_PORT=1234
TEMPLATE="
[ req ]
distinguished_name = req_distinguished_name
default_bits = 2048
default_md = sha256
prompt = no
req_extensions = v3_extensions
[ req_distinguished_name ]
C = US
ST = OR
L = Portland
O = Enlightened Corp
OU = Unnecessary Affairs
CN = authentication.demo.io
[ v3_extensions ]
keyUsage=critical, digitalSignature, keyEncipherment
extendedKeyUsage=critical,clientAuth,emailProtection
"
function generate_server_key() {
if [ -e $PRIVATE_KEY ] && [ -e $SERVER_CERTIFICATE ]
then return
fi
# Generate a new 2048b RSA keypair
export PASSPHRASE=`openssl rand -base64 16`
openssl genpkey -algorithm rsa -pkeyopt rsa_keygen_bits:2048 -out $PRIVATE_KEY -pass env:PASSPHRASE
# Compute the public-key
# (Work-around for openssl not outputting both during key generation)
openssl rsa -passin env:PASSPHRASE -in $PRIVATE_KEY -pubout -out $PUBLIC_KEY
# Prep CSR template for openssl
CSR_TEMPLATE=`mktemp server_csr_XXXXXX`
echo "$TEMPLATE" >> $CSR_TEMPLATE
# Use the CSR template to create a self-signed certificate based on this key-pair
openssl req -new -x509 -config $CSR_TEMPLATE -key $PRIVATE_KEY -out $SERVER_CERTIFICATE
# Clean up temporary file
rm $CSR_TEMPLATE
}
generate_server_key
# Launch the TLS server using that certificate and enable client-authentication
# Any command line parameters are passed to openssl
openssl s_server \
-accept $BIND_PORT \
-cert $SERVER_CERTIFICATE -key $PRIVATE_KEY \
-verify 2 -www \
"$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment