本文整理汇总了Python中twisted.internet.ssl.optionsForClientTLS函数的典型用法代码示例。如果您正苦于以下问题:Python optionsForClientTLS函数的具体用法?Python optionsForClientTLS怎么用?Python optionsForClientTLS使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了optionsForClientTLS函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tls_options
def tls_options(hostname, cert_string=None):
"""Get certificate options for TLS connections.
If we are unable to use TLS because pyOpenSSL is not installed, this will
raise an exception.
Args:
hostname (string): The hostname we are trying to connect to with TLS.
cert_string (string): A certificate in PEM format. If provided, we
return CertificateOptions that will trust only the given cert
(assuming its canonical name attribute matches the given hostname).
If not provided, we will try to load a suitable certificate for
this hostname from our store of trusted self-signed certificates,
and otherwise fall back to just using the trust roots configured
for the OS to validate the server certificate.
Returns (twisted.internet.ssl.CertificateOptions):
Certificate suitable for use by TLS clients to connect to the given
Raises:
Exception: could not import pyOpenSSL package needed for TLS.
"""
if not TLS:
raise Exception('Unable to connect to labrad with TLS. Please be sure '
'to install pyOpenSSL.')
if cert_string is None:
cert_string = load_cert(hostname)
if cert_string is None:
logging.info('No certificate found for host "{}" in {}. Will use '
'system certs to verify tls'.format(hostname, CERTS_PATH))
return ssl.optionsForClientTLS(hostname.decode('utf-8'))
else:
cert = ssl.Certificate.loadPEM(cert_string)
return ssl.optionsForClientTLS(hostname.decode('utf-8'), cert)
示例2: _get_avatar
def _get_avatar(self, avatarId, mind):
endpointstr = self._endpointstr
basedn = self._basedn
binddn = self._binddn
bindpw = self._bindpw
query = self._query_template % {"username": escape_filter_chars(avatarId)}
if self._service_based_attribs:
if mind:
service = mind["service"]
else:
service = ""
if service == "" or service is None or self.service_manager is None:
attributes = self._attribs
else:
service_entry = yield defer.maybeDeferred(self.service_manager.getMatchingService, service)
if service_entry and "attributes" in service_entry:
attributes = service_entry["attributes"]
else:
attributes = self._attribs
else:
attributes = self._attribs
e = clientFromString(reactor, self._endpointstr)
client = yield connectProtocol(e, LDAPClient())
startTls = self._startTls
startTlsHostName = self._startTlsHostName
startTlsAuthority = self._startTlsAuthority
if startTls:
startTlsArgs = []
if startTlsHostName is not None:
if startTlsAuthority is not None:
ctx = optionsForClientTLS(unicode(startTlsHostName), startTlsAuthority)
else:
ctx = optionsForClientTLS(unicode(startTlsHostName), platformTrust())
startTlsArgs.append(ctx)
client = yield client.startTLS(*startTlsArgs)
yield client.bind(binddn, bindpw)
o = ldapsyntax.LDAPEntry(client, basedn)
results = yield o.search(filterText=query, attributes=attributes.keys())
yield client.unbind()
if len(results) != 1:
raise Exception("No unique account found for '%s'." % avatarId)
entry = results[0]
_attribs = attributes
attribs = []
for key, alias in _attribs.iteritems():
if key in entry:
valuelist = entry[key]
for value in valuelist:
attribs.append((alias, value))
user = User(avatarId, attribs)
defer.returnValue(user)
示例3: connect
def connect(self, host=None, port=None, cert=None, key=None):
'''
Connect to another portal somewhere. If retry is set, will attempt to reconnect
with the target continuously. As of the time of this writing, you cannot stop a
polling connection without taking down the portal.
:param retry: continuously attempt to connect on drops or rejections
:type retry: bool.
'''
host = host if host else self.host
port = port if port else self.port
cert = cert if cert else self.certCa
key = key if key else self.keyPrivate # ???
# the first term is the name the server is using in the cert (for now)
ctx = optionsForClientTLS(u"pds.production", Certificate.loadPEM(cert), PrivateCertificate.loadPEM(key))
factory = RiffleClientFactory()
SSL4ClientEndpoint(reactor, host, port, ctx,).connect(factory)
print 'Connecting to ' + host + ':' + str(port)
avatar = yield factory.login(self)
defer.returnValue(Levy(avatar))
示例4: main
def main(reactor, args):
kwds = {}
caCertData = args.ca_cert.read()
client_cert = args.client_cert
if client_cert is not None:
clientData = args.client_cert.read()
clientCertificate = ssl.PrivateCertificate.loadPEM(clientData)
kwds['clientCertificate'] = clientCertificate
authority = ssl.Certificate.loadPEM(caCertData)
host = args.host
port = args.port
netloc = "%s:%d" % (host, port)
if args.ssl_method is not None:
if args.ssl_method == 'ssl3':
extraCertificateOptions = {'method': SSL.SSLv3_METHOD}
elif args.ssl_method == 'tls1':
extraCertificateOptions = {'method': SSL.TLSv1_METHOD}
elif args.ssl_method == 'tls1_1':
extraCertificateOptions = {'method': SSL.TLSv1_1_METHOD}
elif args.ssl_method == 'tls1_2':
extraCertificateOptions = {'method': SSL.TLSv1_2_METHOD}
kwds['extraCertificateOptions'] = extraCertificateOptions
options = ssl.optionsForClientTLS( unicode(host), authority, **kwds)
#options = CustomClientConnectionCreator(ssl_opts, options)
s = yield getPage("https://%s/login" % netloc, contextFactory=options)
print s
示例5: connect
def connect(self, factory):
# further wrap the protocol if we're doing TLS.
# "pray i do not wrap the protocol further".
if self._tls:
# XXX requires Twisted 14+
from twisted.internet.ssl import optionsForClientTLS
context = optionsForClientTLS(self._host)
tls_factory = tls.TLSMemoryBIOFactory(context, True, factory)
socks_factory = _TorSocksFactory(
self._host, self._port, 'CONNECT', tls_factory,
)
else:
socks_factory = _TorSocksFactory(
self._host, self._port, 'CONNECT', factory,
)
self._socks_factory = socks_factory
# forward our address (when we get it) to any listeners
self._socks_factory._get_address().addBoth(self._when_address.fire)
# XXX isn't this just maybeDeferred()
if isinstance(self._proxy_ep, Deferred):
proxy_ep = yield self._proxy_ep
else:
proxy_ep = self._proxy_ep
# socks_proto = yield proxy_ep.connect(socks_factory)
proto = yield proxy_ep.connect(socks_factory)
wrapped_proto = yield proto.when_done()
if self._tls:
returnValue(wrapped_proto.wrappedProtocol)
else:
returnValue(wrapped_proto)
示例6: getMapUpdaterComponentService
def getMapUpdaterComponentService(self, url, realm, mapUpdater):
def create(config):
try:
session = MapUpdaterComponent(mapUpdater, config)
except Exception as e:
# the app component could not be created .. fatal
print(e)
else:
session.debug_app = True
return session
sessionFactory = ApplicationSessionFactory(
ComponentConfig(realm, None))
sessionFactory.session = create
transportFactory = WampWebSocketClientFactory(
sessionFactory, url=url)
transportFactory.noisy = False
transportFactory.autoPingInterval = 30
transportFactory.autoPingTimeout = 30
isSecure, host, port, resource, path, params = parseWsUrl(url)
endpoint = HostnameEndpoint(reactor, host.encode('utf8'), port)
if isSecure:
contextFactory = optionsForClientTLS(hostname=host)
endpoint = wrapClientTLS(contextFactory, endpoint)
return ClientService(endpoint, transportFactory)
示例7: func_connect
def func_connect(bot):
if reactor._started:
bot.say('[RatTracker] Reactor already running!')
return
bot.say('[RatTracker] Gotcha, connecting to RatTracker!')
MyClientProtocol.bot = bot
MyClientProtocol.debug_channel = bot.config.ratbot.debug_channel
MyClientProtocol.board = bot.memory['ratbot']['board']
factory = MyClientFactory(str(bot.config.socket.websocketurl) + ':' + bot.config.socket.websocketport)
factory.protocol = MyClientProtocol
# print('in connect')
hostname = str(bot.config.socket.websocketurl).replace("ws://", '').replace("wss://", '')
print('[Websocket] Hostname: ' + hostname)
if (bot.config.socket.websocketurl.startswith('wss://')):
reactor.connectSSL(hostname,
int(bot.config.socket.websocketport),
factory, contextFactory=optionsForClientTLS(hostname=hostname))
else:
reactor.connectTCP(hostname,
int(bot.config.socket.websocketport),
factory)
# print('pls')
thread = Thread(target=reactor.run, kwargs={'installSignalHandlers': 0})
thread.start()
示例8: endpointForURI
def endpointForURI(self, uri):
if uri.scheme in (b"http", b"https", b"ws", b"wss"):
defaultport = 443 if uri.scheme in (b"https", b"wss") else 80
host, port = BaseUrl.parsenetloc(uri.netloc, defaultport)
endpoint = t_endpoints.HostnameEndpoint(self.reactor, host, port)
if defaultport == 443:
ssl_supported = hasattr(t_endpoints, "TLSWrapperClientEndpoint")
try:
from twisted.internet.ssl import optionsForClientTLS
except ImportError:
ssl_supported = False
if not ssl_supported:
raise t_error.SchemeNotSupported(
"{} not supported (OpenSSL is not available)".format(uri.scheme.decode("utf_8"))
)
options = optionsForClientTLS(host.decode("utf_8"))
endpoint = t_endpoints.TLSWrapperClientEndpoint(options, endpoint)
return endpoint
if uri.scheme == b"unix":
path = url_parse.unquote(uri.netloc.decode("ascii"))
uri.netloc = b"localhost"
return t_endpoints.UNIXClientEndpoint(self.reactor, path)
raise t_error.SchemeNotSupported("{} not supported (unrecognized)".format(uri.scheme.decode("utf_8")))
示例9: start
def start(self):
"""
"""
log.msg("WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release.")
if CONFIG.has_option('output_hpfeeds', 'channel'):
self.channel = CONFIG.get('output_hpfeeds', 'channel')
if CONFIG.has_option('output_hpfeeds', 'endpoint'):
endpoint = CONFIG.get('output_hpfeeds', 'endpoint')
else:
server = CONFIG.get('output_hpfeeds', 'server')
port = CONFIG.getint('output_hpfeeds', 'port')
if CONFIG.has_option('output_hpfeeds', 'tlscert'):
with open(CONFIG.get('output_hpfeeds', 'tlscert')) as fp:
authority = ssl.Certificate.loadPEM(fp.read())
options = ssl.optionsForClientTLS(server, authority)
endpoint = endpoints.SSL4ClientEndpoint(reactor, server, port, options)
else:
endpoint = endpoints.HostnameEndpoint(reactor, server, port)
ident = CONFIG.get('output_hpfeeds', 'identifier')
secret = CONFIG.get('output_hpfeeds', 'secret')
self.meta = {}
self.client = ClientSessionService(endpoint, ident, secret)
self.client.startService()
示例10: create_ssl_context
def create_ssl_context(self, host, ssl_certificate):
#ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
#ssl_context.load_verify_locations(cafile = ssl_certificate)
#ssl_context.verify_mode = ssl.CERT_REQUIRED
certData = FilePath(ssl_certificate).getContent()
authority = ssl.Certificate.loadPEM(certData)
options = ssl.optionsForClientTLS(host, authority)
return options
示例11: creatorForNetloc
def creatorForNetloc(self, hostname, port):
# trustRoot set to platformTrust() will use the platform's root CAs.
#
# This means that a website like https://www.cacert.org will be rejected
# by default, since CAcert.org CA certificate is seldom shipped.
return optionsForClientTLS(hostname.decode("ascii"),
trustRoot=platformTrust(),
extraCertificateOptions={
'method': self._ssl_method,
})
示例12: _make_connect
def _make_connect(self, credentials):
basedn = self._basedn
e = clientFromString(reactor, self._endpointstr)
client = yield connectProtocol(e, LDAPClient())
startTls = self._startTls
startTlsHostName = self._startTlsHostName
startTlsAuthority = self._startTlsAuthority
if startTls:
startTlsArgs = []
if startTlsHostName is not None:
if startTlsAuthority is not None:
ctx = optionsForClientTLS(unicode(startTlsHostName), startTlsAuthority)
else:
ctx = optionsForClientTLS(unicode(startTlsHostName), platformTrust())
startTlsArgs.append(ctx)
client = yield client.startTLS(*startTlsArgs)
dn = yield self._get_dn(client, credentials.username)
yield client.bind(dn, credentials.password)
yield client.unbind()
defer.returnValue(credentials.username)
示例13: join
def join(self):
from twisted.internet._sslverify import OpenSSLCertificateAuthorities
from OpenSSL import crypto
if self._proto:
raise Exception("Already connected")
# Own callbacks
callbacks = {'connected': [CalvinCB(self._connected)],
'disconnected': [CalvinCB(self._disconnected)],
'connection_failed': [CalvinCB(self._connection_failed)],
'data': [CalvinCB(self._data)],
'set_proto': [CalvinCB(self._set_proto)]}
self._factory = TCPClientFactory(callbacks) # addr="%s:%s" % (self._host_ip, self._host_port))
runtime_to_runtime_security = _conf.get("security","runtime_to_runtime_security")
if runtime_to_runtime_security=="tls":
_log.debug("TwistedCalvinTransport with TLS chosen")
trusted_ca_certs = []
try:
self._runtime_credentials = runtime_credentials.RuntimeCredentials(self._node_name)
ca_cert_list_str = certificate.get_truststore_as_list_of_strings(certificate.TRUSTSTORE_TRANSPORT)
for ca_cert in ca_cert_list_str:
trusted_ca_certs.append(crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert))
ca_certs = OpenSSLCertificateAuthorities(trusted_ca_certs)
client_credentials_data =self._runtime_credentials.get_credentials()
client_credentials = ssl.PrivateCertificate.loadPEM(client_credentials_data)
except Exception as err:
_log.error("TwistedCalvinTransport: Failed to load client credentials, err={}".format(err))
raise
try:
options = ssl.optionsForClientTLS(self._server_node_name,
trustRoot=ca_certs,
clientCertificate=client_credentials)
except Exception as err:
_log.error("TwistedCalvinTransport: Failed to create optionsForClientTLS "
"\n\terr={}"
"\n\tself._server_node_name={}".format(err,
self._server_node_name))
raise
try:
endpoint = endpoints.SSL4ClientEndpoint(reactor,
self._host_ip,
int(self._host_port),
options)
except:
_log.error("TwistedCalvinTransport: Client failed connectSSL")
raise
try:
endpoint.connect(self._factory)
except Exception as e:
_log.error("TwistedCalvinTransport: Failed endpoint.connect, e={}".format(e))
raise
else:
reactor.connectTCP(self._host_ip, int(self._host_port), self._factory)
示例14: main
def main(reactor):
torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
ircEndpoint = SOCKS5ClientEndpoint('CHANGE_THIS', 6697, torEndpoint)
host = 'CHANGE_THIS'
options_ = optionsForClientTLS(hostname=host.decode('\
utf-8'), trustRoot=ssl.Certificate.loadPEM(FilePath('\
CHANGE_THIS').getContent()), clientCertificate=None)
tlsEndpoint = TLSWrapClientEndpoint(options_, ircEndpoint)
d = tlsEndpoint.connect(SpewingFactory(TorIRCFactory()))
d.addCallback(lambda proto: proto.wrappedProtocol.deferred)
return d
示例15: main
def main(reactor):
certData = FilePath('server-cert.pem').getContent()
serverCertificate = ssl.Certificate.loadPEM(certData)
options = ssl.optionsForClientTLS(
hostname=TARGET_HOST,
trustRoot=serverCertificate,
# `acceptableProtocols` is the targetted option for this example.
acceptableProtocols=ACCEPTABLE_PROTOCOLS,
)
class BasicH2Request(protocol.Protocol):
def connectionMade(self):
print("Connection made")
# Add a deferred that fires where we're done with the connection.
# This deferred is returned to the reactor, and when we call it
# back the reactor will clean up the protocol.
self.complete = defer.Deferred()
# Write some data to trigger the SSL handshake.
self.transport.write(TLS_TRIGGER_DATA)
def dataReceived(self, data):
# We can only safely be sure what the next protocol is when we know
# the TLS handshake is over. This is generally *not* in the call to
# connectionMade, but instead only when we've received some data
# back.
print('Next protocol is: %s' % self.transport.negotiatedProtocol)
self.transport.loseConnection()
# If this is the first data write, we can tell the reactor we're
# done here by firing the callback we gave it.
if self.complete is not None:
self.complete.callback(None)
self.complete = None
def connectionLost(self, reason):
# If we haven't received any data, an error occurred. Otherwise,
# we lost the connection on purpose.
if self.complete is not None:
print(("Connection lost due to error %s" % (reason,)))
self.complete.callback(None)
else:
print("Connection closed cleanly")
return endpoints.connectProtocol(
endpoints.SSL4ClientEndpoint(
reactor,
TARGET_HOST,
TARGET_PORT,
options
),
BasicH2Request()
).addCallback(lambda protocol: protocol.complete)