本文整理汇总了Python中ssl.SSLContext.wrap_socket方法的典型用法代码示例。如果您正苦于以下问题:Python SSLContext.wrap_socket方法的具体用法?Python SSLContext.wrap_socket怎么用?Python SSLContext.wrap_socket使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ssl.SSLContext
的用法示例。
在下文中一共展示了SSLContext.wrap_socket方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ssl_wrap_socket
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
def ssl_wrap_socket(
sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None
):
"""
All arguments except `server_hostname` have the same meaning as for
:func:`ssl.wrap_socket`
:param server_hostname:
Hostname of the expected certificate
"""
context = SSLContext(ssl_version)
context.verify_mode = cert_reqs
if ca_certs:
try:
context.load_verify_locations(ca_certs)
# Py32 raises IOError
# Py33 raises FileNotFoundError
except Exception: # Reraise as SSLError
e = sys.exc_info()[1]
raise SSLError(e)
if certfile:
# FIXME: This block needs a test.
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock)
示例2: ssl_wrap_socket
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None):
"""
All arguments except `server_hostname` have the same meaning as for
:func:`ssl.wrap_socket`
:param server_hostname:
Hostname of the expected certificate
"""
context = SSLContext(ssl_version)
context.verify_mode = cert_reqs
# Disable TLS compression to migitate CRIME attack (issue #309)
OP_NO_COMPRESSION = 0x20000
context.options |= OP_NO_COMPRESSION
if ca_certs:
try:
context.load_verify_locations(ca_certs)
# Py32 raises IOError
# Py33 raises FileNotFoundError
except Exception as e: # Reraise as SSLError
raise SSLError(e)
if certfile:
# FIXME: This block needs a test.
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock)
示例3: ssl_wrap_socket
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
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
OP_NO_COMPRESSION = 131072
context.options |= OP_NO_COMPRESSION
if ca_certs:
try:
context.load_verify_locations(ca_certs)
except Exception as e:
raise SSLError(e)
if certfile:
context.load_cert_chain(certfile, keyfile)
if HAS_SNI:
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock)
示例4: factory
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
def factory(uri, ssl=False, **init_args):
from urllib.parse import urlparse, unquote, parse_qs
o = urlparse(uri)
srv = None
if o.scheme == "irc" or o.scheme == "ircs":
# https://www.w3.org/Addressing/draft-mirashi-url-irc-01.txt
# https://www-archive.mozilla.org/projects/rt-messaging/chatzilla/irc-urls.html
args = init_args
if o.scheme == "ircs": ssl = True
if o.hostname is not None: args["host"] = o.hostname
if o.port is not None: args["port"] = o.port
if o.username is not None: args["username"] = o.username
if o.password is not None: args["password"] = o.password
modifiers = o.path.split(",")
target = unquote(modifiers.pop(0)[1:])
# Read query string
params = parse_qs(o.query)
if "msg" in params:
if "on_connect" not in args:
args["on_connect"] = []
args["on_connect"].append("PRIVMSG %s :%s" % (target, params["msg"]))
if "key" in params:
if "channels" not in args:
args["channels"] = []
args["channels"].append((target, params["key"]))
if "pass" in params:
args["password"] = params["pass"]
if "charset" in params:
args["encoding"] = params["charset"]
#
if "channels" not in args and "isnick" not in modifiers:
args["channels"] = [ target ]
from nemubot.server.IRC import IRC as IRCServer
srv = IRCServer(**args)
if ssl:
try:
from ssl import create_default_context
context = create_default_context()
except ImportError:
# Python 3.3 compat
from ssl import SSLContext, PROTOCOL_TLSv1
context = SSLContext(PROTOCOL_TLSv1)
from ssl import wrap_socket
srv._fd = context.wrap_socket(srv._fd, server_hostname=o.hostname)
return srv
示例5: __init__
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
def __init__(self, server_address, HandlerClass, dir):
super().__init__(server_address, HandlerClass, bind_and_activate=False)
ctx = SSLContext(PROTOCOL_TLSv1)
ctx.load_cert_chain(join(dir, 'server-cert.pem'), join(dir, 'server-key.pem'))
# ctx.load_verify_locations(join(dir, 'ca-cert.pem'))
self.socket = ctx.wrap_socket(self.socket, server_side=True)
self.server_bind()
self.server_activate()
示例6: ssl_wrap_socket
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
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)
# Py32 raises IOError
# Py33 raises FileNotFoundError
except Exception as e: # Reraise as SSLError
raise SSLError(e)
if certfile:
# FIXME: This block needs a test.
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return (context, context.wrap_socket(sock, server_hostname=server_hostname))
return (context, context.wrap_socket(sock))
示例7: ssl_wrap_socket
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=CERT_NONE,
ca_certs=None, server_hostname=None,
ssl_version=PROTOCOL_SSLv23):
"""
All arguments except `server_hostname` have the same meaning as for
:func:`ssl.wrap_socket`
:param server_hostname:
Hostname of the expected certificate
"""
context = SSLContext(ssl_version)
context.verify_mode = cert_reqs
if ca_certs:
try:
context.load_verify_locations(ca_certs)
except TypeError as e: # Reraise as SSLError
# FIXME: This block needs a test.
raise SSLError(e)
if certfile:
# FIXME: This block needs a test.
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock)
示例8: secureStream
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
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()
示例9: create_socket
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
def create_socket(ip: str, port: int, context: ssl.SSLContext = None,
verify_hostname: bool = True, timeout: int = 10) -> ssl.SSLSocket:
"""
Creates a new SSL-wrapped socket.
:param ip: The IP to connect to.
:param port: The port to connect to.
:param context: The SSL context to use, or None for a default one to be created.
:param verify_hostname: Ignored
:param timeout: The timeout for recv().
:return: A new SSLSocket.
"""
verify_hostname = current_app.conf["SERVER_LOGIN_ON_CLIENT_VERIFY"]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
if context:
sock = context.wrap_socket(s)
else:
sock = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED if verify_hostname else ssl.CERT_NONE)
sock.connect((ip, port))
return sock
示例10: secure_socket
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
def secure_socket(s, host):
ssl_context = SSLContext(PROTOCOL_SSLv23)
ssl_context.options |= OP_NO_SSLv2
return ssl_context.wrap_socket(s, server_hostname=host if HAS_SNI else None)
示例11: SMTPServer
# 需要导入模块: from ssl import SSLContext [as 别名]
# 或者: from ssl.SSLContext import wrap_socket [as 别名]
class SMTPServer(smtpd.SMTPServer):
def __init__(self, localaddr, remoteaddr, ssl=False, certfile=None, keyfile=None, ssl_version=ssl.PROTOCOL_SSLv23, require_authentication=False, credential_validator=None, maximum_execution_time=30, process_count=5):
smtpd.SMTPServer.__init__(self, localaddr, remoteaddr)
self.logger = logging.getLogger( secure_smtpd.LOG_NAME )
self.certfile = certfile
self.keyfile = keyfile
self.ssl_version = ssl_version
self.subprocesses = []
self.require_authentication = require_authentication
self.credential_validator = credential_validator
self.ssl = ssl
self.maximum_execution_time = maximum_execution_time
self.process_count = process_count
self.process_pool = None
self.context = SSLContext(ssl_version)
self.context.load_cert_chain(certfile=certfile, keyfile=keyfile)
def handle_accept(self):
self.process_pool = ProcessPool(self._accept_subprocess, process_count=self.process_count)
self.close()
def _accept_subprocess(self, queue):
while True:
try:
self.socket.setblocking(1)
pair = self.accept()
map = {}
if pair is not None:
self.logger.info('_accept_subprocess(): smtp connection accepted within subprocess.')
newsocket, fromaddr = pair
newsocket.settimeout(self.maximum_execution_time)
if self.ssl:
newsocket = self.context.wrap_socket(
newsocket,
server_side=True,
)
channel = SMTPChannel(
self,
newsocket,
fromaddr,
require_authentication=self.require_authentication,
credential_validator=self.credential_validator,
map=map
)
self.logger.info('_accept_subprocess(): starting asyncore within subprocess.')
asyncore.loop(map=map)
self.logger.error('_accept_subprocess(): asyncore loop exited.')
except (ExitNow, SSLError):
self._shutdown_socket(newsocket)
self.logger.info('_accept_subprocess(): smtp channel terminated asyncore.')
except Exception as e:
self._shutdown_socket(newsocket)
self.logger.error('_accept_subprocess(): uncaught exception: %s' % str(e))
def _shutdown_socket(self, s):
try:
s.shutdown(socket.SHUT_RDWR)
s.close()
except Exception as e:
self.logger.error('_shutdown_socket(): failed to cleanly shutdown socket: %s' % str(e))
def run(self):
asyncore.loop()
if hasattr(signal, 'SIGTERM'):
def sig_handler(signal,frame):
self.logger.info("Got signal %s, shutting down." % signal)
sys.exit(0)
signal.signal(signal.SIGTERM, sig_handler)
while 1:
time.sleep(1)