Python ssl.create_default_context() Examples

The following are 30 code examples of ssl.create_default_context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ssl , or try the search function .
Example #1
Source File: serializekiller.py    From serializekiller with The Unlicense 10 votes vote down vote up
def jenkins(url, port):
    try:
        cli_port = False
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        try:
            output = urllib2.urlopen('https://'+url+':'+port+"/jenkins/", context=ctx, timeout=8).info()
            cli_port = int(output['X-Jenkins-CLI-Port'])
        except urllib2.HTTPError, e:
            if e.getcode() == 404:
                try:
                    output = urllib2.urlopen('https://'+url+':'+port, context=ctx, timeout=8).info()
                    cli_port = int(output['X-Jenkins-CLI-Port'])
                except:
                    pass
        except:
            pass 
Example #2
Source File: microWebSrv2.py    From MicroWebSrv2 with MIT License 7 votes vote down vote up
def EnableSSL(self, certFile, keyFile, caFile=None) :
        import ssl
        if not hasattr(ssl, 'SSLContext') :
            raise MicroWebSrv2Exception('Unable to use SSL (implementation not supported).')
        if not isinstance(certFile, str) or len(certFile) == 0 :
            raise ValueError('"certFile" must be a not empty string.')
        if not isinstance(keyFile, str) or len(keyFile) == 0 :
            raise ValueError('"keyFile" must be a not empty string.')
        if caFile is not None and not isinstance(caFile, str) :
            raise ValueError('"caFile" must be a string or None.')
        self._validateChangeConf()
        try :
            ctx = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH,
                                              cafile = caFile )
        except :
            raise ValueError('"caFile" must indicate a valid PEM file.')
        try :
            ctx.load_cert_chain(certfile=certFile, keyfile=keyFile)
        except :
            raise ValueError('"certFile" and "keyFile" must indicate the valid certificate and key files.')
        self._sslContext = ctx
        if self._bindAddr[1] == 80 :
            self._bindAddr = (self._bindAddr[0], 443)

    # ------------------------------------------------------------------------ 
Example #3
Source File: http.py    From Sony-PMCA-RE with MIT License 6 votes vote down vote up
def request(url, data=None, headers={}, cookies={}, auth=None):
 if cookies:
  headers['Cookie'] = '; '.join(quote(k) + '=' + quote(v) for (k, v) in cookies.items())
 request = Request(str(url), data, headers)
 manager = HTTPPasswordMgrWithDefaultRealm()
 if auth:
  manager.add_password(None, request.get_full_url(), auth[0], auth[1])
 handlers = [HTTPBasicAuthHandler(manager), HTTPDigestAuthHandler(manager)]
 try:
  import certifi, ssl
  handlers.append(HTTPSHandler(context=ssl.create_default_context(cafile=certifi.where())))
 except:
  # App engine
  pass
 response = build_opener(*handlers).open(request)
 cj = CookieJar()
 cj.extract_cookies(response, request)
 headers = dict(response.headers)
 raw_contents = response.read()
 contents = raw_contents.decode(headers.get('charset', 'latin1'))
 return HttpResponse(urlparse(response.geturl()), contents, raw_contents, headers, dict((c.name, c.value) for c in cj)) 
Example #4
Source File: connections.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
def _create_ssl_ctx(self, sslp):
        if isinstance(sslp, ssl.SSLContext):
            return sslp
        ca = sslp.get('ca')
        capath = sslp.get('capath')
        hasnoca = ca is None and capath is None
        ctx = ssl.create_default_context(cafile=ca, capath=capath)
        ctx.check_hostname = not hasnoca and sslp.get('check_hostname', True)
        ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
        if 'cert' in sslp:
            ctx.load_cert_chain(sslp['cert'], keyfile=sslp.get('key'))
        if 'cipher' in sslp:
            ctx.set_ciphers(sslp['cipher'])
        ctx.options |= ssl.OP_NO_SSLv2
        ctx.options |= ssl.OP_NO_SSLv3
        return ctx 
Example #5
Source File: connections.py    From python-gvm with GNU General Public License v3.0 6 votes vote down vote up
def _new_socket(self):
        transport_socket = socketlib.socket(
            socketlib.AF_INET, socketlib.SOCK_STREAM
        )

        if self.certfile and self.cafile and self.keyfile:
            context = ssl.create_default_context(
                ssl.Purpose.SERVER_AUTH, cafile=self.cafile
            )
            context.check_hostname = False
            context.load_cert_chain(
                certfile=self.certfile,
                keyfile=self.keyfile,
                password=self.password,
            )
            sock = context.wrap_socket(transport_socket, server_side=False)
        else:
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            sock = context.wrap_socket(transport_socket)

        sock.settimeout(self._timeout)

        return sock 
Example #6
Source File: ca_certs_locater.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _read_ssl_default_ca_certs():
    # it's not guaranteed to return PEM formatted certs when `binary_form` is False
    der_certs = ssl.create_default_context().get_ca_certs(binary_form=True)
    pem_certs = [ssl.DER_cert_to_PEM_cert(der_cert_bytes) for der_cert_bytes in der_certs]
    return '\n'.join(pem_certs) 
Example #7
Source File: ssl_servers.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def make_https_server(case, context=None, certfile=CERTFILE,
                      host=HOST, handler_class=None):
    if context is None:
        context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    # We assume the certfile contains both private key and certificate
    context.load_cert_chain(certfile)
    server = HTTPSServerThread(context, host, handler_class)
    flag = threading.Event()
    server.start(flag)
    flag.wait()
    def cleanup():
        if support.verbose:
            sys.stdout.write('stopping HTTPS server\n')
        server.stop()
        if support.verbose:
            sys.stdout.write('joining HTTPS thread\n')
        server.join()
    case.addCleanup(cleanup)
    return server 
Example #8
Source File: urllib2.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
            cafile=None, capath=None, cadefault=False, context=None):
    global _opener
    if cafile or capath or cadefault:
        if context is not None:
            raise ValueError(
                "You can't pass both context and any of cafile, capath, and "
                "cadefault"
            )
        if not _have_ssl:
            raise ValueError('SSL support not available')
        context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH,
                                             cafile=cafile,
                                             capath=capath)
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif context:
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif _opener is None:
        _opener = opener = build_opener()
    else:
        opener = _opener
    return opener.open(url, data, timeout) 
Example #9
Source File: cloudscraper.py    From a4kScrapers with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.ssl_context = kwargs.pop('ssl_context', None)
        self.cipherSuite = kwargs.pop('cipherSuite', None)
        self.source_address = kwargs.pop('source_address', None)

        if self.source_address:
            if isinstance(self.source_address, str):
                self.source_address = (self.source_address, 0)

            if not isinstance(self.source_address, tuple):
                raise TypeError(
                    "source_address must be IP address string or (ip, port) tuple"
                )

        if not self.ssl_context:
            self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
            self.ssl_context.set_ciphers(self.cipherSuite)
            self.ssl_context.set_ecdh_curve('prime256v1')
            self.ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)

        super(CipherSuiteAdapter, self).__init__(**kwargs)

    # ------------------------------------------------------------------------------- # 
Example #10
Source File: __init__.py    From tikapy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _connect(self):
        """
        Connects a ssl socket.
        """
        self._connect_socket()
        try:
            ctx = ssl.create_default_context()
            if not self.verify_cert:
                ctx.verify_mode = ssl.CERT_OPTIONAL
            if not self.verify_addr:
                ctx.check_hostname = False
            self._sock = ctx.wrap_socket(self._base_sock,
                                         server_hostname=self.address)
        except ssl.SSLError:
            LOG.error('could not establish SSL connection')
            raise ClientError('could not establish SSL connection') 
Example #11
Source File: wfapi.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def _certifi_ssl_context(self):
        if (sys.version_info.major == 2 and sys.hexversion >= 0x02070900 or
           sys.version_info.major == 3 and sys.hexversion >= 0x03040300):
            where = certifi.where()
            self._log(DEBUG1, 'certifi %s: %s', certifi.__version__, where)
            return ssl.create_default_context(
                purpose=ssl.Purpose.SERVER_AUTH,
                cafile=where)
        else:
            return None


#
# XXX USE OF cloud_ssl_context() IS DEPRECATED!
#
# If your operating system certificate store is out of date you can
# install certifi (https://pypi.python.org/pypi/certifi) and its CA
# bundle will be used for SSL server certificate verification when
# ssl_context is None.
# 
Example #12
Source File: urllib2.py    From GDCTSCP with GNU Affero General Public License v3.0 6 votes vote down vote up
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
            cafile=None, capath=None, cadefault=False, context=None):
    global _opener
    if cafile or capath or cadefault:
        if context is not None:
            raise ValueError(
                "You can't pass both context and any of cafile, capath, and "
                "cadefault"
            )
        if not _have_ssl:
            raise ValueError('SSL support not available')
        context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH,
                                             cafile=cafile,
                                             capath=capath)
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif context:
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif _opener is None:
        _opener = opener = build_opener()
    else:
        opener = _opener
    return opener.open(url, data, timeout) 
Example #13
Source File: tulpar.py    From tulpar with GNU General Public License v3.0 6 votes vote down vote up
def certificateInformation(url,dosyaAdi):
    try:
        context = ssl.create_default_context()
        server = context.wrap_socket(socket.socket(), server_hostname=url)
        server.connect((url, 443))
        certificate = server.getpeercert()
        print "[+]Certificate Serial Number: ",certificate.get('serialNumber')
        print "[+]Certificate SSL Version:", certificate.get('version')
        print "[+]Certificate:",certificate
        raporIcerik="[+]Certificate Serial Number: "+str(certificate.get('serialNumber'))+"\n"
        raporIcerik+="[+]Certificate SSL Version:"+str(certificate.get('version'))+"\n"
        raporIcerik+="[+]Certificate:"+str(certificate)+"\n"
        rapor = open(dosyaAdi, "a")
        rapor.write(raporIcerik)
        rapor.close()
    except:
        pass 
Example #14
Source File: PubSubConsumer.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        self.logger.info('Connecting to %s', self._prefix)
        account = 'opensuse'
        server = 'rabbit.opensuse.org'
        if self._prefix == 'suse':
            account = 'suse'
            server = 'rabbit.suse.de'
        credentials = pika.PlainCredentials(account, account)
        context = ssl.create_default_context()
        ssl_options = pika.SSLOptions(context, server)
        parameters = pika.ConnectionParameters(server, 5671, '/', credentials, ssl_options=ssl_options, socket_timeout=10)
        return pika.SelectConnection(parameters,
                                     on_open_callback=self.on_connection_open) 
Example #15
Source File: PubSubConsumer.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        self.logger.info('Connecting to %s', self._prefix)
        account = 'opensuse'
        server = 'rabbit.opensuse.org'
        if self._prefix == 'suse':
            account = 'suse'
            server = 'rabbit.suse.de'
        credentials = pika.PlainCredentials(account, account)
        context = ssl.create_default_context()
        ssl_options = pika.SSLOptions(context, server)
        parameters = pika.ConnectionParameters(server, 5671, '/', credentials, ssl_options=ssl_options, socket_timeout=10)
        return pika.SelectConnection(parameters,
                                     on_open_callback=self.on_connection_open) 
Example #16
Source File: test_client.py    From selenium-wire with MIT License 5 votes vote down vote up
def _configure_proxy(self, host, port):
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        https_handler = urllib.request.HTTPSHandler(context=context)
        proxy_handler = urllib.request.ProxyHandler({
            'http': 'http://{}:{}'.format(host, port),
            'https': 'http://{}:{}'.format(host, port),
        })
        opener = urllib.request.build_opener(https_handler, proxy_handler)
        urllib.request.install_opener(opener) 
Example #17
Source File: iostream_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_check_hostname(self):
        # Test that server_hostname parameter to start_tls is being used.
        # The check_hostname functionality is only available in python 2.7 and
        # up and in python 3.4 and up.
        server_future = self.server_start_tls(_server_ssl_options())
        with ExpectLog(gen_log, "SSL Error"):
            client_future = self.client_start_tls(
                ssl.create_default_context(), server_hostname="127.0.0.1"
            )
            with self.assertRaises(ssl.SSLError):
                # The client fails to connect with an SSL error.
                yield client_future
            with self.assertRaises(Exception):
                # The server fails to connect, but the exact error is unspecified.
                yield server_future 
Example #18
Source File: timeitContext.py    From Learning-Concurrency-in-Python with MIT License 5 votes vote down vote up
def myFunction():
  # We create this context so that we can crawl 
  # https sites
  myssl = ssl.create_default_context();
  myssl.check_hostname=False
  myssl.verify_mode=ssl.CERT_NONE
  with Timer() as t:
    req = Request('https://tutorialedge.net', headers={'User-Agent': 'Mozilla/5.0'})
    response = urlopen(req, context=myssl)

  print("Elapsed Time: {} seconds".format(t.elapsed)) 
Example #19
Source File: simple_httpclient.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def _get_ssl_options(
        self, scheme: str
    ) -> Union[None, Dict[str, Any], ssl.SSLContext]:
        if scheme == "https":
            if self.request.ssl_options is not None:
                return self.request.ssl_options
            # If we are using the defaults, don't construct a
            # new SSLContext.
            if (
                self.request.validate_cert
                and self.request.ca_certs is None
                and self.request.client_cert is None
                and self.request.client_key is None
            ):
                return _client_ssl_defaults
            ssl_ctx = ssl.create_default_context(
                ssl.Purpose.SERVER_AUTH, cafile=self.request.ca_certs
            )
            if not self.request.validate_cert:
                ssl_ctx.check_hostname = False
                ssl_ctx.verify_mode = ssl.CERT_NONE
            if self.request.client_cert is not None:
                ssl_ctx.load_cert_chain(
                    self.request.client_cert, self.request.client_key
                )
            if hasattr(ssl, "OP_NO_COMPRESSION"):
                # See netutil.ssl_options_to_context
                ssl_ctx.options |= ssl.OP_NO_COMPRESSION
            return ssl_ctx
        return None 
Example #20
Source File: netutil.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def ssl_options_to_context(
    ssl_options: Union[Dict[str, Any], ssl.SSLContext]
) -> ssl.SSLContext:
    """Try to convert an ``ssl_options`` dictionary to an
    `~ssl.SSLContext` object.

    The ``ssl_options`` dictionary contains keywords to be passed to
    `ssl.wrap_socket`.  In Python 2.7.9+, `ssl.SSLContext` objects can
    be used instead.  This function converts the dict form to its
    `~ssl.SSLContext` equivalent, and may be used when a component which
    accepts both forms needs to upgrade to the `~ssl.SSLContext` version
    to use features like SNI or NPN.
    """
    if isinstance(ssl_options, ssl.SSLContext):
        return ssl_options
    assert isinstance(ssl_options, dict)
    assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options
    # Can't use create_default_context since this interface doesn't
    # tell us client vs server.
    context = ssl.SSLContext(ssl_options.get("ssl_version", ssl.PROTOCOL_SSLv23))
    if "certfile" in ssl_options:
        context.load_cert_chain(
            ssl_options["certfile"], ssl_options.get("keyfile", None)
        )
    if "cert_reqs" in ssl_options:
        context.verify_mode = ssl_options["cert_reqs"]
    if "ca_certs" in ssl_options:
        context.load_verify_locations(ssl_options["ca_certs"])
    if "ciphers" in ssl_options:
        context.set_ciphers(ssl_options["ciphers"])
    if hasattr(ssl, "OP_NO_COMPRESSION"):
        # Disable TLS compression to avoid CRIME and related attacks.
        # This constant depends on openssl version 1.0.
        # TODO: Do we need to do this ourselves or can we trust
        # the defaults?
        context.options |= ssl.OP_NO_COMPRESSION
    return context 
Example #21
Source File: honeypot.py    From heralding with GNU General Public License v3.0 5 votes vote down vote up
def create_ssl_context(pem_file):
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.check_hostname = False
    ssl_context.load_cert_chain(pem_file)
    return ssl_context 
Example #22
Source File: cacert_merge.py    From minemeld-core with Apache License 2.0 5 votes vote down vote up
def verify_cafile(cafile=None, cadata=None):
    try:
        create_default_context(cafile=cafile, cadata=cadata)
    except IOError as e:
        if cafile:
            LOG.error('Invalid cafile %s: %s' % (cafile, e))
        else:
            LOG.error('Invalid cadata: %s' % e)
        sys.exit(1) 
Example #23
Source File: test_urllibnet.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_context_argument(self):
        context = ssl.create_default_context(cafile=CERT_selfsigned_pythontestdotnet)
        response = urllib.urlopen("https://self-signed.pythontest.net", context=context)
        self.assertIn("Python", response.read()) 
Example #24
Source File: cacert_merge.py    From minemeld-core with Apache License 2.0 5 votes vote down vote up
def create_default_context(cafile, cadata):
        print('WARNING: old python version (< 2.7.9) - certificate verification not performed') 
Example #25
Source File: email_.py    From messages with MIT License 5 votes vote down vote up
def _get_tls(self):
        """Get an SMTP session with TLS."""
        session = smtplib.SMTP(self.server, self.port)
        session.ehlo()
        session.starttls(context=ssl.create_default_context())
        session.ehlo()
        return session 
Example #26
Source File: email_.py    From messages with MIT License 5 votes vote down vote up
def _get_ssl(self):
        """Get an SMTP session with SSL."""
        return smtplib.SMTP_SSL(
            self.server, self.port, context=ssl.create_default_context()
        ) 
Example #27
Source File: ssl_support.py    From lambda-packs with MIT License 5 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
            # change self.host to mean the proxy server host when tunneling is
            # being used. Adapt, since we are interested in the destination
            # host for the match_hostname() comparison.
            actual_host = self._tunnel_host
        else:
            actual_host = self.host

        if hasattr(ssl, 'create_default_context'):
            ctx = ssl.create_default_context(cafile=self.ca_bundle)
            self.sock = ctx.wrap_socket(sock, server_hostname=actual_host)
        else:
            # This is for python < 2.7.9 and < 3.4?
            self.sock = ssl.wrap_socket(
                sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
            )
        try:
            match_hostname(self.sock.getpeercert(), actual_host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise 
Example #28
Source File: client_rpc.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reconnect(self):
		"""Reconnect to the remote server."""
		self.lock.acquire()
		if self.use_ssl:
			if (sys.version_info[0] == 2 and sys.version_info >= (2, 7, 9)) or sys.version_info >= (3, 4, 3):
				context = ssl.create_default_context()
				context.check_hostname = False
				context.verify_mode = ssl.CERT_NONE
				self.client = advancedhttpserver.http.client.HTTPSConnection(self.host, self.port, context=context)
			else:
				self.client = advancedhttpserver.http.client.HTTPSConnection(self.host, self.port)
		else:
			self.client = advancedhttpserver.http.client.HTTPConnection(self.host, self.port)
		self.lock.release() 
Example #29
Source File: api_socket.py    From RouterOS-api with MIT License 5 votes vote down vote up
def get_socket(hostname, port, use_ssl=False, ssl_verify=True, ssl_verify_hostname=True, ssl_context=None, timeout=15.0):
    api_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    api_socket.settimeout(timeout)
    while True:
        try:
            api_socket.connect((hostname, port))
        except socket.error as e:
            if e.args[0] != EINTR:
                raise exceptions.RouterOsApiConnectionError(e)
        else:
            break
    set_keepalive(api_socket, after_idle_sec=10)
    # A provided ssl_context overrides any options
    if ssl_context is None and use_ssl:
        ssl_context = ssl.create_default_context()
        if ssl_verify:
            ssl_context.check_hostname = ssl_verify_hostname
            ssl_context.verify_mode = ssl.CERT_REQUIRED
        else:
            ssl_context.check_hostname = False
            ssl_context.verify_mode = ssl.CERT_NONE
    if ssl_context is not None:
        api_socket = ssl_context.wrap_socket(api_socket,server_hostname=hostname)
    return SocketWrapper(api_socket)

# http://stackoverflow.com/a/14855726 
Example #30
Source File: socketutil.py    From Pyro5 with MIT License 5 votes vote down vote up
def get_ssl_context(servercert: str = "", serverkey: str = "", clientcert: str = "", clientkey: str = "",
                    cacerts: str = "", keypassword: str = "") -> ssl.SSLContext:
    """creates an SSL context and caches it, so you have to set the parameters correctly before doing anything"""
    global __ssl_client_context, __ssl_server_context
    if servercert:
        if clientcert:
            raise ValueError("can't have both server cert and client cert")
        # server context
        if __ssl_server_context:
            return __ssl_server_context
        if not os.path.isfile(servercert):
            raise IOError("server cert file not found")
        if serverkey and not os.path.isfile(serverkey):
            raise IOError("server key file not found")
        __ssl_server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        __ssl_server_context.load_cert_chain(servercert, serverkey or None, keypassword or None)    # type: ignore
        if cacerts:
            if os.path.isdir(cacerts):
                __ssl_server_context.load_verify_locations(capath=cacerts)
            else:
                __ssl_server_context.load_verify_locations(cafile=cacerts)
        if config.SSL_REQUIRECLIENTCERT:
            __ssl_server_context.verify_mode = ssl.CERT_REQUIRED   # 2-way ssl, server+client certs
        else:
            __ssl_server_context.verify_mode = ssl.CERT_NONE   # 1-way ssl, server cert only
        return __ssl_server_context
    else:
        # client context
        if __ssl_client_context:
            return __ssl_client_context
        __ssl_client_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        if clientcert:
            if not os.path.isfile(clientcert):
                raise IOError("client cert file not found")
            __ssl_client_context.load_cert_chain(clientcert, clientkey or None, keypassword or None)    # type: ignore
        if cacerts:
            if os.path.isdir(cacerts):
                __ssl_client_context.load_verify_locations(capath=cacerts)
            else:
                __ssl_client_context.load_verify_locations(cafile=cacerts)
        return __ssl_client_context