我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ssl.PROTOCOL_TLSv1()。
def test_context(self): self.client.quit() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, keyfile=CERTFILE, context=ctx) self.client = ftplib.FTP_TLS(context=ctx, timeout=10) self.client.connect(self.server.host, self.server.port) self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) self.client.auth() self.assertIs(self.client.sock.context, ctx) self.assertIsInstance(self.client.sock, ssl.SSLSocket) self.client.prot_p() with self.client.transfercmd('list') as sock: self.assertIs(sock.context, ctx) self.assertIsInstance(sock, ssl.SSLSocket)
def start(self): self.deviceHandler.start() if self.protocol == "udp": self.loadState() self.logger.debug("udpHeartbeatSeconds = {0}".format(self.udpHeartbeatSeconds)) self.logger.debug("udpDataPacketInterval = {0}".format(self.udpDataPacketInterval)) self.udpServer = SocketServer.UDPServer(('0.0.0.0', 0), IotUDPHandler) self.udpServer.service = self self.udpServer.role = IotUDPHandler.CLIENT self.logger.info("starting UDP client at {0}:{1} connecting to {2}, state at {3}".format(self.udpServer.server_address[0], self.udpServer.server_address[1], self.serverAddr, self.stateFile)) timer = threading.Timer(0.5, self.repeat) timer.daemon = True timer.start() self.udpServer.serve_forever() elif self.protocol == "ssl": while True: self.logger.info("Connecting by SSL to server at {0}".format(self.serverAddr)) try: sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.logger.debug("using caCertFile={0}, deviceCertFile={1}, deviceKeyFile={2}".format(self.caCertFile, self.deviceCertFile, self.deviceKeyFile)) sslSocket = ssl.wrap_socket(sock, ca_certs=self.caCertFile, cert_reqs=ssl.CERT_REQUIRED, certfile=self.deviceCertFile, keyfile=self.deviceKeyFile, ssl_version=ssl.PROTOCOL_TLSv1) sslSocket.connect((self.serverAddr.split(':')[0], int(self.serverAddr.split(':')[1]))) servercert = sslSocket.getpeercert() subject = dict(x[0] for x in servercert['subject']) self.logger.info("Connected to server with valid certificate, CN={0}".format(subject['commonName'])) self.sslSocket = sslSocket sslThread = threading.Thread(target = self.sslListen, args = (self.sslSocket,)) sslThread.daemon = True sslThread.start() while True: payload = self.deviceHandler.getMessagePayload() self.logger.debug("Sending payload to {0} by SSL: {1}".format(self.serverAddr, payload)) iotcommon.sendMessage(self.sslSocket, payload) time.sleep(self.sslIntervalSeconds) except Exception as e: self.logger.exception(e) time.sleep(10)
def test_can_connect_with_ssl_ca(self): """ Test to validate that we are able to connect to a cluster using ssl. test_can_connect_with_ssl_ca performs a simple sanity check to ensure that we can connect to a cluster with ssl authentication via simple server-side shared certificate authority. The client is able to validate the identity of the server, however by using this method the server can't trust the client unless additional authentication has been provided. @since 2.6.0 @jira_ticket PYTHON-332 @expected_result The client can connect via SSL and preform some basic operations @test_category connection:ssl """ # find absolute path to client CA_CERTS abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) ssl_options = {'ca_certs': abs_path_ca_cert_path,'ssl_version': ssl.PROTOCOL_TLSv1} validate_ssl_options(ssl_options=ssl_options)
def test_can_connect_with_ssl_ca_host_match(self): """ Test to validate that we are able to connect to a cluster using ssl, and host matching test_can_connect_with_ssl_ca_host_match performs a simple sanity check to ensure that we can connect to a cluster with ssl authentication via simple server-side shared certificate authority. It also validates that the host ip matches what is expected @since 3.3 @jira_ticket PYTHON-296 @expected_result The client can connect via SSL and preform some basic operations, with check_hostname specified @test_category connection:ssl """ # find absolute path to client CA_CERTS abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) ssl_options = {'ca_certs': abs_path_ca_cert_path, 'ssl_version': ssl.PROTOCOL_TLSv1, 'cert_reqs': ssl.CERT_REQUIRED, 'check_hostname': True} validate_ssl_options(ssl_options=ssl_options)
def test_can_connect_with_ssl_client_auth(self): """ Test to validate that we can connect to a C* cluster that has client_auth enabled. This test will setup and use a c* cluster that has client authentication enabled. It will then attempt to connect using valid client keys, and certs (that are in the server's truststore), and attempt to preform some basic operations @since 2.7.0 @expected_result The client can connect via SSL and preform some basic operations @test_category connection:ssl """ # Need to get absolute paths for certs/key abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) abs_driver_keyfile = os.path.abspath(DRIVER_KEYFILE) abs_driver_certfile = os.path.abspath(DRIVER_CERTFILE) ssl_options = {'ca_certs': abs_path_ca_cert_path, 'ssl_version': ssl.PROTOCOL_TLSv1, 'keyfile': abs_driver_keyfile, 'certfile': abs_driver_certfile} validate_ssl_options(ssl_options)
def make_HTTPS_handler(params, **kwargs): opts_no_check_certificate = params.get('nocheckcertificate', False) if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9 context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) if opts_no_check_certificate: context.check_hostname = False context.verify_mode = ssl.CERT_NONE try: return YoutubeDLHTTPSHandler(params, context=context, **kwargs) except TypeError: # Python 2.7.8 # (create_default_context present but HTTPSHandler has no context=) pass if sys.version_info < (3, 2): return YoutubeDLHTTPSHandler(params, **kwargs) else: # Python < 3.4 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = (ssl.CERT_NONE if opts_no_check_certificate else ssl.CERT_REQUIRED) context.set_default_verify_paths() return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs): # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting # expected HTTP responses to meet HTTP/1.0 or later (see also # https://github.com/rg3/youtube-dl/issues/6727) if sys.version_info < (3, 0): kwargs[b'strict'] = True hc = http_class(*args, **kwargs) source_address = ydl_handler._params.get('source_address') if source_address is not None: sa = (source_address, 0) if hasattr(hc, 'source_address'): # Python 2.7+ hc.source_address = sa else: # Python 2.6 def _hc_connect(self, *args, **kwargs): sock = compat_socket_create_connection( (self.host, self.port), self.timeout, sa) if is_https: self.sock = ssl.wrap_socket( sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1) else: self.sock = sock hc.connect = functools.partial(_hc_connect, hc) return hc
def __init__(self, *args, **kwargs): self.ssl_kwargs = {"server_side" : False} if 'keyfile' in kwargs: self.ssl_kwargs["keyfile"] = kwargs['keyfile'] if 'certfile' in kwargs: self.ssl_kwargs["certfile"] = kwargs['certfile'] if 'ca_certs' in kwargs and kwargs['ca_certs'] is not None: self.ssl_kwargs["ca_certs"] = kwargs['ca_certs'] self.ssl_kwargs["cert_reqs"] = ssl.CERT_REQUIRED if 'cert_reqs' in kwargs: self.ssl_kwargs["cert_reqs"] = kwargs['cert_reqs'] if not 'ssl_version' in kwargs or kwargs['ssl_version'] is None: self.ssl_kwargs["ssl_version"] = ssl.PROTOCOL_TLSv1 else: self.ssl_kwargs["ssl_version"] = kwargs['ssl_version'] if 'ciphers' is kwargs: self.ssl_kwargs["ciphers"] = kwargs['cipher'] super(SSLClient, self).__init__()
def connect(self): """Overrides HTTPSConnection.connect to specify TLS version""" # Standard implementation from HTTPSConnection, which is not # designed for extension, unfortunately if sys.version_info >= (2, 7): sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) elif sys.version_info >= (2, 6): sock = socket.create_connection((self.host, self.port), self.timeout) else: sock = socket.create_connection((self.host, self.port)) if getattr(self, '_tunnel_host', None): self.sock = sock self._tunnel() # This is the only difference; default wrap_socket uses SSLv23 self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
def __init__(self, *args, **kwargs): self.ssl_kwargs = {"server_side" : False} if 'keyfile' in kwargs: self.ssl_kwargs["keyfile"] = kwargs['keyfile'] if 'certfile' in kwargs: self.ssl_kwargs["certfile"] = kwargs['certfile'] if 'ca_certs' in kwargs and kwargs['ca_certs'] is not None: self.ssl_kwargs["ca_certs"] = kwargs['ca_certs'] self.ssl_kwargs["cert_reqs"] = ssl.CERT_REQUIRED if 'cert_reqs' in kwargs: self.ssl_kwargs["cert_reqs"] = kwargs['cert_reqs'] if not 'ssl_version' in kwargs or kwargs['ssl_version'] is None: self.ssl_kwargs["ssl_version"] = ssl.PROTOCOL_TLSv1 else: self.ssl_kwargs["ssl_version"] = kwargs['ssl_version'] if 'ciphers' is kwargs: self.ssl_kwargs["ciphers"] = kwargs['cipher'] super(PupySSLClient, self).__init__(*args, **kwargs)
def setup_client(self): if self.client is None: if not HAVE_MQTT: print("Please install paho-mqtt 'pip install paho-mqtt' " "to use this library") return False self.client = mqtt.Client( client_id=self.blid, clean_session=self.clean, protocol=mqtt.MQTTv311) # Assign event callbacks self.client.on_message = self.on_message self.client.on_connect = self.on_connect self.client.on_publish = self.on_publish self.client.on_subscribe = self.on_subscribe self.client.on_disconnect = self.on_disconnect # Uncomment to enable debug messages # client.on_log = self.on_log # set TLS, self.cert_name is required by paho-mqtt, even if the # certificate is not used... # but v1.3 changes all this, so have to do the following: self.log.info("Seting TLS") try: self.client.tls_set( self.cert_name, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1) except ValueError: # try V1.3 version self.log.warn("TLS Setting failed - trying 1.3 version") self.client._ssl_context = None context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE context.load_default_certs() self.client.tls_set_context(context) # disables peer verification self.client.tls_insecure_set(True) self.client.username_pw_set(self.blid, self.password) return True return False
def startServer(self): self.accept_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.accept_socket.bind(self.addr) self.accept_socket.listen(1) def accept(): self.server_socket, _ = self.accept_socket.accept() # wrap socket with TLS-PSK self.server_psk_sock = sslpsk.wrap_socket(self.server_socket, psk=self.psk, ciphers='PSK-AES256-CBC-SHA', ssl_version=ssl.PROTOCOL_TLSv1, server_side=True) # accept data from client data = self.server_psk_sock.recv(10) self.server_psk_sock.sendall(data.upper()) threading.Thread(target = accept).start()
def prepare_sock(self, sock, server=None): if self.proto == socket.IPPROTO_SCTP: sock.events.clear() sock.events.data_io = 1 if self.ssl: if server: key=CertGen().get_key(server) try: # sock=ssl.wrap_socket(sock,keyfile=key,certfile=crt,ssl_version=ssl.PROTOCOL_TLSv1) sock=ssl.wrap_socket(sock,keyfile=key,certfile=key,ssl_version=ssl.PROTOCOL_SSLv23,server_side=True) except ssl.SSLError, e: print e else: try: sock=ssl.wrap_socket(sock,ssl_version=ssl.PROTOCOL_SSLv23,ciphers="ALL") except ssl.SSLError, e: print e return sock
def auth(self): '''Set up secure control connection by using TLS/SSL.''' if isinstance(self.sock, ssl.SSLSocket): raise ValueError("Already using TLS") if self.ssl_version == ssl.PROTOCOL_TLSv1: resp = self.voidcmd('AUTH TLS') else: resp = self.voidcmd('AUTH SSL') if self.context is not None: self.sock = self.context.wrap_socket(self.sock) else: self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ssl_version=self.ssl_version) self.file = self.sock.makefile(mode='r', encoding=self.encoding) return resp
def get_ssl_version(sock): # Seth behaves differently depeding on the TLS protocol # https://bugs.python.org/issue31453 # This is an ugly hack (as if the rest of this wasn't...) versions = [ ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, ] firstbytes = sock.recv(16, socket.MSG_PEEK) try: return versions[firstbytes[10]-1] except IndexError: print("Unexpected SSL version: %s" % hexlify(firstbytes)) return versions[-1] # def launch_rdp_client(): # time.sleep(1) # p = subprocess.Popen( # ["xfreerdp", # "/v:%s:%d" % (args.bind_ip, consts.RELAY_PORT), # "/u:%s\\%s" % (domain, user), # ], # )
def oooo(host, port, timeout = 5): iIIii1IIi = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if port == 443: if not oo000: raise decode('\x9b\x96\xf2\xdb\n\x98srb!J:Y\xe9\xf6') try: iIIii1IIi = ssl.wrap_socket(iIIii1IIi, ssl_version=ssl.PROTOCOL_TLSv1) except ssl.SSLError as o0OO00: iIIii1IIi = ssl.wrap_socket(iIIii1IIi, ssl_version=ssl.PROTOL_SSLv23) if 0: i11i.oOooOoO0Oo0O iIIii1IIi.settimeout(timeout) iIIii1IIi.connect((host, port)) return iIIii1IIi if 0: IIiI1I11i11
def test_context(self): self.client.quit() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, keyfile=CERTFILE, context=ctx) self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT) self.client.connect(self.server.host, self.server.port) self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) self.client.auth() self.assertIs(self.client.sock.context, ctx) self.assertIsInstance(self.client.sock, ssl.SSLSocket) self.client.prot_p() sock = self.client.transfercmd('list') try: self.assertIs(sock.context, ctx) self.assertIsInstance(sock, ssl.SSLSocket) finally: sock.close()
def _do_tls_handshake(self): logging.debug('Initializing TLS connection with {}:{}'.format(self.host, self.port)) self.s = ssl.wrap_socket(self.s, keyfile=os.path.join(shared.source_directory, 'tls', 'key.pem'), certfile=os.path.join(shared.source_directory, 'tls', 'cert.pem'), server_side=self.server, ssl_version=ssl.PROTOCOL_TLSv1, do_handshake_on_connect=False, ciphers='AECDH-AES256-SHA', suppress_ragged_eofs=True) if hasattr(self.s, "context"): self.s.context.set_ecdh_curve("secp256k1") while True: try: self.s.do_handshake() break except ssl.SSLWantReadError: select.select([self.s], [], []) except ssl.SSLWantWriteError: select.select([], [self.s], []) except Exception as e: logging.debug('Disconnecting from {}:{}. Reason: {}'.format(self.host, self.port, e)) self.status = 'disconnecting' break self.tls = True logging.debug('Established TLS connection with {}:{}'.format(self.host, self.port))
def test_context(self): self.client.quit() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, keyfile=CERTFILE, context=ctx) self.client = ftplib.FTP_TLS(context=ctx, timeout=2) self.client.connect(self.server.host, self.server.port) self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) self.client.auth() self.assertIs(self.client.sock.context, ctx) self.assertIsInstance(self.client.sock, ssl.SSLSocket) self.client.prot_p() with self.client.transfercmd('list') as sock: self.assertIs(sock.context, ctx) self.assertIsInstance(sock, ssl.SSLSocket)
def server_loop(self, ofp_tcp_listen_port, ofp_ssl_listen_port): if CONF.ctl_privkey is not None and CONF.ctl_cert is not None: if CONF.ca_certs is not None: server = StreamServer((CONF.ofp_listen_host, ofp_ssl_listen_port), datapath_connection_factory, keyfile=CONF.ctl_privkey, certfile=CONF.ctl_cert, cert_reqs=ssl.CERT_REQUIRED, ca_certs=CONF.ca_certs, ssl_version=ssl.PROTOCOL_TLSv1) else: server = StreamServer((CONF.ofp_listen_host, ofp_ssl_listen_port), datapath_connection_factory, keyfile=CONF.ctl_privkey, certfile=CONF.ctl_cert, ssl_version=ssl.PROTOCOL_TLSv1) else: server = StreamServer((CONF.ofp_listen_host, ofp_tcp_listen_port), datapath_connection_factory) # LOG.debug('loop') server.serve_forever()
def __init__(self): """ Create a BasicAuthenticationSuite object. """ super(BasicAuthenticationSuite, self).__init__() self._protocol = ssl.PROTOCOL_TLSv1 self._ciphers = ':'.join(( 'AES128-SHA', 'DES-CBC3-SHA', 'AES256-SHA', 'DHE-DSS-DES-CBC3-SHA', 'DHE-RSA-DES-CBC3-SHA', 'DH-DSS-AES128-SHA', 'DH-RSA-AES128-SHA', 'DHE-DSS-AES128-SHA', 'DHE-RSA-AES128-SHA', 'DH-RSA-AES256-SHA', 'DHE-DSS-AES256-SHA', 'DHE-RSA-AES256-SHA', ))
def _connect(self, host, port, timeout, isssl = False): conn = None try: if isssl and not _SUPPORT_SSL: raise 'Not SUPPORT SSL' conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if isssl: try: conn = ssl.wrap_socket(conn, ssl_version=ssl.PROTOCOL_TLSv1) except ssl.SSLError as _: conn = ssl.wrap_socket(conn, ssl_version=ssl.PROTOL_SSLv23) conn.settimeout(timeout) conn.connect((host, port)) except Exception as e: raise CurlError(Curl.CURLE_COULDNT_CONNECT) return conn
def _apns_create_socket(address_tuple, app_id): app_settings = get_app_settings(app_id) if not app_settings: raise ImproperlyConfigured('You need to set UNIVERSAL_NOTIFICATIONS_MOBILE_APPS[app_id]' ' to send messages through APNS') certfile = app_settings.get("APNS_CERTIFICATE") if not certfile: raise ImproperlyConfigured( 'You need to set UNIVERSAL_NOTIFICATIONS_MOBILE_APPS[app_id]["APNS_CERTIFICATE"] ' 'to send messages through APNS.' ) try: with open(certfile, "r") as f: f.read() except Exception as e: raise ImproperlyConfigured("The APNS certificate file at %r is not readable: %s" % (certfile, e)) sock = socket.socket() sock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1, certfile=certfile) sock.connect(address_tuple) return sock
def __init__(self, server_address, RequestHandlerClass, settings, bind_and_activate=True): """Constructor. May be extended, do not override.""" self.log_path = settings['log'] self.key_file = settings['key'] self.cert_file = settings['cert'] self.allow_ip = IPRange(settings['allow_ip']) self.spellchecker = hunspell.HunSpell('/usr/share/hunspell/en_US.dic', '/usr/share/hunspell/en_US.aff') SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, False) # initialize SSL connection self.socket = ssl.wrap_socket(self.socket, keyfile=self.key_file, certfile=self.cert_file, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1, server_side=True) # start serving if bind_and_activate: self.server_bind() self.server_activate()
def send_xmlrpc(ip, port): s = socket.socket() s.settimeout(10) s.connect((ip, int(port))) # Initial packet which will trigger XMLRPC communication s.sendall("TLSRPC") wrappedSocket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1, ciphers=None) # CONNECT AND PRINT REPLY send_netsh_data(wrappedSocket, create_request(ip, port, INITIATOR)) print "+ Initiator response:" print recv_xmlrpc_data(wrappedSocket) send_netsh_data(wrappedSocket, create_request(ip, port, GetHostOverview)) print recv_xmlrpc_data(wrappedSocket) # CLOSE SOCKET CONNECTION wrappedSocket.close()
def test_context(self): self.client.quit() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, keyfile=CERTFILE, context=ctx) self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT) self.client.connect(self.server.host, self.server.port) self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) self.client.auth() self.assertIs(self.client.sock.context, ctx) self.assertIsInstance(self.client.sock, ssl.SSLSocket) self.client.prot_p() with self.client.transfercmd('list') as sock: self.assertIs(sock.context, ctx) self.assertIsInstance(sock, ssl.SSLSocket)
def create_socket(): logger.info('Creating SSL socket') s_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = ssl.wrap_socket( sock=s_, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_REQUIRED, ssl_version=getattr( ssl, 'PROTOCOL_TLSv1_2', ssl.PROTOCOL_TLSv1 ), ca_certs=certifi.where(), do_handshake_on_connect=True, suppress_ragged_eofs=True, ) try: logger.info('Connecting to {}:{}'.format(ENDPOINT, PORT)) s.connect((ENDPOINT, PORT)) return s except socket.error, exc: logger.error('Exception socket.error : {}'.format(exc))