2009-11-13 11:46:23 +01:00
|
|
|
# Copyright (C) 2009 Novell Inc.
|
|
|
|
# This program is free software; it may be used, copied, modified
|
|
|
|
# and distributed under the terms of the GNU General Public Licence,
|
|
|
|
# either version 2, or (at your option) any later version.
|
|
|
|
|
2013-04-09 12:51:28 +02:00
|
|
|
from __future__ import print_function
|
|
|
|
|
2009-11-13 11:46:23 +01:00
|
|
|
import M2Crypto.httpslib
|
|
|
|
from M2Crypto.SSL.Checker import SSLVerificationError
|
|
|
|
from M2Crypto import m2, SSL
|
2010-01-08 22:20:40 +01:00
|
|
|
import M2Crypto.m2urllib2
|
|
|
|
import socket
|
2011-01-05 16:31:02 +01:00
|
|
|
import sys
|
2009-11-13 11:46:23 +01:00
|
|
|
|
2013-04-09 12:36:42 +02:00
|
|
|
try:
|
2013-04-09 14:03:17 +02:00
|
|
|
from urllib.parse import urlparse, splithost, splitport, splittype
|
|
|
|
from urllib.request import addinfourl
|
2013-04-09 12:36:42 +02:00
|
|
|
from http.client import HTTPSConnection
|
|
|
|
except ImportError:
|
|
|
|
#python 2.x
|
|
|
|
from urlparse import urlparse
|
2013-04-09 14:03:17 +02:00
|
|
|
from urllib import addinfourl, splithost, splitport, splittype
|
2013-04-09 12:36:42 +02:00
|
|
|
from httplib import HTTPSConnection
|
|
|
|
|
2013-04-09 13:02:24 +02:00
|
|
|
from .core import raw_input
|
|
|
|
|
2009-11-13 11:46:23 +01:00
|
|
|
class TrustedCertStore:
|
|
|
|
_tmptrusted = {}
|
|
|
|
|
|
|
|
def __init__(self, host, port, app, cert):
|
|
|
|
|
|
|
|
self.cert = cert
|
|
|
|
self.host = host
|
|
|
|
if self.host == None:
|
|
|
|
raise Exception("empty host")
|
|
|
|
if port:
|
|
|
|
self.host += "_%d" % port
|
|
|
|
import os
|
|
|
|
self.dir = os.path.expanduser('~/.config/%s/trusted-certs' % app)
|
|
|
|
self.file = self.dir + '/%s.pem' % self.host
|
|
|
|
|
|
|
|
def is_known(self):
|
|
|
|
if self.host in self._tmptrusted:
|
|
|
|
return True
|
|
|
|
|
|
|
|
import os
|
|
|
|
if os.path.exists(self.file):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def is_trusted(self):
|
|
|
|
import os
|
|
|
|
if self.host in self._tmptrusted:
|
|
|
|
cert = self._tmptrusted[self.host]
|
|
|
|
else:
|
|
|
|
if not os.path.exists(self.file):
|
|
|
|
return False
|
|
|
|
from M2Crypto import X509
|
|
|
|
cert = X509.load_cert(self.file)
|
|
|
|
if self.cert.as_pem() == cert.as_pem():
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def trust_tmp(self):
|
|
|
|
self._tmptrusted[self.host] = self.cert
|
|
|
|
|
|
|
|
def trust_always(self):
|
|
|
|
self.trust_tmp()
|
|
|
|
from M2Crypto import X509
|
|
|
|
import os
|
|
|
|
if not os.path.exists(self.dir):
|
|
|
|
os.makedirs(self.dir)
|
|
|
|
self.cert.save_pem(self.file)
|
|
|
|
|
|
|
|
|
|
|
|
# verify_cb is called for each error once
|
|
|
|
# we only collect the errors and return suceess
|
|
|
|
# connection will be aborted later if it needs to
|
2009-11-17 14:39:40 +01:00
|
|
|
def verify_cb(ctx, ok, store):
|
|
|
|
if not ctx.verrs:
|
2010-02-24 20:02:52 +01:00
|
|
|
ctx.verrs = ValidationErrors()
|
2009-11-13 11:46:23 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
if not ok:
|
2009-11-17 14:39:40 +01:00
|
|
|
ctx.verrs.record(store.get_current_cert(), store.get_error(), store.get_error_depth())
|
2009-11-13 11:46:23 +01:00
|
|
|
return 1
|
|
|
|
|
2013-04-09 11:27:02 +02:00
|
|
|
except Exception as e:
|
2013-06-15 08:53:26 +02:00
|
|
|
print(e, file=sys.stderr)
|
2009-11-13 11:46:23 +01:00
|
|
|
return 0
|
|
|
|
|
|
|
|
class FailCert:
|
|
|
|
def __init__(self, cert):
|
|
|
|
self.cert = cert
|
|
|
|
self.errs = []
|
|
|
|
|
|
|
|
class ValidationErrors:
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.chain_ok = True
|
|
|
|
self.cert_ok = True
|
|
|
|
self.failures = {}
|
|
|
|
|
|
|
|
def record(self, cert, err, depth):
|
|
|
|
#print "cert for %s, level %d fail(%d)" % ( cert.get_subject().commonName, depth, err )
|
|
|
|
if depth == 0:
|
|
|
|
self.cert_ok = False
|
|
|
|
else:
|
|
|
|
self.chain_ok = False
|
|
|
|
|
|
|
|
if not depth in self.failures:
|
|
|
|
self.failures[depth] = FailCert(cert)
|
|
|
|
else:
|
|
|
|
if self.failures[depth].cert.get_fingerprint() != cert.get_fingerprint():
|
|
|
|
raise Exception("Certificate changed unexpectedly. This should not happen")
|
|
|
|
self.failures[depth].errs.append(err)
|
|
|
|
|
2013-06-15 08:53:26 +02:00
|
|
|
def show(self, out):
|
2009-11-13 11:46:23 +01:00
|
|
|
for depth in self.failures.keys():
|
|
|
|
cert = self.failures[depth].cert
|
2013-06-15 08:53:26 +02:00
|
|
|
print("*** certificate verify failed at depth %d" % depth, file=out)
|
|
|
|
print("Subject: ", cert.get_subject(), file=out)
|
|
|
|
print("Issuer: ", cert.get_issuer(), file=out)
|
|
|
|
print("Valid: ", cert.get_not_before(), "-", cert.get_not_after(), file=out)
|
|
|
|
print("Fingerprint(MD5): ", cert.get_fingerprint('md5'), file=out)
|
|
|
|
print("Fingerprint(SHA1): ", cert.get_fingerprint('sha1'), file=out)
|
2009-11-13 11:46:23 +01:00
|
|
|
|
|
|
|
for err in self.failures[depth].errs:
|
|
|
|
reason = "Unknown"
|
|
|
|
try:
|
|
|
|
import M2Crypto.Err
|
|
|
|
reason = M2Crypto.Err.get_x509_verify_error(err)
|
|
|
|
except:
|
|
|
|
pass
|
2013-06-15 08:53:26 +02:00
|
|
|
print("Reason:", reason, file=out)
|
2009-11-13 11:46:23 +01:00
|
|
|
|
|
|
|
# check if the encountered errors could be ignored
|
|
|
|
def could_ignore(self):
|
|
|
|
if not 0 in self.failures:
|
|
|
|
return True
|
|
|
|
|
|
|
|
nonfatal_errors = [
|
|
|
|
m2.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY,
|
|
|
|
m2.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN,
|
|
|
|
m2.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT,
|
|
|
|
m2.X509_V_ERR_CERT_UNTRUSTED,
|
|
|
|
m2.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE,
|
|
|
|
|
|
|
|
m2.X509_V_ERR_CERT_NOT_YET_VALID,
|
|
|
|
m2.X509_V_ERR_CERT_HAS_EXPIRED,
|
|
|
|
m2.X509_V_OK,
|
|
|
|
]
|
|
|
|
|
|
|
|
canignore = True
|
|
|
|
for err in self.failures[0].errs:
|
|
|
|
if not err in nonfatal_errors:
|
|
|
|
canignore = False
|
|
|
|
break
|
|
|
|
|
|
|
|
return canignore
|
|
|
|
|
|
|
|
class mySSLContext(SSL.Context):
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
SSL.Context.__init__(self, 'sslv23')
|
2011-09-20 15:32:13 +02:00
|
|
|
self.set_options(m2.SSL_OP_NO_SSLv2 | m2.SSL_OP_NO_SSLv3)
|
2012-07-16 05:20:19 +02:00
|
|
|
self.set_cipher_list("ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH")
|
2011-04-18 11:02:26 +02:00
|
|
|
self.set_session_cache_mode(m2.SSL_SESS_CACHE_CLIENT)
|
2009-11-17 14:39:40 +01:00
|
|
|
self.verrs = None
|
2009-11-13 11:46:23 +01:00
|
|
|
#self.set_info_callback() # debug
|
2009-11-17 14:39:40 +01:00
|
|
|
self.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=9, callback=lambda ok, store: verify_cb(self, ok, store))
|
2009-11-13 11:46:23 +01:00
|
|
|
|
2010-01-08 22:20:40 +01:00
|
|
|
class myHTTPSHandler(M2Crypto.m2urllib2.HTTPSHandler):
|
|
|
|
handler_order = 499
|
2011-04-18 11:02:26 +02:00
|
|
|
saved_session = None
|
2010-01-08 22:20:40 +01:00
|
|
|
|
2010-01-20 14:46:10 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.appname = kwargs.pop('appname', 'generic')
|
|
|
|
M2Crypto.m2urllib2.HTTPSHandler.__init__(self, *args, **kwargs)
|
|
|
|
|
2010-01-08 22:20:40 +01:00
|
|
|
# copied from M2Crypto.m2urllib2.HTTPSHandler
|
|
|
|
# it's sole purpose is to use our myHTTPSHandler/myHTTPSProxyHandler class
|
|
|
|
# ideally the m2urllib2.HTTPSHandler.https_open() method would be split into
|
|
|
|
# "do_open()" and "https_open()" so that we just need to override
|
|
|
|
# the small "https_open()" method...)
|
|
|
|
def https_open(self, req):
|
|
|
|
host = req.get_host()
|
|
|
|
if not host:
|
2010-03-07 21:56:29 +01:00
|
|
|
raise M2Crypto.m2urllib2.URLError('no host given: ' + req.get_full_url())
|
2010-01-08 22:20:40 +01:00
|
|
|
|
|
|
|
# Our change: Check to see if we're using a proxy.
|
|
|
|
# Then create an appropriate ssl-aware connection.
|
2010-02-28 02:30:13 +01:00
|
|
|
full_url = req.get_full_url()
|
2013-04-09 12:36:42 +02:00
|
|
|
target_host = urlparse(full_url)[1]
|
2010-01-08 22:20:40 +01:00
|
|
|
|
|
|
|
if (target_host != host):
|
2010-01-20 14:46:10 +01:00
|
|
|
h = myProxyHTTPSConnection(host = host, appname = self.appname, ssl_context = self.ctx)
|
2010-12-17 18:14:11 +01:00
|
|
|
# M2Crypto.ProxyHTTPSConnection.putrequest expects a fullurl
|
|
|
|
selector = full_url
|
2010-01-08 22:20:40 +01:00
|
|
|
else:
|
2010-01-20 14:46:10 +01:00
|
|
|
h = myHTTPSConnection(host = host, appname = self.appname, ssl_context = self.ctx)
|
2010-12-17 18:14:11 +01:00
|
|
|
selector = req.get_selector()
|
2010-01-08 22:20:40 +01:00
|
|
|
# End our change
|
|
|
|
h.set_debuglevel(self._debuglevel)
|
2011-04-18 11:02:26 +02:00
|
|
|
if self.saved_session:
|
|
|
|
h.set_session(self.saved_session)
|
2010-01-08 22:20:40 +01:00
|
|
|
|
|
|
|
headers = dict(req.headers)
|
|
|
|
headers.update(req.unredirected_hdrs)
|
|
|
|
# We want to make an HTTP/1.1 request, but the addinfourl
|
|
|
|
# class isn't prepared to deal with a persistent connection.
|
|
|
|
# It will try to read all remaining data from the socket,
|
|
|
|
# which will block while the server waits for the next request.
|
|
|
|
# So make sure the connection gets closed after the (only)
|
|
|
|
# request.
|
|
|
|
headers["Connection"] = "close"
|
|
|
|
try:
|
2010-12-17 18:14:11 +01:00
|
|
|
h.request(req.get_method(), selector, req.data, headers)
|
2011-04-18 11:02:26 +02:00
|
|
|
s = h.get_session()
|
|
|
|
if s:
|
|
|
|
self.saved_session = s
|
2010-01-08 22:20:40 +01:00
|
|
|
r = h.getresponse()
|
2013-04-09 11:27:02 +02:00
|
|
|
except socket.error as err: # XXX what error?
|
2010-03-07 21:56:29 +01:00
|
|
|
err.filename = full_url
|
|
|
|
raise M2Crypto.m2urllib2.URLError(err)
|
2010-01-08 22:20:40 +01:00
|
|
|
|
|
|
|
# Pick apart the HTTPResponse object to get the addinfourl
|
|
|
|
# object initialized properly.
|
|
|
|
|
|
|
|
# Wrap the HTTPResponse object in socket's file object adapter
|
|
|
|
# for Windows. That adapter calls recv(), so delegate recv()
|
|
|
|
# to read(). This weird wrapping allows the returned object to
|
|
|
|
# have readline() and readlines() methods.
|
|
|
|
|
|
|
|
# XXX It might be better to extract the read buffering code
|
|
|
|
# out of socket._fileobject() and into a base class.
|
|
|
|
|
|
|
|
r.recv = r.read
|
|
|
|
fp = socket._fileobject(r)
|
|
|
|
|
2013-04-09 14:03:17 +02:00
|
|
|
resp = addinfourl(fp, r.msg, req.get_full_url())
|
2010-01-08 22:20:40 +01:00
|
|
|
resp.code = r.status
|
|
|
|
resp.msg = r.reason
|
|
|
|
return resp
|
2009-11-13 11:46:23 +01:00
|
|
|
|
|
|
|
class myHTTPSConnection(M2Crypto.httpslib.HTTPSConnection):
|
2010-01-20 14:46:10 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.appname = kwargs.pop('appname', 'generic')
|
|
|
|
M2Crypto.httpslib.HTTPSConnection.__init__(self, *args, **kwargs)
|
|
|
|
|
2009-11-13 11:46:23 +01:00
|
|
|
def connect(self, *args):
|
2010-01-08 22:20:40 +01:00
|
|
|
M2Crypto.httpslib.HTTPSConnection.connect(self, *args)
|
|
|
|
verify_certificate(self)
|
|
|
|
|
|
|
|
def getHost(self):
|
|
|
|
return self.host
|
|
|
|
|
|
|
|
def getPort(self):
|
|
|
|
return self.port
|
|
|
|
|
2013-04-09 12:36:42 +02:00
|
|
|
class myProxyHTTPSConnection(M2Crypto.httpslib.ProxyHTTPSConnection, HTTPSConnection):
|
2010-01-20 14:46:10 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.appname = kwargs.pop('appname', 'generic')
|
|
|
|
M2Crypto.httpslib.ProxyHTTPSConnection.__init__(self, *args, **kwargs)
|
|
|
|
|
2010-01-08 22:20:40 +01:00
|
|
|
def _start_ssl(self):
|
|
|
|
M2Crypto.httpslib.ProxyHTTPSConnection._start_ssl(self)
|
|
|
|
verify_certificate(self)
|
|
|
|
|
2010-09-16 14:28:14 +02:00
|
|
|
def endheaders(self, *args, **kwargs):
|
2010-12-17 18:14:11 +01:00
|
|
|
if self._proxy_auth is None:
|
2010-09-16 14:28:14 +02:00
|
|
|
self._proxy_auth = self._encode_auth()
|
2014-08-12 15:01:16 +02:00
|
|
|
HTTPSConnection.endheaders(self, *args, **kwargs)
|
2010-09-16 14:28:14 +02:00
|
|
|
|
2010-01-08 22:20:40 +01:00
|
|
|
# broken in m2crypto: port needs to be an int
|
|
|
|
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
|
|
|
|
#putrequest is called before connect, so can interpret url and get
|
|
|
|
#real host/port to be used to make CONNECT request to proxy
|
2013-04-09 14:03:17 +02:00
|
|
|
proto, rest = splittype(url)
|
2010-01-08 22:20:40 +01:00
|
|
|
if proto is None:
|
2013-04-09 12:54:54 +02:00
|
|
|
raise ValueError("unknown URL type: %s" % url)
|
2010-01-08 22:20:40 +01:00
|
|
|
#get host
|
2013-04-09 14:03:17 +02:00
|
|
|
host, rest = splithost(rest)
|
2010-01-08 22:20:40 +01:00
|
|
|
#try to get port
|
2013-04-09 14:03:17 +02:00
|
|
|
host, port = splitport(host)
|
2010-01-08 22:20:40 +01:00
|
|
|
#if port is not defined try to get from proto
|
|
|
|
if port is None:
|
|
|
|
try:
|
|
|
|
port = self._ports[proto]
|
|
|
|
except KeyError:
|
2013-04-09 12:54:54 +02:00
|
|
|
raise ValueError("unknown protocol for: %s" % url)
|
2010-01-08 22:20:40 +01:00
|
|
|
self._real_host = host
|
|
|
|
self._real_port = int(port)
|
|
|
|
M2Crypto.httpslib.HTTPSConnection.putrequest(self, method, url, skip_host, skip_accept_encoding)
|
|
|
|
|
|
|
|
def getHost(self):
|
|
|
|
return self._real_host
|
|
|
|
|
|
|
|
def getPort(self):
|
|
|
|
return self._real_port
|
|
|
|
|
|
|
|
def verify_certificate(connection):
|
|
|
|
ctx = connection.sock.ctx
|
|
|
|
verrs = ctx.verrs
|
|
|
|
ctx.verrs = None
|
|
|
|
cert = connection.sock.get_peer_cert()
|
|
|
|
if not cert:
|
|
|
|
connection.close()
|
|
|
|
raise SSLVerificationError("server did not present a certificate")
|
|
|
|
|
|
|
|
# XXX: should be check if the certificate is known anyways?
|
|
|
|
# Maybe it changed to something valid.
|
|
|
|
if not connection.sock.verify_ok():
|
|
|
|
|
2010-01-19 13:31:07 +01:00
|
|
|
tc = TrustedCertStore(connection.getHost(), connection.getPort(), connection.appname, cert)
|
2010-01-08 22:20:40 +01:00
|
|
|
|
|
|
|
if tc.is_known():
|
|
|
|
|
|
|
|
if tc.is_trusted(): # ok, same cert as the stored one
|
|
|
|
return
|
|
|
|
else:
|
2013-04-09 12:51:28 +02:00
|
|
|
print("WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!", file=sys.stderr)
|
|
|
|
print("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!", file=sys.stderr)
|
|
|
|
print("offending certificate is at '%s'" % tc.file, file=sys.stderr)
|
2011-01-05 17:00:19 +01:00
|
|
|
raise SSLVerificationError("remote host identification has changed")
|
2010-01-08 22:20:40 +01:00
|
|
|
|
2013-06-15 08:53:26 +02:00
|
|
|
# if http_debug is set we redirect sys.stdout to an StringIO
|
|
|
|
# instance in order to do some header filtering (see conf module)
|
|
|
|
# so we have to use the "original" stdout for printing
|
|
|
|
out = getattr(connection, '_orig_stdout', sys.stdout)
|
|
|
|
verrs.show(out)
|
2010-01-08 22:20:40 +01:00
|
|
|
|
2013-06-15 08:53:26 +02:00
|
|
|
print(file=out)
|
2010-01-08 22:20:40 +01:00
|
|
|
|
|
|
|
if not verrs.could_ignore():
|
|
|
|
raise SSLVerificationError("Certificate validation error cannot be ignored")
|
|
|
|
|
|
|
|
if not verrs.chain_ok:
|
2013-06-15 08:53:26 +02:00
|
|
|
print("A certificate in the chain failed verification", file=out)
|
2010-01-08 22:20:40 +01:00
|
|
|
if not verrs.cert_ok:
|
2013-06-15 08:53:26 +02:00
|
|
|
print("The server certificate failed verification", file=out)
|
2010-01-08 22:20:40 +01:00
|
|
|
|
|
|
|
while True:
|
2013-04-09 12:51:28 +02:00
|
|
|
print("""
|
2009-11-13 11:46:23 +01:00
|
|
|
Would you like to
|
2010-01-08 22:20:40 +01:00
|
|
|
0 - quit (default)
|
|
|
|
1 - continue anyways
|
|
|
|
2 - trust the server certificate permanently
|
|
|
|
9 - review the server certificate
|
2013-06-15 08:53:26 +02:00
|
|
|
""", file=out)
|
2010-01-08 22:20:40 +01:00
|
|
|
|
2013-06-15 08:53:26 +02:00
|
|
|
print("Enter choice [0129]: ", end='', file=out)
|
|
|
|
r = raw_input()
|
2010-01-08 22:20:40 +01:00
|
|
|
if not r or r == '0':
|
|
|
|
connection.close()
|
|
|
|
raise SSLVerificationError("Untrusted Certificate")
|
|
|
|
elif r == '1':
|
|
|
|
tc.trust_tmp()
|
|
|
|
return
|
|
|
|
elif r == '2':
|
|
|
|
tc.trust_always()
|
|
|
|
return
|
|
|
|
elif r == '9':
|
2013-06-15 08:53:26 +02:00
|
|
|
print(cert.as_text(), file=out)
|
2009-11-13 11:46:23 +01:00
|
|
|
|
2010-02-25 09:52:47 +01:00
|
|
|
# vim: sw=4 et
|