set -e

# -reqexts adds to the existing req_extentions list I guess. -extensions
# will replace it or whatever. By default openssl-req(1) would create
# CA:TRUE certficiates otherwise(!) but we just want client certificates.

# using v3_req we'd get CA:FALSE but it doesn't include the
# {Subject,Authority}KeyIdentifier stuff which is apparently needed to get
# this non-ca certificate to verify itself when used in a ca trust file/dir.

openssl req \
	-config /usr/lib/ssl/openssl.cnf \
	-new -newkey rsa:4096 -sha256 -nodes \
	-out ca.crt -keyout ca.key \
	-days 358201 -subj /CN=dxld-ca -x509 \
	-extensions usr_cert

openssl req -new -newkey rsa:4096 -sha256 -days 358201 -nodes \
	-config /usr/lib/ssl/openssl.cnf \
	-out dxld.csr -keyout dxld.key \
	-subj /CN=dxld

openssl x509 -req -days 360 \
	-CA ca.crt -CAkey ca.key -CAcreateserial -out dxld.crt -sha256 \
	-in dxld.csr

openssl verify -CAfile ca.crt ca.crt

if openssl verify -CAfile ca.crt dxld.crt; then
	echo 'this should fail!!!!'
	exit 1
fi

# GnuTLS' certtool --verify sets GNUTLS_VERIFY_DO_NOT_ALLOW_SAME which
# explicitly disallows the behaviour we're looking for here. I think this
# is not set by default though so real servers should allow this just fine.
#
# I verified this using:
#   $ gnutls-serv --x509keyfile ca.key --x509certfile ca.crt -p 12345 --echo&
#   $ gnutls-cli -p 1234 127.0.0.1 --x509cafile ca.crt --verify-hostname=dxld-ca
#
# And that works just fine.
if certtool --verify --infile ca.crt --load-ca-certificate=ca.crt; then
	echo 'this should fail!!!!'
	exit 1
fi

echo 'Good, test passed'
