pymongo [SSL: CERTIFICATE_VERIFY_FAILED]: certificate has expired on Mongo Atlas

Question:

I am using MongoDB(Mongo Atlas) in my Django app. All was working fine till yesterday. But today, when I ran the server, it is showing me the following error on console

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "c:usersadminappdatalocalprogramspythonpython39libthreading.py", line 973, in _bootstrap_inner
    self.run()
  File "c:usersadminappdatalocalprogramspythonpython39libthreading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangoutilsautoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangocoremanagementcommandsrunserver.py", line 121, in inner_run
    self.check_migrations()
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangocoremanagementbase.py", line 486, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangodbmigrationsexecutor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangodbmigrationsloader.py", line 53, in __init__
    self.build_graph()
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangodbmigrationsloader.py", line 220, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangodbmigrationsrecorder.py", line 77, in applied_migrations
    if self.has_table():
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangodbmigrationsrecorder.py", line 56, in has_table
    tables = self.connection.introspection.table_names(cursor)
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangodbbackendsbaseintrospection.py", line 52, in table_names
    return get_names(cursor)
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjangodbbackendsbaseintrospection.py", line 47, in get_names
    return sorted(ti.name for ti in self.get_table_list(cursor)
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagesdjongointrospection.py", line 47, in get_table_list
    for c in cursor.db_conn.list_collection_names()
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagespymongodatabase.py", line 880, in list_collection_names
    for result in self.list_collections(session=session, **kwargs)]
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagespymongodatabase.py", line 842, in list_collections
    return self.__client._retryable_read(
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagespymongomongo_client.py", line 1514, in _retryable_read
    server = self._select_server(
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagespymongomongo_client.py", line 1346, in _select_server
    server = topology.select_server(server_selector)
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagespymongotopology.py", line 244, in select_server
    return random.choice(self.select_servers(selector,
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagespymongotopology.py", line 202, in select_servers
    server_descriptions = self._select_servers_loop(
  File "C:UsersAdminAppDataLocalProgramsPythonPython39Libsite-packagespymongotopology.py", line 218, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129), Timeout: 30s, Topology Description: <TopologyDescription id: 6155f0c9148b07ff5851a1b3, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster0-shard-00-00.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')>, <ServerDescription ('cluster0-shard-00-01.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')>, <ServerDescription ('cluster0-shard-00-02.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')>]>

I am using djongo as the database engine

DATABASES = {
    'default': {
            'ENGINE': 'djongo',
            'NAME': 'DbName',
            'ENFORCE_SCHEMA': False,
            'CLIENT': {
                'host': 'mongodb+srv://username:[email protected]/DbName?retryWrites=true&w=majority'
            }  
    }
}

And following dependencies are being used in the app

dj-database-url==0.5.0
Django==3.2.5
djangorestframework==3.12.4
django-cors-headers==3.7.0
gunicorn==20.1.0
psycopg2==2.9.1
pytz==2021.1
whitenoise==5.3.0
djongo==1.3.6
dnspython==2.1.0

What should be done in order to resolve this error?

Asked By: Malina Dale

||

Answers:

This is because of a root CA Let’s Encrypt uses (and Mongo Atals uses Let’s Encrypt) has expired on 2020-09-30 – namely the "IdentTrust DST Root CA X3" one.

The fix is to manually install in the Windows certificate store the "ISRG Root X1" and "ISRG Root X2" root certificates, and the "Let’s Encrypt R3" intermediate one – link to their official site – https://letsencrypt.org/certificates/

Copy from the comments: download the .der field from the 1st category, download, double click and follow the wizard to install it.

Answered By: Todor Minakov

I solved the problem on my windows machine. It had to do with the expiring DST Root CA X3 certificate from Let’s Encrypt.

  1. Download https://letsencrypt.org/certs/lets-encrypt-r3.pem
  2. rename file .pem to .cer
  3. double click and install
  4. Restart your PC

Still, if it doesn’t work

  1. Go to https://letsencrypt.org/certificates/
  2. Download ISRG Root X1, ISRG Root X2 ( Root Certificates), Let’s Encrypt R3 ( Intermediate Certificates)
  3. Restart your PC
Answered By: Harrish Selvarajah

I found the solution in the mongoDB community. Download https://letsencrypt.org/certs/lets-encrypt-r3.pem

  1. rename the .pem file to .cer
  2. double-click and install
  3. try to run the app

Your SSL issue should be resolved.

source: https://www.mongodb.com/community/forums/t/keep-getting-serverselectiontimeouterror/126190/13

Answered By: SATHISH KUMAR

Another solution from MongoDB community. Super easy and worked for me. You can read the full solution here –

https://www.mongodb.com/community/forums/t/keep-getting-serverselectiontimeouterror/126190/

Here is what worked for me (Windows 11) –

heck that dnspython, pymongo and certifi are installed in your virtual environment or install them by:

pip install dnspython pymongo certifi

Can you use the terminal/command line and run Python, in the Python environment can you enter and = run the following commands (please change the password as appropriate for your user in your Atlas cluster):

from pymongo import MongoClient
import certifi
s = MongoClient("mongodb+srv://m220student:[email protected]", tlsCAFile=certifi.where())
Answered By: Gautam Dawar

My error was :

__primary_host_bc-g0q7gf-shard-03-01.cnrej4y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108),ac-g0q78b8-shard-00-02.cnrej4y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108),__primary_host_bc-g0q7gf-shard-03-01.cnrej4y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108), Timeout: 30s, Topology Description: <TopologyDescription id: 63babd290b494b7e05e537ce, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription (‘__primary_host_bc-g0q7gf-shard-03-01.cnrej4y.mongodb.net’, 27017) server_type: Unknown, rtt: None, error=AutoReconnect(‘__primary_host_bc-g0q7gf-shard-03-01.cnrej4y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)’)>, <ServerDescription (‘__primary_host_bc-g0q7gf-shard-03-01.cnrej4y.mongodb.net’, 27017) server_type: Unknown, rtt: None, error=AutoReconnect(‘__primary_host_bc-g0q7gf-shard-03-01.cnrej4y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)’)>, <ServerDescription (‘ac-g0q78b8-shard-00-02.cnrej4y.mongodb.net’, 27017) server_type: Unknown, rtt: None, error=AutoReconnect(‘ac-g0q78b8-shard-00-02.cnrej4y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)’)>]>

the below solution as mentioned by sir gautam helped me to access mongodb cloud:

import pymongo
import certifi

client = pymongo.MongoClient("mongodb+srv://name:password@cluster0.cnrej4y.mongodb.net/?retryWrites=true&w=majority",tlsCAFile=certifi.where())

(Above i changed primary host name)

Answered By: Vishnu Parvatikar