3

I have configured my server to serve only https creating a self-signed certificate. I have a client that I has to validate the server's certificate and after that will download a file from the server.

How do I implement the validation in client? Is there any code example?

My question is similar with this one: How can the SSL client validate the server's certificate? but although the fine explanation, I didn't find any help.

So far, in my code I create a directory and then I download the file with urllib2:

[...] #imports

def dir_creation(path):
try:
    os.makedirs(path)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise


def file_download(url):
ver_file = urllib2.urlopen(url)
data = ver_file.read()
with open(local_filename, "wb") as code:
    code.write(data)

dir_creation(path)
file_download(url)
Community
  • 1
  • 1
antonis_man
  • 311
  • 2
  • 4
  • 10

1 Answers1

3

Rather than configuring your server to present a self-signed certificate, you should use a self-signed certificate as a certificate authority to sign the server certificate. (How to do this is beyond the scope of your question, but I'm sure you can find help on Stack Overflow or elsewhere.)

Now you must configure your client to trust your certificate authority. In python (2.7.9 or later), you can do this using the ssl module:

import ssl

...  # create socket

ctx = ssl.create_default_context(cafile=path_to_ca_certificate)
sslsock = ctx.wrap_socket(sock)

You can then transmit and read data on the secure socket. See the ssl module documentation for more explanation.

The urllib2 API is simpler:

import urllib2

resp = urllib2.urlopen(url, cafile=path_to_ca_certificate)
resp_body = resp.read()

If you wish to use Requests, according to the documentation you can supply a path to the CA certificate as the argument to the verify parameter:

resp = requests.get(url, verify=path_to_ca_certificate)
frasertweedale
  • 5,424
  • 3
  • 26
  • 38
  • I have updated the question with my code, I already use the urllib2 approach. So you say it can verify the certificate? I cannot get this parameter: cafile=path_to_ca_certificate. It is the client's cert? Can you please elaborate? – antonis_man Mar 10 '15 at 00:18
  • It landed in Python 2.7.9, which backported improvements to the `ssl` module. If you are using Python 2 you should upgrade to 2.7.9. – frasertweedale Mar 10 '15 at 01:39