Published on

OpenSSL

Authors
  • Name
    Jackson Chen

References

https://geekflare.com/san-ssl-certificate/

https://support.f5.com/csp/article/K11438

How to setup your own CA with OpenSSL

https://gist.github.com/Soarez/9688998

Procedure to create CSR with SAN - Subject Alternative Name

In RHEL, the private key are stored in the following location

/etc/pki/tls/private/*.key

The certificates, including server certificate, intermediate and root certificates are stored in the directory

/etc/pki/tls/certs/*.crt

Create a SSL request configuration file

Create a SSL request configuration file, such as san.cfg

[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = req_ext
[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
stateOrProvinceName         = State or Province Name (full name)
localityName               = Locality Name (eg, city)
organizationName           = Organization Name (eg, company)
commonName                 = Common Name (e.g. server FQDN)
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1   = name1.com
DNS.2   = name2.com
DNS.3   = server-fqdn

Then copy the san.cfg file to the linux or RHEL server

Generate the CSR and Key file

SSH to the server, and run the following command to generate the CSR and key file

openssl req -out sslcert.csr -newkey rsa:2048 -nodes -keyout private.key -config san.cfg

Verify the CSR for SAN by run the command

openssl req -noout -text -in sslcert.csr | grep DNS
openssl req -noout -text -in sslcert.csr | grep -A1 "Subject Alternative Name"

Sign the certificate request

Using WinSCP to obtain the certificate request file, and run the command to sign the SSL request

# Using Windows CA to sign the SSL request
certreq -submit -attrib "CertificateTemplate:<Template-Name>  sslcert.csr  sslcert.cer

    Where
        Template name       # Example "Server Template with Client Authentication
                            # Important: Check the certificate template name
        sslcert.csr         # CSR to be signed
        sslcert.cer         # Signed SSL certificate
    
# To change cer format to CRT
1. Open the .cer file in NotePad++
2. Save the cer file to .crt

OpenSSL Certificate Authority

https://jamielinux.com/docs/openssl-certificate-authority/introduction.html

OpenSSL is a free and open-source cryptographic library that provides several command-line tools for handling digital certificates.

Setup and Create Root Certificate Authority

Typically, the root CA does not sign server or client certificates directly. The root CA is only ever used to create one or more intermediate CAs, which are trusted by the root CA to sign certificates on their behalf. This is best practice. It allows the root key to be kept offline and unused as much as possible, as any compromise of the root key is disastrous.

It’s best practice to create the root pair in a secure environment. Ideally, this should be on a fully encrypted, air gapped computer that is permanently isolated from the Internet.

Prepare the directory

Choose a directory (/root/ca) to store all keys and certificates.

# Create CA directory
    mkdir /root/ca

# Create the directory structure
The index.txt and serial files act as a flat file database to keep track of signed certificates.
    cd /root/ca
    mkdir certs crl newcerts private
    chmod 700 private
    touch index.txt
    echo 1000 > serial

Note: 
a. create a serial file with 1,000 serial.
b. Root CA serial number of 1,000 is sufficent, as it only sign Issuing CA SSL certificates
Prepare the configuration file

You must create a configuration file for OpenSSL to use.

# Root CA configuration file location
    /root/ca/openssl.cnf

Note:
The CA configuration file contains certificate profiles or templates section

The [ ca ] section is mandatory. Here we tell OpenSSL to use the options from the [ CA_default ] section.

[ ca ]
# `man ca`
default_ca = CA_default

The [ CA_default ] section contains a range of defaults. Make sure you declare the directory you chose earlier (/root/ca).

[ CA_default ]
# Directory and file locations.
dir               = /root/ca
certs             = $dir/certs
crl_dir           = $dir/crl
new_certs_dir     = $dir/newcerts
database          = $dir/index.txt
serial            = $dir/serial
RANDFILE          = $dir/private/.rand

# The root key and root certificate.
private_key       = $dir/private/ca.key.pem
certificate       = $dir/certs/ca.cert.pem

# For certificate revocation lists.
crlnumber         = $dir/crlnumber
crl               = $dir/crl/ca.crl.pem
crl_extensions    = crl_ext
default_crl_days  = 30

# SHA-1 is deprecated, so use SHA-2 instead.
default_md        = sha256

name_opt          = ca_default
cert_opt          = ca_default
default_days      = 375
preserve          = no
policy            = policy_strict

We’ll apply policy_strict for all root CA signatures, as the root CA is only being used to create intermediate CAs.

[ policy_strict ]
# The root CA should only sign intermediate certificates that match.
# See the POLICY FORMAT section of `man ca`.
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

We’ll apply policy_loose for all intermediate CA signatures, as the intermediate CA is signing server and client certificates that may come from a variety of third-parties.

[ policy_loose ]
# Allow the intermediate CA to sign a more diverse range of certificates.
# See the POLICY FORMAT section of the `ca` man page.
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

Options from the [ req ] section are applied when creating certificates or certificate signing requests.

[ req ]
# Options for the `req` tool (`man req`).
default_bits        = 2048
distinguished_name  = req_distinguished_name
string_mask         = utf8only

# SHA-1 is deprecated, so use SHA-2 instead.
default_md          = sha256

# Extension to add when the -x509 option is used.
x509_extensions     = v3_ca

The [ req_distinguished_name ] section declares the information normally required in a certificate signing request. You can optionally specify some defaults.

[ req_distinguished_name ]
# See <https://en.wikipedia.org/wiki/Certificate_signing_request>.
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name
localityName                    = Locality Name
0.organizationName              = Organization Name
organizationalUnitName          = Organizational Unit Name
commonName                      = Common Name
emailAddress                    = Email Address

# Optionally, specify some defaults.
countryName_default             = AU
stateOrProvinceName_default     = ACT
localityName_default            = Canberra
0.organizationName_default      = Test Lab
#organizationalUnitName_default = IT
#emailAddress_default           = 

The next few sections are extensions that can be applied when signing certificates. For example, passing the -extensions v3_ca command-line argument will apply the options set in [ v3_ca ].

We’ll apply the v3_ca extension when we create the root certificate.

[ v3_ca ]
# Extensions for a typical CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

We’ll apply the v3_ca_intermediate extension when we create the intermediate certificate. pathlen:0 ensures that there can be no further certificate authorities below the intermediate CA.

[ v3_intermediate_ca ]
# Extensions for a typical intermediate CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

We’ll apply the usr_cert extension when signing client certificates, such as those used for remote user authentication.

[ usr_cert ]
# Extensions for client certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = client, email
nsComment = "OpenSSL Generated Client Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, emailProtection

We’ll apply the server_cert extension when signing server certificates, such as those used for web servers.

[ server_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

The crl_ext extension is automatically applied when creating certificate revocation lists.

[ crl_ext ]
# Extension for CRLs (`man x509v3_config`).
authorityKeyIdentifier=keyid:always

We’ll apply the ocsp extension when signing the Online Certificate Status Protocol (OCSP) certificate.

[ ocsp ]
# Extension for OCSP signing certificates (`man ocsp`).
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, OCSPSigning

You could add additional section for different SSL certificate type, or template, such as

[ vmware_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated VMware Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

Create the root key

Create the root key (ca.key.pem) and keep it absolutely secure. Anyone in possession of the root key can issue trusted certificates. Encrypt the root key with AES 256-bit encryption and a strong password.

Use 4096 bits for all root and intermediate certificate authority keys. You’ll still be able to sign server and client certificates of a shorter length.

# Procedure
    cd /root/ca
    openssl genrsa -aes256 -out private/ca.key.pem 4096

Then, Enter pass phrase for ca.key.pem: <RequiredandComplexPassPhrase>
Verifying - Enter pass phrase for ca.key.pem: <RequiredandComplexPassPhrase>

# sure the private key
    chmod 400 private/ca.key.pem

Create the root certificate

Use the root key (ca.key.pem) to create a root certificate (ca.cert.pem). Give the root certificate a long expiry date, such as twenty years.

Note:
    Once the root certificate expires, all certificates signed by the CA become invalid.

Whenever you use the req tool, you must specify a configuration file to use with the -config option, otherwise OpenSSL will default to /etc/pki/tls/openssl.cnf

# Use the configured /root/ca/...... openssl.cnf

The steps as follows

cd /root/ca
openssl req -config openssl.cnf \
      -key private/ca.key.pem \
      -new -x509 -days 7300 -sha256 -extensions v3_ca \
      -out certs/ca.cert.pem

Enter pass phrase for ca.key.pem: secretpassword
You are about to be asked to enter information that will be incorporated
into your certificate request.

Country Name (2 letter code) [AU]:AU
State or Province Name [ACT]:
Locality Name [Canberra]:
Organization Name []:Test Lab
Organizational Unit Name []:Test Lab Certificate Authority
Common Name []:Test Lab Root CA
Email Address []:

# Important - Secure the Root CA private key
chmod 444 certs/ca.cert.pem
Verify the root certificate
# Command
openssl x509 -noout -text -in certs/ca.cert.pem

The output shows:

  1. the Signature Algorithm used
  2. the dates of certificate Validity
  3. the Public-Key bit length
  4. the Issuer, which is the entity that signed the certificate
  5. the Subject, which refers to the certificate itself

The Issuer and Subject are identical as the certificate is self-signed.

# Note
    all root certificates are self-signed.

The output also shows the X509v3 extensions. We applied the v3_ca extension, so the options from [ v3_ca ] should be reflected in the output.

# ********* Root CA configuration file *********

# OpenSSL root CA configuration file.
# Copy to `/root/ca/openssl.cnf`.

[ ca ]
# `man ca`
default_ca = CA_default

[ CA_default ]
# Directory and file locations.
dir               = /root/ca
certs             = $dir/certs
crl_dir           = $dir/crl
new_certs_dir     = $dir/newcerts
database          = $dir/index.txt
serial            = $dir/serial
RANDFILE          = $dir/private/.rand

# The root key and root certificate.
private_key       = $dir/private/ca.key.pem
certificate       = $dir/certs/ca.cert.pem

# For certificate revocation lists.
crlnumber         = $dir/crlnumber
crl               = $dir/crl/ca.crl.pem
crl_extensions    = crl_ext
default_crl_days  = 30

# SHA-1 is deprecated, so use SHA-2 instead.
default_md        = sha256

name_opt          = ca_default
cert_opt          = ca_default
default_days      = 375
preserve          = no
policy            = policy_strict

[ policy_strict ]
# The root CA should only sign intermediate certificates that match.
# Important: 
# Set "organizationName        = optional"
# See the POLICY FORMAT section of `man ca`.
countryName             = match
stateOrProvinceName     = match
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ policy_loose ]
# Allow the intermediate CA to sign a more diverse range of certificates.
# See the POLICY FORMAT section of the `ca` man page.
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ req ]
# Options for the `req` tool (`man req`).
default_bits        = 2048
distinguished_name  = req_distinguished_name
string_mask         = utf8only

# SHA-1 is deprecated, so use SHA-2 instead.
default_md          = sha256

# Extension to add when the -x509 option is used.
x509_extensions     = v3_ca

[ req_distinguished_name ]
# See <https://en.wikipedia.org/wiki/Certificate_signing_request>.
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name
localityName                    = Locality Name
0.organizationName              = Organization Name
organizationalUnitName          = Organizational Unit Name
commonName                      = Common Name
emailAddress                    = Email Address

# Optionally, specify some defaults.
countryName_default             = AU
stateOrProvinceName_default     = ACT
localityName_default            = Canberra
0.organizationName_default      = Test Lab
organizationalUnitName_default  = IT
emailAddress_default            =

[ v3_ca ]
# Extensions for a typical CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ v3_intermediate_ca ]
# Extensions for a typical intermediate CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ usr_cert ]
# Extensions for client certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = client, email
nsComment = "OpenSSL Generated Client Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, emailProtection

[ server_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

[ crl_ext ]
# Extension for CRLs (`man x509v3_config`).
authorityKeyIdentifier=keyid:always

[ ocsp ]
# Extension for OCSP signing certificates (`man ocsp`).
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, OCSPSigning

Ceate Intermediate Certificate Authority

An intermediate certificate authority (CA) is an entity that can sign certificates on behalf of the root CA. The root CA signs the intermediate certificate, forming a chain of trust.

The purpose of using an intermediate CA is primarily for security. The root key can be kept offline and used as infrequently as possible. If the intermediate key is compromised, the root CA can revoke the intermediate certificate and create a new intermediate cryptographic pair.

Intermediate CA configuration file

# OpenSSL intermediate CA configuration file.
# Copy to `/root/ca/intermediate/openssl.cnf`.

[ ca ]
# `man ca`
default_ca = CA_default

[ CA_default ]
# Directory and file locations.
dir               = /root/ca/intermediate
certs             = $dir/certs
crl_dir           = $dir/crl
new_certs_dir     = $dir/newcerts
database          = $dir/index.txt
serial            = $dir/serial
RANDFILE          = $dir/private/.rand

# The root key and root certificate.
private_key       = $dir/private/intermediate.key.pem
certificate       = $dir/certs/intermediate.cert.pem

# For certificate revocation lists.
crlnumber         = $dir/crlnumber
crl               = $dir/crl/intermediate.crl.pem
crl_extensions    = crl_ext
default_crl_days  = 30

# SHA-1 is deprecated, so use SHA-2 instead.
default_md        = sha256

name_opt          = ca_default
cert_opt          = ca_default
default_days      = 375
preserve          = no
policy            = policy_loose

[ policy_strict ]
# The root CA should only sign intermediate certificates that match.
# See the POLICY FORMAT section of `man ca`.
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ policy_loose ]
# Allow the intermediate CA to sign a more diverse range of certificates.
# See the POLICY FORMAT section of the `ca` man page.
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ req ]
# Options for the `req` tool (`man req`).
default_bits        = 2048
distinguished_name  = req_distinguished_name
string_mask         = utf8only

# SHA-1 is deprecated, so use SHA-2 instead.
default_md          = sha256

# Extension to add when the -x509 option is used.
x509_extensions     = v3_ca

[ req_distinguished_name ]
# See <https://en.wikipedia.org/wiki/Certificate_signing_request>.
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name
localityName                    = Locality Name
0.organizationName              = Organization Name
organizationalUnitName          = Organizational Unit Name
commonName                      = Common Name
emailAddress                    = Email Address

# Optionally, specify some defaults.
countryName_default             = AU
stateOrProvinceName_default     = ACT
localityName_default            = Canberra
0.organizationName_default      = Test Lab
organizationalUnitName_default  = IT
emailAddress_default            =

[ v3_ca ]
# Extensions for a typical CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ v3_intermediate_ca ]
# Extensions for a typical intermediate CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ usr_cert ]
# Extensions for client certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = client, email
nsComment = "OpenSSL Generated Client Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, emailProtection

[ server_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

[ vmware_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

[ crl_ext ]
# Extension for CRLs (`man x509v3_config`).
authorityKeyIdentifier=keyid:always

[ ocsp ]
# Extension for OCSP signing certificates (`man ocsp`).
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, OCSPSigning

Prepare the directory

The root CA files are kept in /root/ca. Choose a different directory (/root/ca/intermediate) to store the intermediate CA files.

# Create intermediate / issuing CA directory
    mkdir /root/ca/intermediate

Create the same directory structure used for the root CA files. It’s convenient to also create a csr directory to hold certificate signing requests. Set large number for serial, as the issuing CA will issue all the clients and servers SSL certificates.

    cd /root/ca/intermediate
    mkdir certs crl csr newcerts private
    chmod 700 private
    touch index.txt
    echo 100000 > serial

Add a crlnumber file to the intermediate CA directory tree. crlnumber is used to keep track of certificate revocation lists.

# Create certificate revocation list number, the same number as the serial
    echo 100000 > /root/ca/intermediate/crlnumber

Copy the intermediate CA configuration file from the Appendix to /root/ca/intermediate/openssl.cnf. Five options have been changed compared to the root CA configuration file:

[ CA_default ]
dir             = /root/ca/intermediate
private_key     = $dir/private/intermediate.key.pem
certificate     = $dir/certs/intermediate.cert.pem
crl             = $dir/crl/intermediate.crl.pem
policy          = policy_loose

Create the intermediate key

Create the intermediate key (intermediate.key.pem). Encrypt the intermediate key with AES 256-bit encryption and a strong password.

# cd /root/ca
# openssl genrsa -aes256 \
      -out intermediate/private/intermediate.key.pem 4096

Enter pass phrase for intermediate.key.pem: <RequiredandComplexPassPhrase>
Verifying - Enter pass phrase for intermediate.key.pem: <RequiredandComplexPassPhrase>

# chmod 400 intermediate/private/intermediate.key.pem

Create the intermediate certificate

Use the intermediate key to create a certificate signing request (CSR). The details should generally match the root CA. The Common Name, however, must be different.

# Warning
    Make sure you specify the intermediate CA configuration file (intermediate/openssl.cnf)
# Create intermediate CA SSL certificate request file (csr)
    cd /root/ca
    openssl req -config intermediate/openssl.cnf -new -sha256 \
        -key intermediate/private/intermediate.key.pem \
        -out intermediate/csr/intermediate.csr.pem

Enter pass phrase for intermediate.key.pem: secretpassword
You are about to be asked to enter information that will be incorporated
into your certificate request.

Country Name (2 letter code) [AU]:AU
State or Province Name [ACT]:ACT
Locality Name [Canberra]:Canberra
Organization Name []:Test Lab
Organizational Unit Name []:Test Lab Certificate Authority
Common Name []:Test Lab Intermediate CA
Email Address []:

To create an intermediate certificate, use the root CA with the v3_intermediate_ca extension to sign the intermediate CSR. The intermediate certificate should be valid for a shorter period than the root certificate. Ten years would be reasonable.

# Warning
    This time, specify the root CA configuration file (/root/ca/openssl.cnf).
# Create intermediate CA SSL certificate request file
    cd /root/ca
    openssl ca -config openssl.cnf -extensions v3_intermediate_ca \
        -days 3650 -notext -md sha256 \
        -in intermediate/csr/intermediate.csr.pem \
        -out intermediate/certs/intermediate.cert.pem

Enter pass phrase for ca.key.pem: secretpassword
Sign the certificate? [y/n]: y

# Secure the private key
    chmod 444 intermediate/certs/intermediate.cert.pem

The index.txt file is where the OpenSSL ca tool stores the certificate database.It should now contain a line that refers to the intermediate certificate.

# Note
    Do not delete or edit this file by hand. 

Verify the intermediate certificate

As we did for the root certificate, check that the details of the intermediate certificate are correct.

Sign the intermediate SSL certificate request from the newly create root certificate authority.

# Verify the signed intermediate certificate after signing by root CA 
    openssl x509 -noout -text \
        -in intermediate/certs/intermediate.cert.pem

Verify the intermediate certificate against the root certificate. An OK indicates that the chain of trust is intact.

# Verify the newly signed intermediate certificate against the root certificate
    openssl verify -CAfile certs/ca.cert.pem \
        intermediate/certs/intermediate.cert.pem

Note:
    Result: intermediate.cert.pem: OK
Create the certificate chain file

When an application (eg, a web browser) tries to verify a certificate signed by the intermediate CA, it must also verify the intermediate certificate against the root certificate. To complete the chain of trust, create a CA certificate chain to present to the application.

To create the CA certificate chain, concatenate the intermediate and root certificates together. We will use this file later to verify certificates signed by the intermediate CA.

# Concatenate CA certificat chain
    cat intermediate/certs/intermediate.cert.pem \
        certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem
    
    chmod 444 intermediate/certs/ca-chain.cert.pem

Sign server and client certificates

We will be signing certificates using our intermediate CA. You can use these signed certificates in a variety of situations, such as to secure connections to a web server or to authenticate clients connecting to a service.

Create a key

Our root and intermediate pairs are 4096 bits. Server and client certificates normally expire after one year, so we can safely use 2048 bits instead.

If you’re creating a cryptographic pair for use with a web server (eg, Apache), you’ll need to enter this password every time you restart the web server.

# Create server or client certificate key
    cd /root/ca

    openssl genrsa -aes256 \
        -out intermediate/private/www.example.com.key.pem 2048
Note:
You may want to omit the -aes256 option to create a key without a password.

    chmod 400 intermediate/private/www.example.com.key.pem

Create a certificate

Use the private key to create a certificate signing request (CSR). The CSR details don’t need to match the intermediate CA. For server certificates, the Common Name must be a fully qualified domain name (eg, www.example.com), whereas for client certificates it can be any unique identifier (eg, an e-mail address).

# Note
The Common Name cannot be the same as either your root or intermediate certificate.
# Create server or client certificate request CSR
    cd /root/ca
    openssl req -config intermediate/openssl.cnf \
        -key intermediate/private/www.example.com.key.pem \
        -new -sha256 -out intermediate/csr/www.example.com.csr.pem

Enter pass phrase for www.example.com.key.pem: secretpassword
You are about to be asked to enter information that will be incorporated
into your certificate request.

Country Name (2 letter code) [XX]:AU
State or Province Name []:ACT
Locality Name []:Canberra
Organization Name []:Test Lab
Organizational Unit Name []:Test Lab Web Services
Common Name []:www.example.com
Email Address []:

To create a certificate, use the intermediate CA to sign the CSR. If the certificate is going to be used on a server, use the server_cert extension. If the certificate is going to be used for user authentication, use the usr_cert extension. Certificates are usually given a validity of one year, though a CA will typically give a few days extra for convenience.

# Sign the server or client certificate request by the OpenSSL intermediate certificate authority
    cd /root/ca
    openssl ca -config intermediate/openssl.cnf \
        -extensions server_cert -days 375 -notext -md sha256 \
        -in intermediate/csr/www.example.com.csr.pem \
        -out intermediate/certs/www.example.com.cert.pem
    
    chmod 444 intermediate/certs/www.example.com.cert.pem

The intermediate/index.txt file should contain a line referring to this new certificate.

Verify the certificate

# Verify the newly signed server or client certificate
    openssl x509 -noout -text \
        -in intermediate/certs/www.example.com.cert.pem

The Issuer is the intermediate CA. The Subject refers to the certificate itself. The output will also show the X509v3 extensions. When creating the certificate, you used either the server_cert or usr_cert extension. The options from the corresponding configuration section will be reflected in the output.

Use the CA certificate chain file we created earlier (ca-chain.cert.pem) to verify that the new certificate has a valid chain of trust.

# Verify the server or client certificate against the RCA & ICA chain file
    openssl verify -CAfile intermediate/certs/ca-chain.cert.pem \
        intermediate/certs/www.example.com.cert.pem

# Result
    www.example.com.cert.pem: OK

Deploy the certificate

You can now either deploy your new certificate to a server, or distribute the certificate to a client. When deploying to a server application (eg, Apache), you need to make the following files available:

# The following files will be deploy to the server or client
    ca-chain.cert.pem
    www.example.com.key.pem
    www.example.com.cert.pem

Certificate revocation lists

A certificate revocation list (CRL) provides a list of certificates that have been revoked. A client application, such as a web browser, can use a CRL to check a server’s authenticity. A server application, such as Apache or OpenVPN, can use a CRL to deny access to clients that are no longer trusted.

Publish the CRL at a publicly accessible location (eg, http://example.com/intermediate.crl.pem). Third-parties can fetch the CRL from this location to check whether any certificates they rely on have been revoked.

# Note - OCSP
Some applications vendors have deprecated CRLs and are instead using the Online Certificate Status Protocol (OCSP).
Prepare the configuration file

When a certificate authority signs a certificate, it will normally encode the CRL location into the certificate. Add crlDistributionPoints to the appropriate sections. In our case, add it to the [ server_cert ] section.

[ server_cert ]
# ... snipped ...
crlDistributionPoints = URI:http://example.com/intermediate.crl.pem

Create the CRL

# Create CRL
    cd /root/ca
    openssl ca -config intermediate/openssl.cnf \
        -gencrl -out intermediate/crl/intermediate.crl.pem

You can check the contents of the CRL with the crl tool.

# openssl crl -in intermediate/crl/intermediate.crl.pem -noout -text

You should re-create the CRL at regular intervals. By default, the CRL expires after 30 days. This is controlled by the default_crl_days option in the [ CA_default ] section.

# Procedure to revoke ssl certificate
    cd /root/ca
    openssl ca -config intermediate/openssl.cnf \
        -revoke intermediate/certs/bob@example.com.cert.pem

Enter pass phrase for intermediate.key.pem: secretpassword
Revoking Certificate 1001.
Data Base Updated

The line in index.txt that corresponds to revoked certificate now begins with the character R. This means the certificate has been revoked.

R 160420124740Z 150411125310Z 1001 unknown ... /CN=testing@example.com

Online Certificate Status Protocol

The Online Certificate Status Protocol (OCSP) was created as an alternative to certificate revocation lists (CRLs). Similar to CRLs, OCSP enables a requesting party (eg, a web browser) to determine the revocation state of a certificate.

When a CA signs a certificate, they will typically include an OCSP server address (eg, http://ocsp.example.com) in the certificate. This is similar in function to crlDistributionPoints used for CRLs.

Prepare the configuration file

To use OCSP, the CA must encode the OCSP server location into the certificates that it signs. Use the authorityInfoAccess option in the appropriate sections, which in our case means the [ server_cert ] section.

[ server_cert ]
# ... snipped ...
authorityInfoAccess = OCSP;URI:http://ocsp.example.com
Create the OCSP pair

The OCSP responder requires a cryptographic pair for signing the response that it sends to the requesting party. The OCSP cryptographic pair must be signed by the same CA that signed the certificate being checked.

Create a private key and encrypt it with AES-256 encryption.

# Create a private key
    cd /root/ca
    openssl genrsa -aes256 \
        -out intermediate/private/ocsp.example.com.key.pem 4096

Note:
Do not encrypt private key
    openssl genrsa -out intermediate/private/ocsp.example.com.key.pem 4096

Create a certificate signing request (CSR). The details should generally match those of the signing CA. The Common Name, however, must be a fully qualified domain name.

# cd /root/ca
# openssl req -config intermediate/openssl.cnf -new -sha256 \
      -key intermediate/private/ocsp.example.com.key.pem \
      -out intermediate/csr/ocsp.example.com.csr.pem

Sign the CSR with the intermediate CA.

# openssl ca -config intermediate/openssl.cnf \
      -extensions ocsp -days 375 -notext -md sha256 \
      -in intermediate/csr/ocsp.example.com.csr.pem \
      -out intermediate/certs/ocsp.example.com.cert.pem

Verify that the certificate has the correct X509v3 extensions.

# openssl x509 -noout -text \
      -in intermediate/certs/ocsp.example.com.cert.pem
Server Certificate Configuration File (cnf)
# OpenSSL configuration file for creating a CSR for web server
#
# 1. Generate the private key
# Run command:
# cd /root/ca
# openssl genrsa \
      -out intermediate/private/webserver01.test.lab.key.pem 2048
# chmod 400 intermediate/private/webserver01.test.lab.key.pem
#

# 2. Generate Certificate Signing Request (CSR)
# Run command:
# cd /root/ca
# openssl req -config intermediate/blackrouter.cnf \
#   -key intermediate/private/webserver01.test.lab.key.pem \
#   -new -sha256 -out intermediate/csr/webserver01.test.lab.csr.pem 
#


[ req ]
default_bits        = 2048
default_md = sha256

distinguished_name  = req_distinguished_name
encrypt_key = no
prompt = no
string_mask = nombstr
req_extensions = v3_req

[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = DNS:webserver01,DNS:webserver01.test.lab,DNS:192.168.1.100

[ req_distinguished_name ]
countryName         = AU
stateOrProvinceName     = ACT
localityName            = Canberra
0.organizationName      = Test Lab
organizationalUnitName      = IT
commonName          = webserver01.test.lab
emailAddress            = admin@test.lab
#************************* Alternative format *********************
# OpenSSL configuration file for creating a CSR for mobility black router
#
# 1. Generate the private key
# Run command:
# cd /root/ca
# openssl genrsa \
      -out intermediate/private/webserver01.test.lab.key.pem 2048
# chmod 400 intermediate/private/webserver01.test.lab.key.pem
#

# 2. Generate Certificate Signing Request (CSR)
# Run command:
# cd /root/ca
# openssl req -config intermediate/blackrouter.cnf \
#   -key intermediate/private/webserver01.test.lab.key.pem \
#   -new -sha256 -out intermediate/csr/webserver01.test.lab.csr.pem 
#


[ req ]

prompt             = no
encrypt_key        = no
string_mask        = default

# The size of the keys in bits:
default_bits       = 2048
default_md     = sha256
distinguished_name = req_dn
req_extensions     = req_ext

[ req_dn ]

# Note that the following are in 'reverse order' to what you'd expect to see in
# Windows and the numbering is irrelevant as long as each line's number differs.

# Locality style:
countryName = AU
stateOrProvinceName = ACT
localityName = Canberra
organizationName = ASN Black
organizationalUnitName = IT Dept
commonName = Mobility Black Router 01

# Or traditional org style:
# countryName = AU
# stateOrProvinceName = ACT
# organizationName = ASN Black
# organizationalUnitName = IT Dept
# commonName = Mobility Black Router 01

[ req_ext ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth

subjectAltName = @alt_names

[alt_names]
# To copy the CN (in the case of a DNS name in the CN) use:
# DNS = ${req_dn::commonName}
DNS.1 = webserver01
DNS.2 = webserver01.test.lab
DNS.3 = 192.168.1.1
#*************************************************************************************

Server Certificate Request Automation

#!/bin/bash

#
# Purpose:
#   Test Web Server Certificate Request
#
# Environment:
#    Test Lab
#
# Important:
#   Restrict the script only can be accessible by root
#       chmod 700 /usr/local/bin/scripts/webservercertrequest.sh
#
#

# Ensure run script as root
if [[ $EUID -ne 0 ]]
then
    echo -e "Warning: You need to run this script as root"
    exit 1
fi


WebServer01Key=/root/ca/intermediate/private/webserver01.test.lab.key.pem


#
# Generate the web server private key in PEM format
# 
if [ -f "$WebServer01Key" ]
then
    echo -e "\nThe web server priviate key already exist.\nFile location: $WebServer01Key"
    echo -e "\nChecking webserver private key\n"
    
    # Check webserver private key
    openssl rsa -in $WebServer01Key -check
    
else
    echo -e "\nGenerate pivate key for web server."
    openssl genrsa -out "$WebServer01Key" 2048
    
    # Pause for 2 seconds
    sleep 2
    
    if [ -f "$WebServer01Key" ]
    then
        # Secure the newly created private key
        echo -e "\nThe request private key for web server has been created.\nKey location: $WebServer01Key"
        chmod 400 $WebServer01Key
    
        # Check the newly create private key
        echo -e "\nChecking webserver private key\n"
        openssl rsa -in $WebServer01Key -check
        echo ""
    fi
fi


#
# Generate the certificate signing request (csr) file
#

WebServer01Cnf=/root/ca/intermediate/webservercert.cnf
WebServer01CSR=/root/ca/intermediate/csr/webserver01.test.lab.csr.pem

if [ -f "$WebServer01CSR" ]
then
    echo -e "\nThe web server certificate signing request file already exist.\nCSR file location: $WebServer01CSR"
    echo -e "\nChecking the webserver certificate signing request file\n"
    
    # Check webserver CSR
    openssl req -text -noout -verify -in $WebServer01CSR
    echo ""
else
    echo -e "\nGenerate the certificate signing request based on webserver configuration file"
    openssl req -config $WebServer01Cnf -key $WebServer01Key -new -sha256 -out $WebServer01CSR

    if [ -f "$WebServer01CSR" ]
    then
        echo -e "\nThe web server certificate signing request file location - $WebServer01CSR"
        
        # Check the webserver certificate signing request file
        openssl req -text -noout -verify -in $WebServer01CSR
        echo ""
    fi
fi


#
# Sign web server certificate request with webserver certificate template
#

ICAopenSSLCNF=/root/ca/intermediate/openssl.cnf
ICAcertFile=/root/ca/intermediate/certs/intermediate.pem
ICAKeyFile=/root/ca/intermediate/private/intermediate.key.pem
webserverCertTemplate="webserver_cert"
certDays="365"
WebServer01CertFile=/root/ca/intermediate/certs/webservertest.test.lab.cert.pem

if [ -f "WebServer01CertFile" ]
then
    echo -e "\nThe web server certificate file already exist.\nCertificate location: $WebServer01CertFile"  
    echo -e "\nVerify the web server certificate\n"
    
    # Verify the web server certificate
    openssl x509 -in $WebServer01CertFile -text -noout
    echo ""
else
    # Sign the web server certificate request
    # Using "webserver_cert" template
    
    # Verify intermediate CA private key
    # openssl rsa -in /root/ca/intermediate/private/intermediate.key.pem
    # 
    # Note: 
    # 1. It will prompt for the pass phrase
    # 2. consult secretserver for the pass phrase
    
    #
    # Secure the passin (pass phrase)
    # 
    sudo openssl x509 \
    -passin pass:'xxxxxxxxEnterPassHerexxxxxxxxx' \
    -req \
    -in $WebServer01CSR \
    -CA $ICAcertFile \
    -CAkey $ICAKeyFile \
    -CAcreateserial \
    -out $WebServer01CertFile \
    -days $certDays
    
    
    if [ -f "$WebServer01CertFile" ]
    then
        chmod 444 $WebServer01CertFile
        echo -e "\nVerify the web server certificate\n"
    
        # Verify the web server certificate
        openssl x509 -in $WebServer01CertFile -text -noout
    fi
 
fi


#
# Create web server certificate p12 file
#
WebServer01P12File=/root/ca/intermediate/p12/webservertest.mobility.p12

if [ -f "WebServer01P12File" ] 
then
    echo -e "\nThe web server p12 file already exist.\nFile locaton: $WebServer01P12File"
else
    if [ -f "$WebServer01CertFile" ]
    then
        if [ -f "$WebServer01Key" ]
        then
            sudo openssl pkcs12 -export -out $WebServer01P12File -inkey $WebServer01Key -in $WebServer01CertFile
            
            if [ -f "$WebServer01P12File" ]
            then
                echo -e "\nThe web server p12 file has been succcessfully been created.\nFile location: $WebServer01P12File"
            fi
        else
            echo -e "\nThe web server private key does not exist."
        fi
    else
        echo -e "\nThe web server certificate does not exist."
    fi
fi

OpenSSL Create certificate chain with Root and Intermediat CA

https://www.golinuxcloud.com/openssl-create-certificate-chain-linux/

https://dadhacks.org/2017/12/27/building-a-root-ca-and-an-intermediate-ca-using-openssl-and-debian-stretch/

https://roll.urown.net/ca/ca_intermed_setup.html

Note:
Create the serial file, to store next incremental serial number.
Using random instead of incremental serial numbers is a recommended security practice:

$ openssl rand -hex 16 > intermed-ca.serial
Signing Certificates

https://roll.urown.net/ca/ca_cert.html

Automation References

https://www.golinuxcloud.com/shell-script-to-generate-certificate-openssl/

https://mycyberuniverse.com/linux/ssl-certificate-automatically-by-a-bash-script.html

openssl req -x509 -newkey rsa:2048 -keyout examplekey.pem -out examplecert.pem -nodes -days 365 -set_serial NNNNN -subj "/C=AU/L=Any City/OU=Test Lab/CN=*.example.com"
# Sign Intermediate CA certificate
openssl ca -config openssl.cnf -extensions v3_intermediate_ca -days 2650 -notext -batch -passin file:mypass.enc -in intermediate/csr/intermediate.csr.pem -out intermediate/certs/intermediate.cert.pem

# Create RootCA and ICA certificate chain
cat rootca.pem ica.pem > ca-chain-bundle.cert.pem

# Request and sign server certificate commands
openssl x509 -req -in client.csr -passin file:mypass.enc -CA /root/tls/intermediate/certs/ca-chain-bundle.cert.pem -CAkey /root/tls/intermediate/private/intermediate.key.pem -out client.cert.pem -CAcreateserial -days 365 -sha256 -extfile client_cert_ext.cnf

How to create CSR for a SAN certificate

https://docs.druva.com/Knowledge_Base/inSync/How_To/How_to_create_CSR_for_a_SAN_certificate#:~:text=Create%20a%20CSR%20for%20a%20SAN%20certificate,-Login%20to%20the&text=Open%20the%20command%20prompt%20as,KEY%20file%20with%20this%20command.&text=Enter%20the%20details%20to%20complete,of%20the%20inSync%20master%20server.

https://www.golinuxcloud.com/openssl-subject-alternative-name/

This article provides the steps to create a Certificate Signing Request (CSR) for a SAN certificate using an OpenSSL tool.

  1. Login to the server installed with the OpenSSL tool.
  2. Create a file named server_cert.cnf with the following information at the location: C:\OpenSSL-WinXX\bin
[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = req_ext
[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
stateOrProvinceName         = State or Province Name (full name)
localityName               = Locality Name (eg, city)
organizationName           = Organization Name (eg, company)
commonName                 = Common Name (e.g. server FQDN or YOUR name)
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1   = test.domain.com
DNS.2   = test2.domain.com
DNS.3   = test3.domain.com
IP.1    = 192.168.10.100
  1. Verify the server FQDN mentioned under alt_names, where alt_names section is the one you have to change for additional DNS.
  2. Open the command prompt as an administrator and change the directory to C:\OpenSSL-WinXX\bin.
  3. Generate the CSR and KEY file with this command.
openssl req -out server.csr -newkey rsa:2048 -key server.key -config server_cert.cnf
  1. Enter the details to complete the CSR. Common Name must be the FQDN of the inSync master server.
  2. Convert the server.key to RSA format using:
openssl rsa -in server.key -out myserver.key
  1. You now have the myserver.key file in the required RSA format. Thus, the CSR and private key are created.

Verification

  1. To verify the CSR for SAN:
  2. Open the command prompt as an administrator and change the directory to C:\OpenSSL-WinXX\bin and run:
openssl req -noout -text -in server.csr
openssl req -noout -text -in server.csr | grep DNS
openssl req -noout -text -in server.csr | grep IP

Under Subject Alternative Name, the different DNS names must appear for which this CSR is valid.

DNS:test.domain.com, DNS:test2.domain.com, DNS:test3.domain.com, IP Address:192.168.10.100

Example on how to create server certificate with SAN temple

https://www.golinuxcloud.com/openssl-subject-alternative-name/

# Generate private key
openssl genrsa -out server.key 4096

# Generate csr
We will not use the complete /root/ca/intermediate/openssl.cnf,
instead we will create our own custom ssl configuration file server_cert.cnf with required parameters only.
Note:
    To generate CSR for SAN we need distinguished_name and req_extensions

Example of server_cert.cnf

[req]
distinguished_name = req_distinguished_name
req_extensions = req_ext
prompt = no

[req_distinguished_name]
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name (full name)
localityName                    = Locality Name (eg, city)
organizationalUnitName          = Organizational Unit Name (eg, section)
commonName                      = Common Name (eg, your name or your server\'s hostname)
emailAddress                    = Email Address

[req_ext]
subjectAltName = @alt_names

[alt_names]
IP.1 = 10.10.10.13
IP.2 = 10.10.10.14
IP.3 = 10.10.10.17
DNS.1 = centos8-2.example.com
DNS.2 = centos8-3.example.com

# Generate csr
openssl req -new -key server.key -out server.csr -config server_cert.cnf

Note: 
    Since we have used prompt=no and have also provided the CSR information, 
    there is no output for this command but our CSR is generated

# Verify Subject Alternative Name from csr
openssl req -noout -text -in server.csr | grep -A 1 "Subject Alternative Name"

Note: We get an empty output. The SAN Extensions are missing from our certificate.

Missing SAN Extensions from the Certificate

  1. This is an expected behaviour. As per official documentation from openssl
  2. Extensions in certificates are not transferred to certificate requests and vice versa.
  3. Due to this, the extensions which we added in our CSR were not transferred by default to the certificate. So these extensions must be added to the certificate explicitly.

Generate SAN Certificates with X509 extensions

  1. We need to use -extensions argument with the name of the extension to be used from the configuration file.
  2. We have defined our SAN fields under req_ext extension so we will use the following command to generate the certificate
openssl x509 -req -days 365 -in server.csr -CA /root/ca/intermediate/certs/ca-chain.pem -CAkey /root/ca/intermediate/private/intermediate.key.pem

Note:
1. If do not want to be prompted for private key pass phrase
a. Remove the pass phrase
    openssl -in <intermediate.key.pem> -out <new.key.pem>
        Note: It will prompt to enter the pass phrase
    cp intermediate.key.pem intermediate.org.key.pem
    cp new.key.pem intermediate.key.pem


# openssl x509 -text -noout -in server.crt | grep -A 1 "Subject Alternative Name"                            
X509v3 Subject Alternative Name:
    IP Address:10.10.10.13,  DNS:centos8-2.example.com  

Example

#!/bin/bash

#
# File Name: Create_WebServer_Certificate.sh
# 
# Purpose:
#   Test WebServer Certificate Signing Request
#
#

webserverKey=/root/ca/intermediate/private/webserver.test.lab.key.pem


#
# Generate the webserver private key in PEM format
# 
if [ -f "$webserverKey" ]
then
    echo -e "\nThe webserver priviate key already exist.\nFile location: $webserverKey"
    echo -e "\nChecking webserver private key\n"
    
    # Check webserver private key
    openssl rsa -in $webserverKey -check
    
else
    echo -e "\nGenerate pivate key for webserver."
    openssl genrsa -out "$webserverKey" 2048
    
    # Pause for 2 seconds
    sleep 2
    
    if [ $? -eq 0 ]
    then
        # Secure the newly created private key
        echo -e "\nThe request private key for webserver has been created.\nKey location: $webserverKey"
        chmod 400 $webserverKey
    
        # Check the newly create private key
        echo -e "\nChecking webserver private key\n"
        openssl rsa -in $webserverKey -check
        echo ""
    else
        echo -e "\nWarning: Failed to generate webserver private key. Please verify and run the script again"
        exit 1
    fi
fi


#
# Generate the certificate signing request (csr) file
#

webserverCnf=/root/ca/intermediate/webservercert.cnf
webserverCSR=/root/ca/intermediate/csr/webserver.test.lab.csr.pem

# Verify whether the webserver certificate signing request file exist
# Only generate the CSR file when not already exist
if [ -f "$webserverCSR" ]
then
    echo -e "\nThe webserver certificate signing request file already exist.\nCSR file location: $webserverCSR"
    echo -e "\nChecking the webserver certificate signing request file\n"
    
    # Check webserver CSR
    openssl req -text -noout -verify -in $webserverCSR
    echo ""
else
    echo -e "\nGenerate the certificate signing request based on webserver configuration file"
    openssl req -new -key $webserverKey -sha256 -out $webserverCSR -config $webserverCnf

    if [ -f "$webserverCSR" ]
    then
        echo -e "\nThe webserver certificate signing request file location - $webserverCSR"
        
        # Check the webserver certificate signing request file
        openssl req -text -noout -verify -in $webserverCSR
        echo -e "\nVerify webserver CSR Subject Alternative Name\nImportant: Ensure it contains DNS entries and IP address.\n"
        openssl req -noout -text -in $webserverCSR | grep -A 1 "Subject Alternative Name"
        echo ""
    fi
fi


#
# Sign webserver certificate request with webserver certificate template
#

intermediateCertFile=/root/ca/intermediate/certs/intermediate.pem
ICAKeyFile=/root/ca/intermediate/private/intermediate.key.pem
webserverCertExtensions="v3_ca"
webserverCnf=/root/ca/intermediate/webservercert.cnf
certDays="375"
webserverCertFile=/root/ca/intermediate/certs/webserver.test.lab.cert.pem

if [ -f "webserverCertFile" ]
then
    echo -e "\nThe webserver certificate file already exist.\nCertificate location: $webserverCertFile" 
    echo -e "\nVerify the webserver certificate\n"
    
    # Verify the webserver certificate
    openssl x509 -in $webserverCertFile -text -noout
    # Verify webserver certificate Subject Alternative Name
    echo -e "\nPlease verify webserver certificate, and ensure it contains DNS entry and IP address.\n"
    openssl x509 -in $webserverCertFile -text -noout | grep -A 1 "Subject Alternative Name" 
    echo ""
else
    # Sign the webserver certificate request
    # Using "v3_ca" extensions in webserver certificate configuration file
    
    # Verify intermediate CA private key
    # openssl rsa -in /root/ca/intermediate/private/intermediate.key.pem
    # 
    # Note: 
    # 1. It will prompt for the pass phrase
    # 2. consult secretserver for the pass phrase
    
    echo -e "\nSigning webserver SSL certificate.\n"
    
    sudo openssl x509 -req \
    -in $webserverCSR \
    -CA $intermediateCertFile \
    -CAkey $ICAKeyFile \
    -CAcreateserial \
    -out $webserverCertFile \
    -extensions $webserverCertExtensions \
    -extfile $webserverCnf \
    -days $certDays
    
    
    if [ -f "$webserverCertFile" ]
    then
        chmod 444 $webserverCertFile
        echo -e "\nVerify the webserver certificate\n"
    
        # Verify the webserver certificate
        openssl x509 -in $webserverCertFile -text -noout
        
        # Verify webserver certificate Subject Alternative Name contains DNS entry and IP address
        echo -e "\nVerify webserver certificate Subject Alternative Name contains DNS entry and IP address\n"
        openssl x509 -in $webserverCertFile -text -noout | grep -A 1 "Subject Alternative Name"
    fi
 
fi


#
# Create webserver certificate p12 file
#
webserverP12File=/root/ca/intermediate/p12/webserver.test.lab.p12
passPhrase="EnterPasswordHere"

if [ -f "webserverP12File" ] 
then
    echo -e "\nThe webserver p12 file already exist.\nFile locaton: $webserverP12File"
else
    if [ -f "$webserverCertFile" ]
    then
        if [ -f "$webserverKey" ]
        then
            sudo openssl pkcs12 -export -out $webserverP12File -inkey $webserverKey -in $webserverCertFile -passout pass:$passPhrase
            
            if [ -f "$webserverP12File" ]
            then
                echo -e "\nThe webserver p12 file has been succcessfully been created.\nFile location: $webserverP12File"
            fi
        else
            echo -e "\nThe webserver private key does not exist."
        fi
    else
        echo -e "\nThe webserver certificate does not exist."
    fi
fi

Consideration

#*********** Preparation
1. Remove intermediate CA key pass phrase
cd /root/ca
openssl rsa -in intermediate/private/intermediate.key.pem -out intermediate/private/ica.key.pem
    # Enter the pass phrase when prompt
cp intermediate/private/intermediate.key.pem intermediate/private/intermediate.passphrase.key.pem 
cp intermediate/private/ica.key.pem intermediate/private/intermediate.key.pem

2. create rootca and ica certificate chain pem file
cat intermediate/certs/asn.rootca.pem intermediate/certs/pink.intermediate.pem > intermediate/certs/ca-chain.pem



# How to generate SSL certificate with SAN
https://www.golinuxcloud.com/openssl-subject-alternative-name/

1. Generate Private Key
openssl genrsa -out server.key 4096

2 Generate CSR for SAN Certificate
We will not use the complete /etc/pki/tls/openssl.cnf instead we will create our own custom ssl configuration file with required parameters only.

To generate CSR for SAN we need distinguished_name and req_extensions

I have also added the value for individual distinguished_name parameters in this configuration file to avoid user prompt.


[req]
distinguished_name = req_distinguished_name
req_extensions = req_ext

[req_distinguished_name]
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name (full name)
localityName                    = Locality Name (eg, city)
organizationalUnitName          = Organizational Unit Name (eg, section)
commonName                      = Common Name (eg, your name or your server\'s hostname)
emailAddress                    = Email Address

[req_ext]
subjectAltName = @alt_names

[alt_names]
IP.1 = 10.10.10.13
IP.2 = 10.10.10.14
IP.3 = 10.10.10.17
DNS.1 = centos8-2.example.com
DNS.2 = centos8-3.example.com


# generate CSR
openssl req -new -key server.key -out server.csr -config server_cert.cnf


# verify CSR with SAN
# openssl req -noout -text -in server.csr | grep -A 1 "Subject Alternative Name"

# output:
    X509v3 Subject Alternative Name:
            IP Address:10.10.10.13, IP Address:10.10.10.14, IP Address:10.10.10.17, DNS:centos8-2.example.com, DNS:centos8-3.example.com


# generate/sign certificate
#
# Important:
# 1. Need to use the server certificate configuration file /root/ca/intermediate/server_cert.cnf
# 2. Need to reference [req_ext] extensions in /root/ca/intermediate/server_cert.cnf
# 3. Need to use 
#
openssl x509 -req \
    -days 365 \
    -in intermediate/csr/www.example.com.csr \
    -CA intermediate/certs/ca-chain.cert.pem \
    -CAkey intermediate/private/intermediate.key.pem \
    -CAcreateserial \
    -out intermediate/certs/www.example.com.pem \
    -extensions v3_req \
    -extfile intermediate/servercert.cnf

# Verify the newly signed server certificate for SAN
openssl x509 -text -noout -in intermediate/certs/www.example.com.pem | grep -A 1 "Subject Alternative Name"



# references
https://security.stackexchange.com/questions/74345/provide-subjectaltname-to-openssl-directly-on-the-command-line

-- Ansible -----
[req]
distinguished_name = req_distinguished_name
req_extensions     = v3_req
x509_extensions    = v3_req

[req_distinguished_name]
commonName       = {{ common_name }}
emailAddress     = {{ ssl_certs_email }}
organizationName = {{ ssl_certs_organization }}
localityName     = {{ ssl_certs_locality }}
countryName      = {{ ssl_certs_country }}

[v3_req]
# The extentions to add to a self-signed cert
subjectKeyIdentifier = hash
basicConstraints     = critical,CA:false
subjectAltName       = DNS:{{ common_name }}
keyUsage             = critical,digitalSignature,keyEncipherment


# ********* Better methods -- using theh configuration in run-time via commands ************

openssl req -new -sha256 \
    -key domain.key \
    -subj "/C=US/ST=CA/O=Acme, Inc./CN=example.com" \
    -extensions SAN \
    -config <(cat /etc/ssl/openssl.cnf \
        <(printf "\n[SAN]\nsubjectAltName=DNS:example.com,DNS:www.example.com")) \
    -out domain.csr

openssl req -new -sha256 -key domain.key -subj "/C=US/ST=CA/O=Acme, Inc./CN=example.com" -extensions SAN -config <(cat /etc/ssl/openssl.cnf <(printf "[SAN]\nsubjectAltName=DNS:example.com,DNS:www.example.com")) -out domain.csr


openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout example.key -out example.crt -subj '/CN=example.com' \
  -extensions san \
  -config <(echo '[req]'; echo 'distinguished_name=req';
            echo '[san]'; echo 'subjectAltName=DNS:example.com,DNS:example.net,IP:192.168.10.100')
Automated Creation of Test Systems P12 Certificates
#!/bin/bash

# 
# Purpose:
# Create testsystem certificates
#
# Note:
# Remove carriage return, run command
#   sed -i -e 's/\r$//' /usr/local/bin/scripts/create_testsystem_certificates.sh
#   where
#      -i   in-place replace
#      -e   expression/input file to process
#      
#
# Name          Date        Version        Comment
# -----------------------------------------------------------
# Jackson Chen  xx/xx/xx    0.1            initial
#
#**
**********************************************************

# Ensure run the script as root, otherwise exit the program
if [[ $EUID -ne 0 ]]
then
        echo -e "\n!!!!!!!!! Warning !!!!!!!!!!!!!!!"
        echo "You need to run this script as root. Please try to run the testsystem certificate again."
        sleep 3
        exit 1
fi


#
# Global Variables
#

# ******************************************
#
# Important:
# Update with the required number of testsystems
#
totaltestsystems=3
# ******************************************

testsystemNumber=""
domainSuffix="test.lab"

# certificates folders
keyDir=/mnt/testsystem/keys
certDir=/mnt/testsystem/certs
csrDir=/mnt/testsystem/csr
p12Dir=/mnt/testsystem/p12


#
# Function Name:
#   createtestsystemCertificateDirtories $arg(0) $arg(1) $arg(2) $arg(3)
#
# $arg(0) or $1:
#   First argument: certificate key directory
# $arg(1) or $2:
#   Second argument: certificate dierctory
# $arg(2) or $3:
#   Third argument: certificate signing request directory
# $arg(3) or $4:
#   Fourth argument: certificate p12 directory
#
#
# Function Return:
# The function will return the testsystem number as string
# 

createtestsystemCertificateDirtories ()
{
    # Create the certificate folders if not exist
    if [ ! -d $1 ]
    then       
        mkdir -p $keyDir
        # Secure certificate private key
        chmod 700 $keyDir
    fi

    if [ ! -d $2 ]
    then
        mkdir -p $certDir
    fi

    if [ ! -d $3 ]
    then
        mkdir -p $csrDir
    fi

    if [ ! -d $4 ]
    then
        mkdir -p $p12Dir
        # Secure certificate p12 files
        chmod 700 $p12Dir
    fi

    # List the testsystem certificate folders
    echo -e "\n******* List testsystem certificate folders and folder permissions *******"
    echo -e "testsystem certificate folders: $certDir"
    echo -e "testsystem private key folders: $keyDir"
    echo -e "testsystem certificate signing request folders: $csrDir"
    echo -e "testsystem certificate p12 folders: $p12Dir\n"     
    ls -l /mnt/testsystem | grep "^d"
}


#
# Function Name:
#   constructtestsystemNumber $arg(0)
#
# $arg(0) or $1
#   Function first argument: The testsystem number in digit
#
# Function Return:
# The function will return the testsystem number as string
# 

constructtestsystemNumber ()
{
    # create character string for the testsystem number
    # Adding leading zero "0" if required to create four digit number
    if [ "$1" -lt 10 ]
    then
        testsystemNumber='000'$i            
        
    elif [ "$1" -lt 100 ]
    then
        testsystemNumber='00'$i
    
    elif [ "$1" -lt 1000 ]
    then
        testsystemNumber='0'$i
    
    elif [ "$1" -lt 10000 ]
    then
        testsystemNumber=$1
    else
        # If testsystems count greater and equal to 10,000, breaking from while loop
        break
    fi
    
    # Return value
    echo "$testsystemNumber"
}


#
# Function Name:
#   createtestsystemCertificatePrivateKey
#
# $arg(0) or $i
#   Function first argument: The testsystem number in four digit characters
# 
# Purpose:
# Create certificate private key in PEM format
# 

createtestsystemCertificatePrivateKey ()
{
    # Local variables
    testsystemNo="testsystem$1" 
    testsystemPrivateKey="$keyDir/$testsystemNo.key.pem"    
    
    echo -e "Process $testsystemNo certificate private key."
    
    # Create the testsystem private key if does not exist
    if [ ! -f "$testsystemPrivateKey" ]
    then
        echo -e "Create certificate private key for $testsystemNo"
        openssl genrsa -out $testsystemPrivateKey 4096
        
        # Pause for 2 seconds
        sleep 2
        
        if [ -f "$testsystemPrivateKey" ]
        then
            # Secure the testsystem certificate private key
            chmod 400 $testsystemPrivateKey
            
            echo -e "$testsystemNo certificate private key has been created: $testsystemPrivateKey"
    
            # Check testsystem certificate private key
            openssl rsa -in $testsystemPrivateKey -check
        fi
    else
        echo -e "$testsystemNo certificate private key already exist: $testsystemPrivateKey"
    fi
}



#
# Function Name:
#   createtestsystemCertificateSigningRequest
#
# $arg(0) or $i
#   Function first argument: The testsystem number in four digit characters
# 
# Purpose:
# Create certificate signing request in PEM format
# 

createtestsystemCertificateSigningRequest ()
{
    # Local variables
    testsystemNo="testsystem$1" 
    testsystemPrivateKey="$keyDir/$testsystemNo.key.pem"
    testsystemCnf=/root/ca/intermediate/testsystem.cnf
    testsystemFQDN="$testsystemNo.$domainSuffix"
    testsystemCSR="$csrDir/$testsystemNo.csr.pem"
    
    # testsystem IP address will need to be updated
    # To do !!!!!!!!!!!
    # 
    testsystemIP="192.168.10.100"
    
    
    echo -e "\nProcess $testsystemNo certifcate signing request"

    # Create the testsystem certificate signing request if it does not exist
    if [ ! -f "$testsystemCSR" ]
    then
        echo -e "Create certificate signing request"
        
        if [ -f "$testsystemPrivateKey" ]
        then
            # Create testsystem CSR
            openssl req \
                -new \
                -key $testsystemPrivateKey \
                -out $testsystemCSR \
                -config <(echo '[ req ]';
                        echo 'default_bits = 2048';
                        echo 'default_md = sha256';
                        echo 'distinguished_name  = req_distinguished_name';
                        echo 'encrypt_key = no';
                        echo 'prompt = no';
                        echo 'string_mask = nombstr';
                        echo 'req_extensions = v3_req';
                        echo "";
                    echo '[ v3_req ]';                      
                        echo 'basicConstraints = CA:FALSE'; 
                        echo 'keyUsage = digitalSignature, keyEncipherment, dataEncipherment';
                        echo 'extendedKeyUsage = serverAuth, clientAuth';
                        echo "subjectAltName = DNS:$testsystemNo,DNS:$testsystemFQDN,DNS:usb.$testsystemFQDN,DNS:wifi.$testsystemFQDN,IP:$testsystemIP";
                        echo "";
                      echo '[ req_distinguished_name ]';
                        echo 'countryName = AU';
                        echo 'stateOrProvinceName = ACT';
                        echo 'localityName = Canberra';
                        echo "0.organizationName = $domainSuffix";
                        echo 'organizationalUnitName = IT';
                        echo "commonName = $testsystemFQDN";
                        echo 'emailAddress = admin@test.lab')
                
        
            # Check testsystem certificate signing request after creation
            if [ -f "$testsystemCSR" ]
            then            
                echo -e "$testsystemNo certificate signing request has been created: $testsystemCSR"
    
                # Verify testsystem CSR
                echo -e "Verify the newly created certificate signing request."
                openssl req -noout -text -verify -in $testsystemCSR
                
                # Check testsystem certificate signing request for Subject Alternative Name
                echo -e "\n!!!! Please verify CSR Subject Alternative Name for DNS entries & IP address !!!!"
                openssl req -noout -text -in $testsystemCSR | grep -A 1 "Subject Alternative Name"
            else
                echo -e "Waring: $testsystemNo certificate signing file does not exist after creation, please manually check."
            fi
        else
            echo -e "\n!!!!! Warning: testsystemNo certificate private key does not exist. !!!!!"
            echo -e "Waring: Failed to create certificate signing request for $testsystemNo"
        fi
    else
        # Check testsystem certificate signing request for Subject Alternative Name
        echo -e "$testsystemNo certifcate signing request already exist: $testsystemCSR"
        echo -e "!!!! Please verify CSR Subject Alternative Name for DNS entries & IP address !!!!"
        openssl req -noout -text -in $testsystemCSR | grep -A 1 "Subject Alternative Name"      
    fi
}



#
# Function Name:
#   signIssuetestsystemCertificate
#
# $arg(0) or $i
#   Function first argument: The testsystem number in four digit characters
# 
# Purpose:
# Sign stick certifcate request and issue certifcate in PEM format
# 

signIssuetestsystemCertificate ()
{
    # Local variables
    testsystemNo="testsystem$1" 
    icaDir=/root/ca/intermediate
    intermediateCert="$icaDir/certs/intermediate.cert.perm"
    caChainCert="$icaDir/certs/ca-chain.cert.pem"
    intermediateKey="$icaDir/private/intermediate.key.pem"
    testsystemCSR="$csrDir/$testsystemNo.csr.pem"
    testsystemCertExtensions="v3_req"
    testsystemCert="$certDir/$testsystemNo.crt.pem"
    
    # 18 months certificate
    certDays="558"
    
    # Verify whether the certificate signing request exist
    if [ -f "$testsystemCSR" ]
    then
        # Verify whether the certificate exist
        if [ ! -f "testsystemCert" ]
        then 
            echo -e "\nInformation: Sign testsystem certificate request"
            
            # Sign the testsystem certificate signing request
            openssl x509 \
                -req \
                -days $certDays \
                -in $testsystemCSR\
                -CA $caChainCert \
                -CAkey $intermediateKey \
                -CAcreateserial \
                -out $testsystemCert \
                -extensions $testsystemCertExtensions \
                -extfile <(echo '[ req ]';
                        echo 'default_bits = 2048';
                        echo 'default_md = sha256';
                        echo 'distinguished_name  = req_distinguished_name';
                        echo 'encrypt_key = no';
                        echo 'prompt = no';
                        echo 'string_mask = nombstr';
                        echo 'req_extensions = v3_req';
                        echo "";
                    echo '[ v3_req ]';                      
                        echo 'basicConstraints = CA:FALSE'; 
                        echo 'keyUsage = digitalSignature, keyEncipherment, dataEncipherment';
                        echo 'extendedKeyUsage = serverAuth, clientAuth';
                        echo "subjectAltName = DNS:$testsystemNo,DNS:$testsystemFQDN,DNS:usb.$testsystemFQDN,DNS:wifi.$testsystemFQDN,IP:$testsystemIP";
                        echo "";
                      echo '[ req_distinguished_name ]';
                        echo 'countryName = AU';
                        echo 'stateOrProvinceName = ACT';
                        echo 'localityName = Canberra';
                        echo "0.organizationName = $domainSuffix";
                        echo 'organizationalUnitName = IT';
                        echo "commonName = testsystemFQDN";
                        echo 'emailAddress = admin@test.lab')
            
            # Verify the newly create testsystem certificate
            if [ -f "$testsystemCert" ]
            then                
                echo -e "$testsystemNo certifcate has been created: $testsystemCert"
                echo "Verify the newly signed testsystem certificate"
                openssl x509 -noout -text -in $testsystemCert
                echo -e "!!!! Verify certificate against certificate authority !!!!"
                openssl verify -verbose -CAfile $caChainCert $testsystemCert
                echo -e "!!!! Verify certificate Subject Alternative Name for DNS entries & IP address !!!!"
                openssl x509 -noout -text -in $testsystemCert | grep -A 1 "Subject Alternative Name"            
            else
                echo -e "Waring: $testsystemNo certificate file does not exist after creation, please manually check."
            fi
        
        # Verify the existing testsystem certificate
        else
            echo -e "$testsystemNo certificate already exist: $testsystemCert"
            echo -e "!!!! Verify certificate against certificate authority !!!!"
            openssl verify -verbose -CAfile $caChainCert $testsystemCert
            echo -e "!!!! Verify certificate Subject Alternative Name for DNS entries & IP address !!!!"
            openssl x509 -noout -text -in $testsystemCert | grep -A 1 "Subject Alternative Name"
        fi
    
    # Not able to create testsystem certificate when stick certificate signing request does not exist
    else
        echo -e "!!!! Warning: $testsystemNo certifcate signing request does not exist"
        echo -e "!!!! Not able to create certificate, please verify and manually "
    fi
}



#
# Function Name:
#   createtestsystemP12Certificate
#
# $arg(0) or $i
#   Function first argument: The testsystem number in four digit characters
# 
# Purpose:
# Create testsystem p12 certificate
# 
# Note:
# p12 certificate export passsword:  
#   UseRequiredComplexePassword
# 

createtestsystemP12Certificate ()
{
    # Local variables
    testsystemNo="testsystem$1"
    testsystemPrivateKey="$keyDir/$testsystemNo.key.pem"
    testsystemCert="$certDir/$testsystemNo.crt.pem"
    testsystemP12Cert="$p12Dir/$testsystemNo.$domainSuffix.p12"
    
    #***************************************
    # testsystem p12 certifcate export passsword
    #
    p12ExportPass="UseRequiredComplexePassword"
    #***************************************

    # Verify whether testsystem p12 certificate exist
    if [ ! -f "$testsystemP12Cert" ]
    then        
        # Verify whether testsystem certifcate private key exist
        if [ -f "$testsystemPrivateKey" ]
        then        
            # Verify whether testsystem certifcate exist
            if [ -f "$testsystemCert" ]
            then
                echo -e "\nInformation: Create testsystem p12 certifcate"
                openssl pkcs12 \
                    -export \
                    -out $testsystemP12Cert \
                    -inkey $testsystemPrivateKey \
                    -in $testsystemCert \
                    -passout pass:$p12ExportPass
            
                if [ -f "$testsystemP12Cert" ]
                then
                    echo -e "$testsystemNo p12 certifcate has been created: $testsystemP12Cert"
                    echo -e "!!!! Verify p12 certificate !!!!"
                    openssl pkcs12 \
                        -info \
                        -in $testsystemP12Cert \
                        -passin pass:$p12ExportPass \
                        -passout pass:$p12ExportPass
                        
                else
                    echo -e "Waring: $testsystemNo p12 certificate file does not exist after creation, please manually check."
                fi
                
            # Not able to create p12 certificate if testsystem certifcate does not exist
            else
                echo -e "Warning: $testsystemNo certifcate does not exist.\Please verify and manually create testsystem p12 certifcate"
            fi
        
        # Not able to create p12 certifcate if testsystem certifcate private key does not exist
        else
            echo -e "Warning: $testsystemNo certifcate private key does not exist.\Please verify and manually create testsystem p12 certifcate"
        fi
        
    # Verify the existing testsystem certificate p12 file
    else
        echo -e "\n$testsystemNo p12 certificate already exist: $testsystemP12Cert"
        echo -e "!!!! Verify p12 certificate !!!!"
        
        #
        # sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
        # where
        # -n "regexp"    lines that matching the regexp
        # /-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/
        #    lines that begin "-BEGIN CERTIFICATE-" and end with "-END CERTIFICATE-"
        #    begin address: /-BEGIN CERTIFICATE-/
        #    end address:   /-END CERTIFICATE-/
        # -e    expression
        # /p    only print lines
        # 
        openssl pkcs12 \
            -info \
            -in $testsystemP12Cert \
            -passin pass:$p12ExportPass \
            -passout pass:$p12ExportPass | \
            sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | \
            openssl x509 -subject -issuer -noout
            
        
        #
        # If want to see the entire p12 certifcate information
        # 
        # openssl pkcs12 \
        #   -info \
        #   -in $testsystemP12Cert \
        #   -passin pass:$p12ExportPass \
        #   -passout pass:$p12ExportPass
        #   
    fi
}





# **************************************************
#
# Main
#
# **************************************************

echo -e "\n\n************************************************************\n"
echo -e "   Automate the creation of testsystem certificate p12 files\n"
echo -e "   Number of testsystem p12 files to be created:  $totaltestsystems \n"
echo -e "************************************************************\n"

now=$(date +"%d-%m-%Y %H:%M:%S")
echo -e "\n$now: Start processing testsystem certificates, please wait....."


# Create testsystem certificate directories
createtestsystemCertificateDirtories $keyDir $certDir $csrDir $p12Dir

# Proces the creation of testsystem certificate
for (( i=1; i<=$totaltestsystems; i++))
do  
    # Step 1: create character string for the testsystem number
    # Adding leading zero "0" if required to create four digit number
    
    testsystemNumber=$(constructtestsystemNumber $i)
    
    # Inform the testsystem to be processed
    echo -e "\n******* The testsystem to be processed: testsystem$testsystemNumber *******"
    
    # Step 2: Create testsystem certificate private keys
    createtestsystemCertificatePrivateKey $testsystemNumber
    
    # Step 3: Create testsystem certificate signing request file (CSR) file
    createtestsystemCertificateSigningRequest $testsystemNumber
    
    # Step 4: Sign testsystem certificate signing request and issue certificate
    signIssuetestsystemCertificate $testsystemNumber

    # Step 5: Create testsystem p12 certifcate
    createtestsystemP12Certificate $testsystemNumber

done


# Inform that all testsystem certificates have been created.
now=$(date +"%d-%m-%Y %H:%M:%S")
echo -e "\n$now: ***** All testsystems certificates have been created *****"

Copy Certificate Files to External System

# ************** Preparation ******************
# Install cifs-utils
yum install -y cifs-utils

# Create credential file
/etc/credentials/external_credentials
username="RequiredUserName"
password="RequiredPassword"
domain=test.local

# Create directory mount point /mnt/delivery
    mkdir /mnt/delivery

# update /etc/fstab
/<share-path/share-folder> /mnt/delivery  cifs  

Note:
# test manual mount

# Verify /etc/fstab mounts
    mount -fav

# If successful, then mount the new mount
    systemctl daemon-restart
    mount -a
#!/bin/bash

#
# Purpose:
# Delivery stik p12 certificates
# 
# Source:
# /root/ca/intermediate/test/p12
#
# Destination:
# /mnt/stik_certs_delivery
# Test File Server Location: \\test.local\share
# 
#
# Note:
# 1. Remove carriage return, run command
#       sed -i -e 's/\r$//' /usr/local/bin/scripts/transfer_test_p12.sh
#       where
#      -i       in-place replace
#          -e   expression/input file to process
#
# 2. Secure the script
#    chmod 700 /usr/local/bin/scripts/transfer_test_p12.sh
#
**********************************************************

# Ensure run the script as root, otherwise exit the program
if [[ $EUID -ne 0 ]]
then
        echo -e "\n!!!!!!!!! Warning !!!!!!!!!!!!!!!\nYou need to run this script as root. Please try to run the stik certificate again."
                sleep 3
                exit 1
fi


#
# Global Variables
#
# destDir:
# /mnt/certs_delivery has been mounted to \\test.local\share

sourceDir=/root/ca/intermediate/test/p12
destDir=/mnt/certs_delivery


# **************************************************
#
# Main
#
# **************************************************

# Copy stik certificate p12 files from OpenSSL server to test system certificate directory
if [ -d "$sourceDir" ]
then
    if [ -d "$destDir" ]
    then
        # Empty the directory p12 files before copying
        echo "Empty the p12 files at the destination director: $destDir"
        rm -f "$destDir"/*
        
        # Copy the certificate p12 files to the destination directory
        echo "Copying certificate p12 files from $sourceDir to $destDir"
        cp -f "$sourceDir"/* "$destDir"

        if [ $? -eq 0 ]
        then
            echo "The certificate p12 files have been successfully copied to the destination directory. Please verify the destination."
        else
            echo "Waring: Failed to copy the certificate p12 files to the destination. Please rerun or manually verify."
        fi
    else
        echo -e "Warning: The destination directry $destDir does not exist. Please verify the destination directory and try again."
    fi
else
    echo -e "Warning: The source directry $sourceDir does not exist. Please verify the source directory and try again."
fi

How to quickly create the SSL certificate private key and certificate

#***** This is quick steps
1. SSH to RHEL server
2. Update certificate request config file server.cfs file
    Update with the required common name, SAN names
3. Generate the private key and CSR request file
openssl req -out server.csr -newkey rsa:2048 -key server.key -config server.cfg

4. Convert the private key to pem format
openssl rsa -in server.key -out server.key.pem -outform pem 
    Note:
    If the private key has passphase, remove the passphase
        openssl rsa -in server.key -out servernew.key

5. Sign the CSR
This could be signed by Microsoft CA, third party CA

6. Convert the certificate cer file to pem format
openssl x509 -in server.cer -outform pem -out server.pem

7. Create the certificate chain pem file
cat server.pem ica.pem rca.pem > server.chain.pem