How do I have python httplib accept untrusted certs?
Asked Answered
U

2

21

How do I have python httplib accept untrusted certs? I created a snake oil/self signed cert on my webserver, and my python client fails to connect as I am using a untrusted cert.

I'd rather problematically fix this in my client code rather than have it trusted on my system.

import httplib


def main():
    conn = httplib.HTTPSConnection("127.0.0.1:443")
    conn.request("HEAD","/")
    res = conn.getresponse()
    print res.status, res.reason
    data = res.read()
    print len(data)


if __name__ == "__main__":
    main()
Unprofitable answered 15/3, 2011 at 23:51 Comment(1)
(I'm guessing you mean "programmatically", rather than "problematically"...) Are you sure of what's happening? The docs say "This does not do any verification of the server’s certificate.", so it should accept a self-signed certificate.Aldo
C
46

Some of my scripts stopped working after updating my computer. Turns out, this was the problem: https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection

Changed in version 2.7.9: context was added.

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

So if your version of Python is >= 2.7.9 (2.7.10 in my case), you'll likely run into this. To fix it, I updated my call:

httplib.HTTPSConnection(hostname, timeout=5, context=ssl._create_unverified_context())

This is likely the simplest change to retain the same behavior.

Coronet answered 24/8, 2015 at 18:38 Comment(1)
Thanks. I also ran into this problem, although it was in Python 2.7.5 strangely - probably after a CentOS update. The same solution worked there as well. I did have to import ssl though.Mortonmortuary
P
8

From inspecting the Python 2.7.14 source code, you may set an environment variable

PYTHONHTTPSVERIFY=0

and this will cause certificate verification to be disabled by default (this will apply to all requests from your program).

I believe this works from 2.7.12+ - but it does not apply to 3.x.

Ref. PEP 493: Verify HTTPS by default, but allow envvar to override that

Pyroxenite answered 17/11, 2017 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.