def get_ssl_context(*args): """Create and return an SSLContext object.""" certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. ctx = SSLContext(ssl.PROTOCOL_SSLv23) if hasattr(ctx, "options"): # Explicitly disable SSLv2 and SSLv3. Note that up to # date versions of MongoDB 2.4 and above already do this, # python disables SSLv2 by default in >= 2.7.7 and >= 3.3.4 # and SSLv3 in >= 3.4.3. There is no way for us to do this # explicitly for python 2.6 or 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) if certfile is not None: if passphrase is not None: vi = sys.version_info # Since python just added a new parameter to an existing method # this seems to be about the best we can do. if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi < (3, 3)): raise ConfigurationError( "Support for ssl_pem_passphrase requires " "python 2.7.9+ (pypy 2.5.1+) or 3.3+") ctx.load_cert_chain(certfile, keyfile, passphrase) else: ctx.load_cert_chain(certfile, keyfile) if crlfile is not None: if not hasattr(ctx, "verify_flags"): raise ConfigurationError( "Support for ssl_crlfile requires " "python 2.7.9+ (pypy 2.5.1+) or 3.4+") # Match the server's behavior. ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.load_verify_locations(crlfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs return ctx
def secure(self, verify=True, hostname=None): """ Apply a layer of security onto this connection. """ from ssl import SSLContext, SSLError try: # noinspection PyUnresolvedReferences from ssl import PROTOCOL_TLS except ImportError: from ssl import PROTOCOL_SSLv23 context = SSLContext(PROTOCOL_SSLv23) else: context = SSLContext(PROTOCOL_TLS) if verify: from ssl import CERT_REQUIRED context.verify_mode = CERT_REQUIRED context.check_hostname = bool(hostname) else: from ssl import CERT_NONE context.verify_mode = CERT_NONE context.load_default_certs() try: self.__socket = context.wrap_socket(self.__socket, server_hostname=hostname) except (IOError, OSError) as error: # TODO: add connection failure/diagnostic callback if error.errno == 0: raise BrokenWireError( "Peer closed connection during TLS handshake; " "server may not be configured for secure connections") else: raise WireError( "Unable to establish secure connection with remote peer") else: self.__active_time = monotonic()
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: try: context.load_verify_locations(ca_certs) print('------') except Exception as e: raise SSLError(e) else: context.load_default_certs(purpose=Purpose.SERVER_AUTH) if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: # server name indication enabled by OpenSSL return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def context(self) -> Optional[SSLContext]: if self.ssl: self.logger.info("Setting up SSL") context = SSLContext(PROTOCOL_TLS) if self.cert and self.key: self.logger.info("Using SSL Cert: %s", self.cert) try: context.load_cert_chain(str(self.cert), str(self.key), password=self.key_password) except FileNotFoundError as e: raise FileNotFoundError( better_file_not_found_error( self.cert, self.key, purpose='ssl cert loading')) if self.warn_if_expires_before_days: self._warn_expiry_task = create_task( self.check_cert_expiry()) set_task_name(self._warn_expiry_task, 'CheckSSLCertValidity') context.verify_mode = CERT_REQUIRED if self.cert_required else CERT_NONE context.check_hostname = self.check_hostname self.logger.info('%s, Check Hostname: %s' % (context.verify_mode, context.check_hostname)) if context.verify_mode != CERT_NONE: if self.cafile or self.capath or self.cadata: locations = { 'cafile': str(self.cafile) if self.cafile else None, 'capath': str(self.capath) if self.capath else None, 'cadata': self.cadata } try: context.load_verify_locations(**locations) self.logger.info("Verifying SSL certs with: %s", locations) except FileNotFoundError: raise FileNotFoundError( better_file_not_found_error( *locations.values(), purpose='CA ssl cert validation')) else: context.load_default_certs(self.purpose) self.logger.info("Verifying SSL certs with: %s", get_default_verify_paths()) self.logger.info("SSL Context loaded") # OpenSSL 1.1.1 keylog file if hasattr(context, 'keylog_filename'): keylogfile = os.environ.get('SSLKEYLOGFILE') if keylogfile and not sys.flags.ignore_environment: self.logger.warning( "TLS encryption secrets are being stored in %s", keylogfile) context.keylog_filename = keylogfile return context return None
def load_TLS(self): context = SSLContext(PROTOCOL_TLS) context.minimum_version = TLSVersion.TLSv1_3 context.verify_mode = CERT_REQUIRED context.check_hostname = True if self.CA != 'default' and self.CA != '': context.load_verify_locations(self.CA) else: context.load_default_certs() self.server = create_connection((self.SERVER_HOST, self.SERVER_PORT)) self.server = context.wrap_socket(self.server, server_hostname=self.SERVER_HOST)
class secureStream(stream): def __init__(self): stream.createsocket(stream) self.contxt = SSLContext(PROTOCOL_TLSv1_2) self.contxt.verify_mode = CERT_REQUIRED self.contxt.load_default_certs() def connect(self,host,port): self.connection.settimeout(15) self.connection.connect((host,port)) self.connection = self.contxt.wrap_socket(self.connection)#stream.connection self.connection.settimeout(0) def twitchconnect(self): self.connect('api.twitch.tv',443) def receive(self,buffer=4096): try: data = self.connection.recv(buffer).decode() #print(data)#temporary except: return(None) else: return(data) def transmit(self,data): junk = self.receive() data = data.encode() try: self.connection.sendall(data) except ConnectionAbortedError: print('Break detected!') self.connection = None self.connection = socket(AF_INET,SOCK_STREAM) self.twitchconnect() self.connection.settimeout(0) except ConnectionResetError: print('Break detected!') self.connection = None self.connection = socket(AF_INET,SOCK_STREAM) self.twitchconnect() self.connection.settimeout(0) junk = None def close(self): self.connection.close()
def secure(self, verify=True, hostname=None): """ Apply a layer of security onto this connection. """ from ssl import SSLContext, PROTOCOL_TLS, CERT_NONE, CERT_REQUIRED context = SSLContext(PROTOCOL_TLS) if verify: context.verify_mode = CERT_REQUIRED context.check_hostname = bool(hostname) else: context.verify_mode = CERT_NONE context.load_default_certs() try: self.__socket = context.wrap_socket(self.__socket, server_hostname=hostname) except (IOError, OSError): # TODO: add connection failure/diagnostic callback raise WireError( "Unable to establish secure connection with remote peer")
def __get_ssl_context(cls, sslca=None): """Make an SSLConext for this Python version using public or sslca """ if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or (version_info[0] == 3 and version_info[1] >= 4)): logger.debug('SSL method for 2.7.5+ / 3.4+') # pylint: disable=no-name-in-module,import-outside-toplevel from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # see CRIME security exploit ctx.options |= OP_NO_COMPRESSION # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = False else: # Verify public certifcates if sslca is None (default) from ssl import Purpose # pylint: disable=no-name-in-module,import-outside-toplevel ctx.load_default_certs(purpose=Purpose.SERVER_AUTH) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = True elif version_info[0] == 3 and version_info[1] < 4: logger.debug('Using SSL method for 3.2+, < 3.4') # pylint: disable=no-name-in-module,import-outside-toplevel from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 ctx = SSLContext(PROTOCOL_SSLv23) ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED else: # Verify public certifcates if sslca is None (default) ctx.set_default_verify_paths() ctx.verify_mode = CERT_REQUIRED else: raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3])) return ctx
def __get_ssl_context(cls, sslca=None): """Make an SSLConext for this Python version using public or sslca """ if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 9)) or (version_info[0] == 3 and version_info[1] >= 4)): logger.debug('SSL method for 2.7.9+ / 3.4+') # pylint: disable=no-name-in-module from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # see CRIME security exploit ctx.options |= OP_NO_COMPRESSION # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = False else: # Verify public certifcates if sslca is None (default) from ssl import Purpose # pylint: disable=no-name-in-module ctx.load_default_certs(purpose=Purpose.SERVER_AUTH) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = True elif version_info[0] == 3 and version_info[1] < 4: logger.debug('Using SSL method for 3.2+, < 3.4') # pylint: disable=no-name-in-module from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 ctx = SSLContext(PROTOCOL_SSLv23) ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED else: # Verify public certifcates if sslca is None (default) ctx.set_default_verify_paths() ctx.verify_mode = CERT_REQUIRED else: raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3])) return ctx
def get_ssl_context(*args): """Create and return an SSLContext object.""" certfile, keyfile, ca_certs, cert_reqs = args # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. ctx = SSLContext(ssl.PROTOCOL_SSLv23) if hasattr(ctx, "options"): # Explicitly disable SSLv2 and SSLv3. Note that up to # date versions of MongoDB 2.4 and above already do this, # python disables SSLv2 by default in >= 2.7.7 and >= 3.3.4 # and SSLv3 in >= 3.4.3. There is no way for us to do this # explicitly for python 2.6 or 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) if certfile is not None: ctx.load_cert_chain(certfile, keyfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs return ctx
async def main(host: str, port: int, handshake: bytes | None, api: int, input_timeout: float, idle_timeout: float, tls: bool, debug: bool): import logging from cats.v2 import Config, SHA256TimeHandshake from cats.v2.client import Connection logging.basicConfig(level='DEBUG' if debug else 'INFO', force=True) if handshake is not None: handshake = SHA256TimeHandshake(secret_key=handshake, valid_window=1, timeout=5.0) config = Config( idle_timeout=idle_timeout, input_timeout=input_timeout, input_limit=5, debug=debug, handshake=handshake, ) conn = Connection(config, api_version=api) ssl_options = None if tls: from ssl import SSLContext, PROTOCOL_TLS_CLIENT, CERT_REQUIRED ssl_options = SSLContext(protocol=PROTOCOL_TLS_CLIENT) ssl_options.verify_mode = CERT_REQUIRED ssl_options.load_default_certs() try: await conn.connect(host, port, ssl_options=ssl_options) await PingAction().send(conn) exit(int(not conn.is_open)) except (HandshakeError, ProtocolError): exit(0) except StreamClosedError: exit(1) except Exception: exit(500) raise
def main(host: str, port: int, handshake: bytes | None, api: int, input_timeout: float, idle_timeout: float, tls: bool, debug: bool): import logging from tornado.ioloop import IOLoop from cats.v2 import Config, SHA256TimeHandshake from cats.v2.server import Api, Application, Handler, Server logging.basicConfig(level='DEBUG' if debug else 'INFO', force=True) api = Api() class EchoHandler(Handler, api=api, id=0xFFFF): # noqa async def handle(self): return self.action if handshake is not None: handshake = SHA256TimeHandshake(secret_key=handshake, valid_window=1, timeout=5.0) config = Config(idle_timeout=idle_timeout, input_timeout=input_timeout, input_limit=5, debug=debug, handshake=handshake) ssl_options = None if tls: from ssl import SSLContext, PROTOCOL_TLS_CLIENT, CERT_REQUIRED ssl_options = SSLContext(protocol=PROTOCOL_TLS_CLIENT) ssl_options.verify_mode = CERT_REQUIRED ssl_options.load_default_certs() app = Application([api], config=config) cats_server = Server(app, ssl_options=ssl_options) cats_server.bind(port, host) cats_server.start(1) IOLoop.current().start()
def get_ssl_context(*args): """Create and return an SSLContext object.""" (certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile, match_hostname) = args verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating # PROTOCOL_SSLv23. ctx = SSLContext( getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23)) # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4. # PROTOCOL_TLS_CLIENT (added in Python 3.6) enables it by default. if hasattr(ctx, "check_hostname"): if _PY37PLUS and verify_mode != ssl.CERT_NONE: # Python 3.7 uses OpenSSL's hostname matching implementation # making it the obvious version to start using this with. # Python 3.6 might have been a good version, but it suffers # from https://bugs.python.org/issue32185. # We'll use our bundled match_hostname for older Python # versions, which also supports IP address matching # with Python < 3.5. ctx.check_hostname = match_hostname else: ctx.check_hostname = False if hasattr(ctx, "options"): # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that # up to date versions of MongoDB 2.4 and above already disable # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7 # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do # any of this explicitly for python 2.6 or 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) # OpenSSL >= 1.0.0 ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0) if certfile is not None: try: if passphrase is not None: vi = sys.version_info # Since python just added a new parameter to an existing method # this seems to be about the best we can do. if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi < (3, 3)): raise ConfigurationError( "Support for ssl_pem_passphrase requires " "python 2.7.9+ (pypy 2.5.1+) or 3.3+") ctx.load_cert_chain(certfile, keyfile, passphrase) else: ctx.load_cert_chain(certfile, keyfile) except ssl.SSLError as exc: raise ConfigurationError( "Private key doesn't match certificate: %s" % (exc, )) if crlfile is not None: if not hasattr(ctx, "verify_flags"): raise ConfigurationError( "Support for ssl_crlfile requires " "python 2.7.9+ (pypy 2.5.1+) or 3.4+") # Match the server's behavior. ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.load_verify_locations(crlfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = verify_mode return ctx
context = None if app.config.get('HERMES_CERTIFICAT_TLS') and app.config.get( 'HERMES_CLE_PRIVEE_TLS'): context = SSLContext(PROTOCOL_TLS) context.check_hostname = True context.set_ciphers( "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384" ) context.verify_mode = CERT_REQUIRED context.load_cert_chain(app.config.get('HERMES_CERTIFICAT_TLS'), app.config.get('HERMES_CLE_PRIVEE_TLS')) context.load_default_certs(Purpose.SERVER_AUTH) if app.config.get('HERMES_CERTIFICAT_CA'): context.load_verify_locations( app.config.get('HERMES_CERTIFICAT_CA')) adhoc_request = app.config.get( 'HERMES_CERTIFICAT_TLS') is False and app.config.get( 'HERMES_CLE_PRIVEE_TLS') is False and app.config.get( 'HERMES_CERTIFICAT_CA') is False app.run(host='0.0.0.0', port=5000, threaded=True, ssl_context=context if not adhoc_request else 'adhoc')
def ssl_context() -> SSLContext: context = SSLContext() context.load_default_certs() context.check_hostname = False context.verify_mode = CERT_NONE return context
except IOError as e: # Platform-specific: Python 2.7 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise <<<<<<< HEAD elif ssl_context is None and hasattr(context, 'load_default_certs'): ======= elif ssl_context is None and hasattr(context, "load_default_certs"): >>>>>>> master # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() # Attempt to detect if we get the goofy behavior of the # keyfile being encrypted and OpenSSL asking for the # passphrase via the terminal and instead error out. if keyfile and key_password is None and _is_key_file_encrypted(keyfile): raise SSLError("Client private key is encrypted, password is required") if certfile: if key_password is None: context.load_cert_chain(certfile, keyfile) else: context.load_cert_chain(certfile, keyfile, key_password) # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1
def get_ssl_context(*args): """Create and return an SSLContext object.""" certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating # PROTOCOL_SSLv23. ctx = SSLContext( getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23)) # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4. # PROTOCOL_TLS_CLIENT enables it by default. Using it # requires passing server_hostname to wrap_socket, which we already # do for SNI support. To support older versions of Python we have to # call match_hostname directly, so we disable check_hostname explicitly # to avoid calling match_hostname twice. if hasattr(ctx, "check_hostname"): ctx.check_hostname = False if hasattr(ctx, "options"): # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that # up to date versions of MongoDB 2.4 and above already disable # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7 # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do # any of this explicitly for python 2.6 or 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) # OpenSSL >= 1.0.0 ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0) if certfile is not None: try: if passphrase is not None: vi = sys.version_info # Since python just added a new parameter to an existing method # this seems to be about the best we can do. if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi < (3, 3)): raise ConfigurationError( "Support for ssl_pem_passphrase requires " "python 2.7.9+ (pypy 2.5.1+) or 3.3+") ctx.load_cert_chain(certfile, keyfile, passphrase) else: ctx.load_cert_chain(certfile, keyfile) except ssl.SSLError as exc: raise ConfigurationError( "Private key doesn't match certificate: %s" % (exc,)) if crlfile is not None: if not hasattr(ctx, "verify_flags"): raise ConfigurationError( "Support for ssl_crlfile requires " "python 2.7.9+ (pypy 2.5.1+) or 3.4+") # Match the server's behavior. ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.load_verify_locations(crlfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs return ctx
import io import os.path import urllib.request import smtplib from email.mime.text import MIMEText from ssl import SSLContext from apscheduler.schedulers.blocking import BlockingScheduler options_file = io.open('options.json') options = json.loads(''.join(options_file.readlines())) options_file.close() scheduler = BlockingScheduler() #load ssl context for emails ssl_context = SSLContext() ssl_context.load_default_certs() def notify(): if 'email' in options['notify']: msg = MIMEText("CK's page has updated!\n Check it out: %s" % options['ck_page']) msg['Subject'] = "CK's wepbages has updated!" msg['From'] = options['EMAILFrom'] msg['To'] = options['EMAILTo'] smtp = smtplib.SMTP_SSL(host=options['SMTPHost'], port=options['SMTPPort'], context=ssl_context) if options['SMTPUsername'] != '': try:
def get_ssl_context(*args): """Create and return an SSLContext object.""" (certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile, match_hostname) = args verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating # PROTOCOL_SSLv23. ctx = SSLContext( getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23)) # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4. # PROTOCOL_TLS_CLIENT (added in Python 3.6) enables it by default. if hasattr(ctx, "check_hostname"): if _PY37PLUS and verify_mode != ssl.CERT_NONE: # Python 3.7 uses OpenSSL's hostname matching implementation # making it the obvious version to start using this with. # Python 3.6 might have been a good version, but it suffers # from https://bugs.python.org/issue32185. # We'll use our bundled match_hostname for older Python # versions, which also supports IP address matching # with Python < 3.5. ctx.check_hostname = match_hostname else: ctx.check_hostname = False if hasattr(ctx, "options"): # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that # up to date versions of MongoDB 2.4 and above already disable # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7 # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do # any of this explicitly for python 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) # OpenSSL >= 1.0.0 ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0) # Python 3.7+ with OpenSSL >= 1.1.0h ctx.options |= getattr(ssl, "OP_NO_RENEGOTIATION", 0) if certfile is not None: try: if passphrase is not None: vi = sys.version_info # Since python just added a new parameter to an existing method # this seems to be about the best we can do. if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi < (3, 3)): raise ConfigurationError( "Support for ssl_pem_passphrase requires " "python 2.7.9+ (pypy 2.5.1+) or 3.3+") ctx.load_cert_chain(certfile, keyfile, passphrase) else: ctx.load_cert_chain(certfile, keyfile) except ssl.SSLError as exc: raise ConfigurationError( "Private key doesn't match certificate: %s" % (exc,)) if crlfile is not None: if not hasattr(ctx, "verify_flags"): raise ConfigurationError( "Support for ssl_crlfile requires " "python 2.7.9+ (pypy 2.5.1+) or 3.4+") # Match the server's behavior. ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.load_verify_locations(crlfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = verify_mode return ctx