Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)') #610

Open
sponaugle opened this issue Aug 20, 2019 · 76 comments

Comments

@sponaugle
Copy link

sponaugle commented Aug 20, 2019

Environment
Hi, I am running the following --

  • Python: 3.6 (64 bit)
  • pyodbc: 4.0.27
  • OS: Linux (Redhat 7.6)
  • driver: ODBC Driver 17 for SQL Server

and am trying to access a SQL SERVER (version 10.0.1600.22) hosted on a Windows NT 5.2 (XP/Server 2003) machine.

Code

`def connectToSQLServer(server_name, username, password, db_name):

conn = pyodbc.connect(
                      'Driver={ODBC Driver 17 for SQL Server};'
                      f'Server={server_name};'
                      f'Database={db_name};'
                      f'UID={username};'
                      `f'PWD={password};'`
                      'Mars_Connection=Yes;'
                     )
return conn

conn = connectToSQLServer(server_name='<server_name>', username='',password=,db_name='<db_name>')`

Issue

Issue
I am receiving the following error --

'Driver={ODBC Driver 17 for SQL Server};'
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)')

I am able to access several other SQL Server machines using the same environment and code without issue, although they are using more recent Operating Systems (Windows NT 6.0+) and SQL Server versions (10.5+).

I understand that Windows NT 5.2 and SQL Server (10.0.1600.22) are very old and no longer supported. I read the following ticket (microsoft/msphpsql#252) and some people suggested the Operating System needs to be upgraded. So I'm wondering if that may be the case here.

However, I am a little skeptical because I am able to establish connection when I run the same code but from my local Windows 10 laptop, which uses the Windows equivalent of the same ODBC driver. My local Windows 10 machine also uses the same Python and pyodbc versions. So my real question is, how come I can establish a connection from my Windows 10 machine but not from the Linux machine? Could there be something else at play here?

Thanks a lot for your help.

@v-makouz
Copy link
Contributor

v-makouz commented Aug 20, 2019

Just to rule out pyodbc itself, can you try to connect directly using the ODBC driver?
To do so run isql -v -k "<Your connection string>", and see if it gives the same error.

Also it may be useful to look at ODBC traces from the successful Windows connection and the failed connection. (ODBC tracing Linux: https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/data-access-tracing-with-the-odbc-driver-on-linux?view=sql-server-2017, Windows: https://docs.oracle.com/cd/E17952_01/connector-odbc-en/connector-odbc-configuration-trace-windows.html)

@sponaugle
Copy link
Author

Hi v-makouz,

The isql command returns the same error --

[08001][Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746
[08001][Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection
[ISQL]ERROR: Could not SQLDriverConnect

I also did the tracing for both the successful windows 10 connection and the failed linux one. I attached those logs to this message (and removed the private connection information). I looked them over but didn't see anything stick out but it's my first time ever reading those type of logs.

Since we've ruled out that it is not pyodbc related I understand if you have to close the ticket. But if you or anyone else can point me in the right direction I would greatly appreciate it.

Thank you,
Zack

database_connection_trace_linux.txt
database_connection_trace_windows_10.LOG

@gordthompson
Copy link
Collaborator

Does it make any difference if you explicitly specify Encrypt=no in your connection string?

@v-chojas
Copy link
Contributor

What version of OpenSSL are you using on the RedHat machine? You can run openssl version to check.

Could you do a packet capture with Wireshark in both the working and non-working cases? The difference could be due to TLS configuration.

@sponaugle
Copy link
Author

Adding "Encrypt=no" to the connection string still returns the same error.

OpenSSL version is OpenSSL 1.0.2k-fips on the Red Hat machine.

I will work on setting up wireshark to analyze both cases.

Thank you both.

@adamtabrams
Copy link

@sponaugle Did you ever find a solution? I'm having the same issue.

@v-chojas
Copy link
Contributor

@adamtabrams could you provide your environment details, and Wireshark if possible?

@adamtabrams
Copy link

Environment

  • Python: 3.7
  • pyodbc: 4.0.27
  • unixodbc-dev 2.3.6
  • msodbcsql17 17.4.1.1-1
  • OS: Linux (Debian Buster-Slim 10.1)
  • Running as a Docker container
  • driver: ODBC Driver 17 for SQL Server

Issue
With this environment, I was getting the same error as sponaugle when I was trying to connect to the database. I was actually able to fix the problem for my use case by switching to Debian Stretch-Slim 9.11. One slight difference that I noticed is that Stretch has unixodbc-dev 2.3.7 available, but it seems that only 2.3.6 is available for Buster (even though it's newer). Now that I have it working, I'm done tinkering with it, but I hope that's enough info to point everyone in the right direction. Thanks!

@v-chojas
Copy link
Contributor

You may be seeing the effect of the OpenSSL changes in Debian: https://wiki.debian.org/ContinuousIntegration/TriagingTips/openssl-1.1.1

Also note that you can get the unixODBC 2.3.7 packages here too: https://packages.microsoft.com/debian/10/prod/pool/main/u/unixodbc/

@roirodriguez
Copy link

Hi,
I was experiencing the same problem, and fixed thanks to @v-chojas comment above. Just edited /etc/ssl/openssl.cnf and changed:

MinProtocol = TLSv1.0
CipherString = DEFAULT@SECLEVEL=1

@aap82
Copy link

aap82 commented Oct 3, 2019

Confirmed this worked for me:

https://stackoverflow.com/questions/57265913/error-tcp-provider-error-code-0x2746-during-the-sql-setup-in-linux-through-te/57453901#57453901

System Info
Python: 2.7
pyodbc: 4.0.26
OS: Ubuntu 18.04
driver: ODBC Driver 17 for SQL Server

@sponaugle
Copy link
Author

My openssl.cnf file in Red Hat 7 does not have any existing MinProtocol or CipherString options. Also its path is at /etc/pki/tls. Not sure if that matters.

@sonnehansen
Copy link

@sponaugle I can confirm that @roirodriguez 's solution works. It seems that there are different ways to input default values. Deleting them (or not having them) it one of them. At least on Ubuntu 18.04 it works with no entries and openssl v1.1.1g

A third option is mentioned in the Debian release issues, which is just a different take on the info already provided by @v-chojas.

Thanks a million to all of you for pointing me in the right direction :)

For future reference for conda users. My problem arose when upgrading miniconda bases image from 4.5.12 (Debian 9) to 4.7.12 (Debian 10), which was required due to some package resolving issues in existing environments.

@atroiano
Copy link

I can also confirm @roirodriguez worked in Debian 10

@jfmontanaro
Copy link

Just wanted to chime in here and mention that at least in my case, the issue wasn't due to SQL Server lacking support for TLSv1.2 but rather to the server's certificate having too weak a key.

The ideal solution in this case is obviously to update the server certificate, but failing that it also works to set CipherString = DEFAULT@SECLEVEL=1 as mentioned by @roirodriguez and leave MinProtocol alone.

@sondrelg
Copy link

In case anyone (like me) stumbles onto this thread without knowing even the basics of linux; this is how I ended up implementing @roirodriguez's fix in my Dockerfile:

RUN chmod +rwx /etc/ssl/openssl.cnf
RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf
RUN sed -i 's/SECLEVEL=2/SECLEVEL=1/g' /etc/ssl/openssl.cnf

sed -i replaces text in a file in-place, while the chmod-command was necessary to give the current user access rights to the file.

@trs80
Copy link

trs80 commented Feb 26, 2020

Even with 'encrypt=no' I see a TDS7 pre-login message - TLS exchange sent by the client, followed by a FIN, ACK from the server. Setting CipherString = DEFAULT@SECLEVEL=1 in openssl.cnf allows the connection to proceed, there's further TDS7 pre-login messages showing the default self-signed certificate and a TLS exchange which appears to contain the login.

So a) the default certificate is too weak and b) something's attempting TLS even with encrypt=no.

@v-chojas
Copy link
Contributor

See the TDS spec Encryption section: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/60f56408-0188-4cd5-8b90-25c6f2423868

The default cert (and the TLS handshake) is present to provide some protection from passive attackers, if you need something stronger you can set up your own certificate: https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/enable-encrypted-connections-to-the-database-engine

@HARIKABANDARU
Copy link

The same error occurred when trying to connect from python using SQLAlchemy on windows.

@v-chojas
Copy link
Contributor

This is a TLS configuration issue, and is unrelated to pyODBC.

@trs80
Copy link

trs80 commented Apr 27, 2020

Well can you document it somewhere then? Because clearly lots of people hit the problem. Ideally with the error messages so it's good Google bait. Also that encrypt=no isn't respected.

@v-chojas
Copy link
Contributor

The behaviour of TDS Encryption is documented in the link I posted above.

@trs80
Copy link

trs80 commented Apr 28, 2020

Clearly nobody knows how to find those documents or that they're the root cause of their connection problems since people keep filing bugs. Perhaps on https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Linux or https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15 or https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/known-issues-in-this-version-of-the-driver?view=sql-server-ver15 ?

@shushko1
Copy link

after adding to /etc/ssl/openssl.cnf the lines MinProtocol = TLSv1.0 and CipherString = DEFAULT@SECLEVEL=1
what do we need to restart/refresh? I still get "TCP Provider: Error code 0x2746" and "Client unable to establish connection" after executing sqlcmd.

@v-chojas
Copy link
Contributor

You will need to provide a lot more information about your environment for anyone else to be able to give you more assistance.

@shushko1
Copy link

my environment is Ubuntu 20.04 LTS, running nginx web service and PHP 7.4. from there I try to connect to M$ SQL Server 2014 database on a Windows 2012 R2 server.
on the Ubuntu-box I have unixodbc-dev 2.3.7, msodbcsql17 17.5.2.1-1, openssl 1.1.1f.
as far as I understood, this SQL connection is using TLS v1.2 by default, which is causing problems, and we need to force the connection to use TLS v1.0 - and that is achieved by modifying /etc/ssl/openssl.cnf ?

@v-chojas
Copy link
Contributor

Everything in that list supports TLS 1.2. Make sure your server has this update:
https://support.microsoft.com/en-us/help/3135244/tls-1-2-support-for-microsoft-sql-server

@samueldominguez
Copy link

samueldominguez commented Jul 1, 2020

Still running into this issue even after changing TLS configuration on Debian 10. My connection string is the following: DRIVER={ODBC Driver 17 for SQL Server};SERVER=sqlserver,1936;UID=user;PWD=password where the port is specified as per the library sqlserverport when getting the instance name via sqlserverport.lookup(server_name, instance_name).

If I change the connection string to DRIVER={ODBC Driver 17 for SQL Server};SERVER=sqlserver;PORT=1936;UID=user;PWD=password I get the following error instead: pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]ODBC Driver 17 for SQL Server does not support connections to SQL Server 2000 or earlier versions. (22) (SQLDriverConnect)') even though I am using MS SQL 2008 R2.

@RafaelSnor
Copy link

I had the same issue:

pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: The certificate chain was issued by an authority that is not trusted.\r\n (-2146893019) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 18 for SQL Server]Client unable to establish connection (-2146893019)')

And it was solved adding Encrypt=no

cnxn = pyodbc.connect(r'DRIVER={ODBC Driver 18 for SQL Server};SERVER='+x+';DATABASE='+database+';UID='+username+';PWD='+password+';Encrypt=no')

@WeinaWPS
Copy link

Boa noite! Tive o mesmo problema e resolvi com o Encrypt=no

OperationalError: ('08001', '[08001] fe_sendauth: no password supplied\n (101) (SQLDriverConnect)')

Solução:

import pyodbc

dados_conexao = ("Driver={PostgreSQL ODBC Driver(UNICODE)};"
"Server=127.0.0.1;"
"Database=postgres;"
"UID=postgres;"
"PWD=****;Encrypt=no;")

conexao = pyodbc.connect(dados_conexao)
print("Conexao bem sucedida")

@gparedesprieto
Copy link

En windows 11, me faltaba instalar openpyxl, pip install openpyxl.
Tambien verificar si es necesario instalar ODBC Driver 17 for SQL Server
https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver16

@gruossomonica
Copy link

gruossomonica commented Jul 19, 2023

Client environment

  • Python: 3.11 (installed using miniconda)
  • pyodbc: 4.0.39
  • OS: Ubuntu 22.04
  • DB: hosted on a remote Windows machine with SQL Server 2012
  • driver: ODBC Driver 17 for SQL Server (a.k.a. 17.10 version)

Issue

I'm trying to connect to a remote SQL server hosted on a Windows Machine with SQL Server 2012. I want to read a table in the SQL database.

The pyodbc connection command was the following:

conn = pyodbc.connect(
    "Driver={ODBC Driver 17 for SQL Server};"
    "Server=" + server_name + ";"
    "Database=" + database + ";"
    "UID=" + user_name + ";"
    "PWD=" + password + ";"
    "TrustServerCertificate=yes" 
)

I got a connection error:

pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)')

I tried to connect to the remote server using telnet on the 1433 port and it is ok. Then, I checked the SQL connection using the sqlcmd command using the same parameters. The connection was established and I was able to make queries.
I ran the isql command with the same connection string used with pyodbc and the connection was established.

I had to change the OpenSSL config following the issue comment to be able to connect at least with sqlcmd or isql.

The OpenSSL version is the following
OpenSSL 3.0.9 30 May 2023 (Library: OpenSSL 3.0.9 30 May 2023)

I also tried to add Encrypt=no or Encrypt=yes, but the error persists with pyodbc.

How can that error be solved?
Thanks to everyone!

@v-chojas
Copy link
Contributor

You can strace a successful connect using isql, and compare with an strace of your unsuccessful Python connect. In particular, pay attention to after it loads the driver lib (libmsodbcsql-17.x.so.y.z) for any differences.

@gruossomonica
Copy link

You can strace a successful connect using isql, and compare with an strace of your unsuccessful Python connect. In particular, pay attention to after it loads the driver lib (libmsodbcsql-17.x.so.y.z) for any differences.

Thanks for your support @v-chojas
I can't understand all the logs and I'm not sure about the differences. Below strace of the isql command (on the left) and strace of the connection with python (on the right) after the driver lib loading.
Could it depend on the conda env configuration? Package missing? Symlink to be configured?
Can you help me to better understand the strace log files?

image

Here the last part of the strace related to the python connection:
image

@v-chojas
Copy link
Contributor

If you actually post the files rather than images that can't be searched, then I may be able to read them.

@gruossomonica
Copy link

If you actually post the files rather than images that can't be searched, then I may be able to read them.

Hi @v-chojas Thanks again for your support! Here the files.

@gruossomonica
Copy link

Hi. The problem has been solved and the files are no longer available.

@jose-cheble
Copy link

@gruossomonica hi! Im having the same issue. I can connect using the isql but not with pyodbc. It'll be so helpfull if you could tell me more about how you fix your problems! Thanks a lot!

@gruossomonica
Copy link

Hi @jose-cheble, there were some problems with the sql server account. I have no useful tips. The IT department solved the issue.

@jose-cheble
Copy link

@v-chojas Hi! I'm running a Docker container with Debian 11 and using a Flask app. I can connect using isql -v -k <string>, but when I call the endpoint that contains the SQL connection using pyodbc, I get the following error:
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 18 for SQL
Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)')
I tried to trace it to understand it better, but to my surprise, when I ran the module in the console using python3 module_name.py, the connection is successful. I checked a few times and when i excecute the module in console the connection is succsessfull but not when calling the endpoint. Any suggestions? THANKS A LOTT!

@v-chojas
Copy link
Contributor

10054 - connection reset by peer. Are you sure connection string is identical in success and failure case?

@jose-cheble
Copy link

jose-cheble commented Sep 19, 2023

@v-chojas not only is the same connection string (i've checked it several times) but if a run my module where the connection to the sql server is made, the connection is succsessfull (python3 conn_sql_server.py).

this is conn_sql_server.py

import pyodbc 
import traceback

class SQL:
    def __init__(self):
        self.connection_string = 'DSN=test;UID=user;PWD=pass;'
        
        try:
            self.connection = pyodbc.connect(self.connection_string)
            self.cursor = self.connection.cursor()
            pass
        except Exception as e:
            traceback.print_exc()
    def get_cursor(self):
        return self.cursor

    def close(self):
        try:
            self.connection.close()
        except:
            pass
        try:
            self.cursor.close()
        except:
            pass
        pass


if __name__ == "__main__":
    sql = SQL()
    print("connected!!:", sql.connection)
    sql.close()

but imported from another module (its an endpoint in flask) it throws the 10054.

from flask import Blueprint, request
from utils.token_auth import token_required, admin_permission_required
import json
import os
from utils.conn_sql_server import SQL


configuracion = Blueprint('equipos_clientes_blueprint',__name__)


@configuracion.route('/clientes', methods=['GET'])
@token_required
def get_clientes():

    try:
        sql = SQL()
        print(sql.connection)
        return {"data": "llega"}, 200
    except Exception as e:
        return json.dumps({"responseInfo": f'Internal Server Error: {e}'}), 500
    finally:
        sql.close()

@mybugubird
Copy link

Im having the same issue.@jose-cheble,Just like you!

@jose-cheble
Copy link

@mybugubird yesterday I solved it. For my case the issue was that my flask application also was using mysql-connector-python. Its seems that when the mysql library is imported some dependencies are in conflict. Also would be a good idea check the working directory, It dependes from where you execute the app.

@mybugubird
Copy link

MSSQL Server typically uses TLS/SSL for secure communication. By default, MSSQL Server typically supports multiple TLS versions, including TLS 1.0. However, due to security considerations, newer OpenSSL versions may not default to TLS 1.0 as it is considered insecure. By setting MinProtocol to TLSv1.0, you explicitly told OpenSSL that TLS 1.0 is allowed, which may solve some connection issues, especially if MSSQL Server still requires TLS 1.0 for communication.

sudo vim /etc/ssl/openssl.cnf

MinProtocol = TLSv1.0
CipherString = DEFAULT@SECLEVEL=1

@triplehoon
Copy link

@sponaugle @eljirg
I am using amazon Linux for deploying Python with elastic beanstalk.

I am facing the same problem.

In Red Hat (in my case amazon Linux), you must configure /etc/pki/tls/openssl.cnf.

First, add or change,

openssl_conf = default_conf

and add to last line

[default_conf]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=1

I write a bash code doing this job.

       # Define the directory and file
        DIR="/etc/pki/tls/"
        FILE="openssl.cnf"
        BACKUP_FILE="openssl.cnf.bak"

        # Navigate to the directory
        cd $DIR

        # Backup the original file
        cp $FILE $BACKUP_FILE

        # Check if openssl_conf already exists and modify/add as necessary
        grep -q "openssl_conf" $FILE
        if [ $? -eq 0 ]; then
            # Line exists, modify it
            sed -i 's/^openssl_conf =.*/openssl_conf = default_conf/' $FILE
        else
            # Line doesn't exist, add it
            echo "openssl_conf = default_conf" >> $FILE
        fi

        # Check if [default_conf] already exists, if not add the additional configuration
        if ! grep -q "\[default_conf\]" $FILE; then
            cat <<EOL >>$FILE

        [default_conf]
        ssl_conf = ssl_sect

        [ssl_sect]
        system_default = system_default_sect

        [system_default_sect]
        MinProtocol = TLSv1.2
        CipherString = DEFAULT@SECLEVEL=1
        EOL
        fi

        echo "File updated successfully!"

@efren-cabrera
Copy link

@sponaugle @eljirg I am using amazon Linux for deploying Python with elastic beanstalk.

I am facing the same problem.

In Red Hat (in my case amazon Linux), you must configure /etc/pki/tls/openssl.cnf.

First, add or change,

openssl_conf = default_conf
...

I can confirm that this works on Amazon Linux 2023, thanks @triplehoon.

@thdaguin
Copy link

thdaguin commented Jan 5, 2024

Works for me on
Docker
Ubuntu 22.04
ODBC Driver 18 for SQL Server

In /etc/ssl/openssl.cnf file :

1/ change
openssl_conf = openssl_init
to
openssl_conf = default_conf

2/ add those lines at the end of file

[ default_conf ]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=0

Then test it with

isql -v -k "Driver={ODBC Driver 18 for SQL Server};Server=xx;Database=xx;UID=xx;PWD=xx;Encrypt=no"

@pmandadkes1207
Copy link

pmandadkes1207 commented May 26, 2024

Hello, I am getting the similar errors as mentioned above, but my case is a bit different. All my other processes/functions using a single process/cpu when trying to connect to sql server are working fine but when I use multiprocessing(even with 1cpu) of python it fails with the below errors.

pyodbc.OperationalError: ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLExecDirectW)')

pyodbc.OperationalError: ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]Communication link failure (-2147467259) (SQLEndTran)')

  • Python: 3.11.9
  • pyodbc: 5.1.0
  • OS: Ubuntu 24.04(deployed on AWS fargate instances)
  • DB: Microsoft SQL Server 2017 (RTM-CU27)(AWS RDS)
  • Driver: ODBC17 or ODBC 18

I am seeing this only when I am using multiprocessing on a linux system. I have other processes from same environment to the same sqlserver that doesn't use multiprocessing which don't fail. The weird part is, if I try to run this from my local windows machine with 8cpu with same code and same sql server, it worked every time without any issues. I tried increasing IOPS on sql server but no luck.

I would really appreciate any guidance to handle this error.

EDIT : I am also using pandas==2.2.2 to connect to sql server with pd.read_sql with pyodbc connection. I am not using sql alchemy due to some other package version conflicts.

@v-chojas
Copy link
Contributor

@pmandadkes1207 ODBC connections don't like being forked in a different process. lurcher/unixODBC#149

@pmandadkes1207
Copy link

pmandadkes1207 commented May 31, 2024

Thank you @v-chojas. As per the conversation in the link there are few approaches suggested. What would be the best way to handle this ? As one user suggested should I use the below :

mp.set_start_method('spawn')

In my case I should definitely use parallel processing due to the amount of data I have to process. Again this is only happening on Linux instance as I mentioned above.

Would setting start method to spawn be a better option or do you have any other recommendation ?

I really appreciate your help.

@v-chojas
Copy link
Contributor

You can try that and see whether it works for you. The goal is to not have the ODBC connections inherited across forked processes.

@pmandadkes1207
Copy link

pmandadkes1207 commented Jun 5, 2024

@v-chojas Setting start method to 'spawn' resolved the issue. Thank you for pointing me to the source of the issue.

@wilsonsergio2500
Copy link

Hi, I was experiencing the same problem, and fixed thanks to @v-chojas comment above. Just edited /etc/ssl/openssl.cnf and changed:

MinProtocol = TLSv1.0
CipherString = DEFAULT@SECLEVEL=1

This was truly the solution and thank you 🎉
My challenge presented itself within a context of an Azure Function. Challenge is / was that once the changes were made they did not persisted upon reboots or subsequent deployments. Hence, with the help of the above guide my solution was to introduce an openssl.cnf within the codebase and reference it as environment variable.

image

Just dropping this out here, Hoping to save someone a compelling amount of time, If they are faced with the same challenge 🙏🏼

@mobious999
Copy link

I've managed to get the connection working with ssl to an aws rds instance by using the following

Variables for database name etc removed.

Path to the SSL certificate included in the Lambda layer

ssl_certificate_path = './us-east-2-bundle.pem'

Connection string with SSL encryption

connection_string = (
f'DRIVER={{ODBC Driver 18 for SQL Server}};'
f'SERVER={server};'
f'DATABASE={database};'
f'UID={username};'
f'PWD={password};'
f'Encrypt=yes;'
f'TrustServerCertificate=yes;'
f'Trusted_Connection=no;'
f'WSID=localhost;'
f'APP=pyodbc-ssl;'
f'Mars_Connection=yes;'
f'ColumnEncryption=Enabled;'
f'SSL_Certificate={ssl_certificate_path}'
)

try:
# Establishing the connection
connection = pyodbc.connect(connection_string)
print("Connection successful")

# Example query execution
cursor = connection.cursor()
cursor.execute("SELECT @@VERSION;")
row = cursor.fetchone()
while row:
    print(row)
    row = cursor.fetchone()

except pyodbc.Error as e:
print(f"Error connecting to SQL Server: {e}")

finally:
# Closing the connection
if 'connection' in locals():
connection.close()
print("Connection closed")

No dsn connection just trying to see if I can connect.

odbcinst.ini
[ODBC Driver 18 for SQL Server]
Description=Microsoft ODBC Driver 18 for SQL Server
Driver=/opt/microsoft/msodbcsql18/lib64/libmsodbcsql-18.4.so.1.1
UsageCount=1

[ODBC]
Trace=Yes
TraceFile=/home/ec2-user/odbctrace.log

@v-chojas
Copy link
Contributor

From where are you seeing that "SSL_Certificate" is a valid connection string keyword? Because it's not.

https://learn.microsoft.com/en-us/sql/connect/odbc/dsn-connection-string-attribute?view=sql-server-ver16

@mobious999
Copy link

@v-chojas your right it's not part of the dsn - SSL_CERT_FILE is an environment variable https://stackoverflow.com/questions/14286265/how-to-use-ssl-cert-file-for-openssl-windows-openssl-1-0-1c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests