30

Trying to connect to Azure CosmosDB mongo server results into an SSL handshake error.

I am using Python3 and Pymongo to connect to my Azure CosmosDB. The connection works fine if I run the code with Python27 but causes the below error when using Python3:

import pymongo
from pymongo import MongoClient
import json
import sys

def check_server_status(client, data):
   '''check the server status of the connected endpoint'''
   db = client.result_DB
   server_status = db.command('serverStatus')
   print('Database server status:')
   print(json.dumps(server_status, sort_keys=False, indent=2, separators=(',', ': ')))
   coll = db.file_result
   print (coll)
   coll.insert_one(data)

def main():
    uri = "mongodb://[email protected]:10255/?ssl=true&replicaSet=globaldb"
    client = pymongo.MongoClient(uri)
    emp_rec1 = {
        "name":"Mr.Geek",
        "eid":24,
        "location":"delhi"
        }
    check_server_status(client, emp_rec1)

if __name__ == "__main__":
    main()

Running this on Python3 results into below error:

pymongo.errors.ServerSelectionTimeoutError: SSL handshake failed: backendstore.documents.azure.com:10255: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Here is my successful output when I run the same code with Python27:

Database server status: { "_t": "OKMongoResponse", "ok": 1 } Collection(Database(MongoClient(host=['backend.documents.azure.com:10255'], document_class=dict, tz_aware=False, connect=True, ssl=True, replicaset='globaldb'), u'result_DB'), u'file_result')

1
  • 7
    VERY IMPORTANT: several answers here suggest using ssl_cert_reqs=ssl.CERT_NONE or tlsAllowInvalidCertificates=True. They DON'T solve the issue, but just silence the error by connecting without any certificate validation, which is insecure. If you want to do that for testing, fine, but do not, I repeat, DO NOT USE in production environments under any circumstance! Commented Feb 1, 2023 at 23:58

14 Answers 14

34

On Windows you can do like this

pip install certifi

Then use it in code:

import certifi
ca = certifi.where()

client = pymongo.MongoClient(
"mongodb+srv://username:[email protected]/xyzdb?retryWrites=true&w=majority", tlsCAFile=ca)
8
  • 3
    What does this do exactly ? I tried it, it indeed solved my problem but I am having trouble to understand what the problem was (as it happened overnight) and how this trick solves it.
    – vianmixt
    Commented Sep 30, 2021 at 16:36
  • 5
    MongoClient require TLS certificate for secure communication sometimes python is unable request via TLS so here we explicitly mentioning for MongoClient to request to mongodb using certifi package Commented Oct 3, 2021 at 10:37
  • Isn't it needed to add tls=true at URI? Commented Apr 5, 2022 at 4:02
  • @HimalAcharya yes if you are using certificate to authenticate Commented Apr 23, 2022 at 7:57
  • it worked for me. I was facing an issue related to ssl certificate failed. I applied this solution and it worked Commented Aug 20, 2022 at 9:31
17

Solved the problem with this change:

client = pymongo.MongoClient(uri, ssl_cert_reqs=ssl.CERT_NONE)
3
  • 8
    Does this just mean it doesn't use a TLS handshake? It doesn't seem like the greatest idea for something in production.
    – axme100
    Commented Feb 4, 2020 at 21:47
  • 2
    That's fine for testing and perhaps in a development scenario when you know what you're connecting to. This isn't what I'd call a solution however. Commented Oct 6, 2020 at 19:02
  • 1
    awesome solution to ServerSelectionTimeoutError ! of course that this is mostly used in testing and dev propose, do not leave this solution to production! Commented Oct 14, 2021 at 14:37
11

The section Troubleshooting TLS Errors of the PyMongo offical document `TLS/SSL and PyMongo introduces the issue as below.

TLS errors often fall into two categories, certificate verification failure or protocol version mismatch. An error message similar to the following means that OpenSSL was not able to verify the server’s certificate:

[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

This often occurs because OpenSSL does not have access to the system’s root certificates or the certificates are out of date. Linux users should ensure that they have the latest root certificate updates installed from their Linux vendor. macOS users using Python 3.6.0 or newer downloaded from python.org may have to run a script included with python to install root certificates:

open "/Applications/Python <YOUR PYTHON VERSION>/Install Certificates.command"

Users of older PyPy and PyPy3 portable versions may have to set an environment variable to tell OpenSSL where to find root certificates. This is easily done using the certifi module from pypi:

$ pypy -m pip install certifi
$ export SSL_CERT_FILE=$(pypy -c "import certifi; print(certifi.where())")

You can try to follow the description above to fix your issue, which seems to be for Linux and Mac Users. On Windows, I can not reproduce your issue in Python 3.7 and 3.6. If you have any concern, please feel free to let me know.

2
  • Thanks for the answer! For anyone trying to connect through Djongo, this was the only solution that worked for me. I'm on MacOs, Django 1.3, Django 2.2 BTW Commented Dec 23, 2021 at 20:24
  • Very important is to open a new shell when running it the next time. I happened to stumble over another SO answer that mentioned it for Windows. Could've wasted many an hour if I missed it.
    – aydow
    Commented Sep 15, 2022 at 14:41
9

Make sure you whitelist your IP on the MongoDb Atlas dashboard!

This was blocking me from completing the SSL handshake.

3
  • This was my issue, my webserver suddently stopped working after my Internet box change IP address. This is the error that appeared: pymongo.errors.ServerSelectionTimeoutError: SSL handshake failed: cluster....mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR]
    – GuyOlivier
    Commented Mar 26 at 9:46
  • For me it stopped working on my dev box since my ISP changed my IP address.
    – A.K.
    Commented May 30 at 9:51
  • This was my issue, thanky you!
    – coreyb
    Commented Aug 2 at 20:40
6

Faced the same issue when trying to connect mongodb from Digital Ocean, Solved by using this function with params in MongoClient:

def get_client(host,port,username,password,db):
      return MongoClient('mongodb://{}:{}/'.format(host,port),
                         username=username,
                         password=password,
                         authSource=db,
                         ssl=True,ssl_cert_reqs=ssl.CERT_NONE)

client = get_client("host-ip","port","username","password","db-name")
0
4

On Mac Mojave 10.14.6 , I used (PyMongo 3.10 and python 3.7), to solve:

flask pymongo pymongo.errors.ServerSelectionTimeoutError [SSL: CERTIFICATE_VERIFY_FAILED]

Execute in terminal:

sudo /Applications/Python\ 3.7/Install\ Certificates.command

If you use other python version, only change versión number (In my case, i have Python 3.7)

0
3
cluster = MongoClient(
    "url",
    ssl=True,
    ssl_cert_reqs=ssl.CERT_NONE,
)
1
  • 2
    While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Yunnosch
    Commented Sep 12, 2021 at 10:05
3

By default pymongo relies on the operating system’s root certificates.

It could be that Atlas itself updated its certificates or it could be that something on your OS changed. “certificate verify failed” often occurs because OpenSSL does not have access to the system’s root certificates or the certificates are out of date. For how to troubleshoot see TLS/SSL and PyMongo — PyMongo 3.12.0 documentation 107.

pls Try :

client = pymongo.MongoClient(connection, tlsCAFile=certifi.where())

and dont forget to install certifi

2

Im using mac and none of the solution above solved the issue, what solved the issue was installing pymongo[ocsp]

 pip3 install pymongo[ocsp]
1
  • indeed this is the only thing that worked for me too. I think it might be because of the Python version. In the documentation of MongoDB it does say 3.12 or higher. Using Python 3.11 this is good. Commented Jun 10 at 8:03
1

Adding the following code to your client connection will solve the issue:

tls=True, tlsAllowInvalidCertificates=True

# Example 
client = MongoClient(mongo_uri, tls=True, tlsAllowInvalidCertificates=True)
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Oct 4, 2023 at 16:33
1

Just add Current IP Address or access from anywhere to your MongoDB Cluster, it's in network access

0

import ssl

Simply importing this fixed my issue. On my macbook, it worked fine on windows PC

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jun 27, 2023 at 0:46
0

I was faced the same issues while connecting locally python program to https://cloud.mongodb.com/ and it's perfectly working in my case,

  1. whitelist your machine IP in Network Access [ https://cloud.mongodb.com/v2/5fa4ead022943073aaa5866c#/security/network/accessList]
  2. follow this step's - https://stackoverflow.com/a/72841895/2685581

Complete Python-MongoDB snippet code -

    import certifi
    from pymongo import MongoClient


    MONGO_DB_CONNECTION = "mongodb+srv://<username>:<password>@cluster0.XXXvx6dXXX.mongodb.net/"

    client = MongoClient(MONGO_DB_CONNECTION,tlsCAFile=certifi.where())
    
    employee = {
        "id": "102",
        "name": "Peter",
        "profession": "Software Engineer"
    }
    # Get the Database name i.e stock_matrix_db
    db = client["stock_matrix_db"]
    # Get the Collection name i.e stock_matrix
    collection_name = db.stock_matrix
    for val in collection_name.find():
        print(val)

    collection_name.insert_one(employee)
    for val in collection_name.find():
        print(val)
-1

On mac Monterey, I used pymongo 3.12.1 and virtual environment

To solve, use

ssl_cert_reqs=CERT_NONE

with mongodb url

Not the answer you're looking for? Browse other questions tagged or ask your own question.