#!/bin/bash

# Configure SSL for DB2 LUW on Linux
# Run this shell script while logged on as the DB2 instance owner e.g.
# su - db2inst1 

SERVER=mydbserver
# password for the certificate store
PASSWORD=mypassword
HOST=myhost.mydomain.com
COMPANY=MyCompany
CN=myhost.mydomain.com
CNCA=myhostCA.mydomain.com
LABEL=DB2
CALABEL=%SERVER%CA

DB2DIR=/opt/ibm/db2/V11.5
GSK=$DB2DIR/gskit/bin; export GSK
SSLDIR=$HOME/ssl
SSLPORT=50448

mkdir -p $SSLDIR
cd $SSLDIR

# Create the keystore
$GSK/gsk8capicmd_64 -keydb -create \
-db "$SERVER.kdb" -pw "$PASSWORD" -stash

# Create a self-signed CA certificate
$GSK/gsk8capicmd_64 -cert -create \
-db "$SERVER.kdb" -stashed \
-label "$CALABEL" \
-dn "CN=$CNCA,O=$COMPANY,OU=CustomerSupport,L=California,ST=ON,C=CA" \
-default_cert yes -ca true \
-size 2048 -sigalg SHA256_WITH_RSA

# Export the CA certificate for use by the client
$GSK/gsk8capicmd_64 -cert -extract -db "$SERVER.kdb" \
-pw "$PASSWORD" -label "$CALABEL" \
-target "$SSLDIR/$SERVER.arm" -format ascii -fips

# create CSR
$GSK/gsk8capicmd_64 -certreq -create -db "$SERVER.kdb" -stashed -label "$LABEL" -dn "CN=$CN,O=$COMPANY,OU=$COMPANY,L=San Francisco,ST=CA,C=US" -size 2048 -sigalg SHA256_WITH_RSA -target "$SERVER.csr"

# sign the cert
$GSK/gsk8capicmd_64 -cert -sign -file "$SERVER.csr" -db "$SERVER.kdb" -stashed -label "$CALABEL" -target "$SERVER-signed.arm" -expire 364

# install the certificate as defualt
$GSK/gsk8capicmd_64 -cert -receive -db "$SERVER.kdb" -stashed -file "$SERVER-signed.arm" -default_cert yes


# Update DB2 LUW server
db2 update dbm cfg using SSL_SVR_KEYDB "$SSLDIR/$SERVER.kdb"
db2 update dbm cfg using SSL_SVR_LABEL $LABEL
db2 update dbm cfg using SSL_SVR_STASH "$SSLDIR/$SERVER.sth"
db2 update dbm cfg using SSL_SVCENAME $SSLPORT
db2set DB2COMM=SSL,TCPIP

# Optional - enforce TLS 1.2
db2 update dbm cfg using ssl_versions TLSv12

# restart Db2
db2stop
db2start
