Understanding the x509 Certificate Error
When connecting to a MongoDB server using Go, an error can occur due to certificate validation issues. This error is caused when the x509 certificate used for TLS authentication relies on the legacy Common Name (CN) field instead of Subject Alternative Names (SANs).
Solution: Using SANs in Certificates
To resolve this issue, the certificate must be regenerated with SANs instead of the CN field. SANs provide a more secure and flexible way to identify the server's domain or hostname.
Generating a Certificate with SANs
Use OpenSSL to generate a CSR (Certificate Signing Request) and sign it with the root CA:
<code class="sh">openssl req -new \ -subj "${SUBJ_PREFIX}/CN=${DNS}/emailAddress=${EMAIL}" \ -key "${KEY}" \ -addext "subjectAltName = DNS:${DNS}" \ -out "${CSR}" openssl ca \ -create_serial \ -cert "${ROOT_CRT}" \ -keyfile "${ROOT_KEY}" \ -days "${CERT_LIFETIME}" \ -in "${CSR}" \ -batch \ -config "${CA_CONF}" \ -out "${CRT}"</code>
CA Configuration
Configure the CA with the following options:
[ ca ] default_ca = my_ca [ my_ca ] ... copy_extensions = copy [ my_cert ] basicConstraints = CA:FALSE nsComment = "generated by https://github.com/me/my-pki" subjectKeyIdentifier = hash authorityKeyIdentifier = keyid,issuer [ policy_match ] # ensure CSR fields match that of delivered Cert countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional
Verifying the Certificate
Inspect the resulting server certificate using OpenSSL:
<code class="sh">openssl x509 -in server.crt -noout -text</code>
The certificate should now include a SAN section:
X509v3 Subject Alternative Name: DNS:myserver.com
By updating the certificates with SANs, the TLS connection should now establish successfully without triggering the error message related to the legacy CN field.
The above is the detailed content of Why is my Go MongoDB connection throwing a x509 certificate error, and how can I fix it using SANs?. For more information, please follow other related articles on the PHP Chinese website!