本文整理汇总了Python中backports.ssl_match_hostname.match_hostname函数的典型用法代码示例。如果您正苦于以下问题:Python match_hostname函数的具体用法?Python match_hostname怎么用?Python match_hostname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了match_hostname函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: connect
def connect(self):
# Create the raw socket and wrap it in ssl.
httplib.HTTPConnection.connect(self)
self.sock = ssl.wrap_socket(self.sock, **self.__kwargs)
# Verify the remote hostname.
match_hostname(self.sock.getpeercert(), self.host.split(':', 1)[0])
开发者ID:vgol,项目名称:freeipa-rosa,代码行数:7,代码来源:otptoken.py
示例2: connect
def connect(self):
"""
Connect
Checks if verification is toggled; if not, just call
httplib.HTTPSConnection's connect
"""
if not self.verify:
return httplib.HTTPSConnection.connect(self)
# otherwise, create a connection and verify the hostname
# use socket.create_connection (in 2.6+) if possible
if getattr(socket, 'create_connection', None):
sock = socket.create_connection((self.host, self.port),
self.timeout)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.host, self.port))
# Activate the HTTP proxy
if self.http_proxy_used:
self._activate_http_proxy(sock=sock)
self.sock = ssl.wrap_socket(sock,
self.key_file,
self.cert_file,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.ca_cert,
ssl_version=libcloud.security.SSL_VERSION)
cert = self.sock.getpeercert()
try:
match_hostname(cert, self.host)
except CertificateError:
e = sys.exc_info()[1]
raise ssl.SSLError('Failed to verify hostname: %s' % (str(e)))
开发者ID:galet,项目名称:libcloud,代码行数:35,代码来源:httplib_ssl.py
示例3: connect
def connect(self, url, **options):
"""
Connect to url. url is websocket url scheme. ie. ws://host:port/resource
You can customize using 'options'.
If you set "header" dict object, you can set your own custom header.
>>> ws = WebSocket()
>>> ws.connect("ws://echo.websocket.org/",
... header={"User-Agent: MyProgram",
... "x-custom: header"})
timeout: socket timeout time. This value is integer.
if you set None for this value,
it means "use default_timeout value"
options: current support option is only "header".
if you set header as dict value,
the custom HTTP headers are added.
"""
hostname, port, resource, is_secure = _parse_url(url)
# TODO: we need to support proxy
self.sock.connect((hostname, port))
if is_secure:
if HAVE_SSL:
sslopt = dict(cert_reqs=ssl.CERT_REQUIRED,
ca_certs=os.path.join(os.path.dirname(__file__), "cacert.pem"))
sslopt.update(self.sslopt)
self.sock = ssl.wrap_socket(self.sock, **sslopt)
match_hostname(self.sock.getpeercert(), hostname)
else:
raise WebSocketException("SSL not available.")
self._handshake(hostname, port, resource, **options)
开发者ID:klamar,项目名称:websocket-client,代码行数:34,代码来源:__init__.py
示例4: connect
def connect(self):
""" Wrap socket properly. """
sock = None
source_addr = getattr(self, 'source_address', None)
timeout = getattr(self, 'timeout', DEFAULT_TIMEOUT)
makesock = getattr(socket, 'create_connection', _create_connection)
if source_addr:
# TODO: socket.create_connection doesn't support source_address
# in Python 2.6
warn(RuntimeWarning,
"No support for binding a source address, will ignore")
sock = makesock((self.host, self.port), timeout)
if (getattr(self, '_tunnel_host', None)
and hasattr(self, '_tunnel')):
self.sock = sock
self._tunnel()
# this will throw NameError if we call the function without ssl
# support
self.sock = ssl.wrap_socket(sock,
keyfile=self.key_file,
certfile=self.cert_file,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.ca_file)
if self.ca_file and self.do_match_hostname:
match_hostname(self.sock.getpeercert(), self.host)
开发者ID:unioslo,项目名称:pybofh,代码行数:29,代码来源:https.py
示例5: _on_connect
def _on_connect(self, parsed):
if self._timeout is not None:
self.io_loop.remove_timeout(self._timeout)
self._timeout = None
if self.request.request_timeout:
self._timeout = self.io_loop.add_timeout(
self.start_time + self.request.request_timeout,
self._on_timeout)
if (self.request.validate_cert and
isinstance(self.stream, SSLIOStream)):
match_hostname(self.stream.socket.getpeercert(),
parsed.hostname)
if (self.request.method not in self._SUPPORTED_METHODS and
not self.request.allow_nonstandard_methods):
raise KeyError("unknown method %s" % self.request.method)
for key in ('network_interface',
'proxy_host', 'proxy_port',
'proxy_username', 'proxy_password'):
if getattr(self.request, key, None):
raise NotImplementedError('%s not supported' % key)
if "Host" not in self.request.headers:
self.request.headers["Host"] = parsed.netloc
username, password = None, None
if parsed.username is not None:
username, password = parsed.username, parsed.password
elif self.request.auth_username is not None:
username = self.request.auth_username
password = self.request.auth_password or ''
if username is not None:
auth = utf8(username) + b(":") + utf8(password)
self.request.headers["Authorization"] = (b("Basic ") +
base64.b64encode(auth))
if self.request.user_agent:
self.request.headers["User-Agent"] = self.request.user_agent
if not self.request.allow_nonstandard_methods:
if self.request.method in ("POST", "PUT"):
assert self.request.body is not None
else:
assert self.request.body is None
if self.request.body is not None:
self.request.headers["Content-Length"] = str(len(
self.request.body))
if (self.request.method == "POST" and
"Content-Type" not in self.request.headers):
self.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
if self.request.use_gzip:
self.request.headers["Accept-Encoding"] = "gzip"
req_path = ((parsed.path or '/') +
(('?' + parsed.query) if parsed.query else ''))
request_lines = [utf8("%s %s HTTP/1.1" % (self.request.method,
req_path))]
for k, v in self.request.headers.get_all():
line = utf8(k) + b(": ") + utf8(v)
if b('\n') in line:
raise ValueError('Newline in header: ' + repr(line))
request_lines.append(line)
self.stream.write(b("\r\n").join(request_lines) + b("\r\n\r\n"))
if self.request.body is not None:
self.stream.write(self.request.body)
self.stream.read_until_regex(b("\r?\n\r?\n"), self._on_headers)
开发者ID:sun3shines,项目名称:ufs_tornado,代码行数:60,代码来源:simple_httpclient.py
示例6: cert_verify_hostname
def cert_verify_hostname(s):
# hostname verification (disabled)
from backports.ssl_match_hostname import match_hostname, CertificateError
try:
match_hostname(s.getpeercert(True), host)
print_error("hostname matches", host)
except CertificateError, ce:
print_error("hostname did not match", host)
开发者ID:AdamISZ,项目名称:electrum,代码行数:8,代码来源:interface.py
示例7: convert_to_ssl
def convert_to_ssl(self, sni=None, alpn_protos=None, **sslctx_kwargs):
"""
cert: Path to a file containing both client cert and private key.
options: A bit field consisting of OpenSSL.SSL.OP_* values
verify_options: A bit field consisting of OpenSSL.SSL.VERIFY_* values
ca_path: Path to a directory of trusted CA certificates prepared using the c_rehash tool
ca_pemfile: Path to a PEM formatted trusted CA certificate
"""
verification_mode = sslctx_kwargs.get("verify_options", None)
if verification_mode == SSL.VERIFY_PEER and not sni:
raise exceptions.TlsException("Cannot validate certificate hostname without SNI")
context = self.create_ssl_context(alpn_protos=alpn_protos, sni=sni, **sslctx_kwargs)
self.connection = SSL.Connection(context, self.connection)
if sni:
self.sni = sni
self.connection.set_tlsext_host_name(sni.encode("idna"))
self.connection.set_connect_state()
try:
self.connection.do_handshake()
except SSL.Error as v:
if self.ssl_verification_error:
raise self.ssl_verification_error
else:
raise exceptions.TlsException("SSL handshake error: %s" % repr(v))
else:
# Fix for pre v1.0 OpenSSL, which doesn't throw an exception on
# certificate validation failure
if verification_mode == SSL.VERIFY_PEER and self.ssl_verification_error:
raise self.ssl_verification_error
self.cert = certs.SSLCert(self.connection.get_peer_certificate())
# Keep all server certificates in a list
for i in self.connection.get_peer_cert_chain():
self.server_certs.append(certs.SSLCert(i))
# Validate TLS Hostname
try:
crt = dict(subjectAltName=[("DNS", x.decode("ascii", "strict")) for x in self.cert.altnames])
if self.cert.cn:
crt["subject"] = [[["commonName", self.cert.cn.decode("ascii", "strict")]]]
if sni:
hostname = sni
else:
hostname = "no-hostname"
ssl_match_hostname.match_hostname(crt, hostname)
except (ValueError, ssl_match_hostname.CertificateError) as e:
self.ssl_verification_error = exceptions.InvalidCertificateException(
"Certificate Verification Error for {}: {}".format(sni or repr(self.address), str(e))
)
if verification_mode == SSL.VERIFY_PEER:
raise self.ssl_verification_error
self.ssl_established = True
self.rfile.set_descriptor(self.connection)
self.wfile.set_descriptor(self.connection)
开发者ID:MatthewShao,项目名称:mitmproxy,代码行数:58,代码来源:tcp.py
示例8: connect
def connect(self):
httplib.HTTPConnection.connect(self)
self.sock = ssl.wrap_socket(self.sock, keyfile=self.key_file,
certfile=self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs)
if self.cert_reqs & ssl.CERT_REQUIRED:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
match_hostname(cert, hostname)
开发者ID:Nikea,项目名称:VisTrails,代码行数:10,代码来源:https.py
示例9: hostname_mismatch
def hostname_mismatch(self, ssl_sock):
"""
Check if wrong hostname is identified
get the server's certificate using getpeercert()
match_hostname should mismatch for wrong hostname
"""
try:
match_hostname(ssl_sock.getpeercert(), "www.example-wrong.com")
self.nfail += 1
logging.info('\n match_hostname failed to identify wrong hostname')
except CertificateError:
logging.info('\nIdentified mismatch in hostname')
开发者ID:CongLi,项目名称:autotest-client-tests,代码行数:12,代码来源:python_match_hostname.py
示例10: connect
def connect(self):
httplib.HTTPConnection.connect(self)
self.sock = ssl.wrap_socket(self.sock, keyfile=self.key_file,
certfile=self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs)
if self.cert_reqs & ssl.CERT_REQUIRED:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
# Fix for invalid subjectAltName in cis.porezna-uprava.hr certificate
if 'subjectAltName' in cert:
del cert['subjectAltName']
match_hostname(cert, hostname)
开发者ID:vvojvoda,项目名称:fiscal-hr-python,代码行数:13,代码来源:fiscal.py
示例11: hostname_match
def hostname_match(self, ssl_sock):
"""
Check if hostname is matching
get the server's certificate using getpeercert()
Verify the cert matches the hostname
"""
try:
match_hostname(ssl_sock.getpeercert(), "www.example.com")
except CertificateError:
logging.error('hostname doesnt match. \n')
self.nfail += 1
raise error.TestError('\nTest failed to match hostname')
开发者ID:CongLi,项目名称:autotest-client-tests,代码行数:13,代码来源:python_match_hostname.py
示例12: connect
def connect(self, host, port=None):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(self.socket_connect_timeout) # connect timeout
self.sock.connect((host, port or self.port))
self.sock.settimeout(self.socket_timeout) # regular timeout
if self.ssl_enable:
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile,
ssl_version=self.ssl_version,
ciphers=self.ssl_ciphers,
server_side=False,
cert_reqs=self.cert_required,
ca_certs=self.cacerts)
if self.validate_hostname:
try:
match_hostname(self.sock.getpeercert(), host)
except CertificateError, e:
self.log.exception("SSL hostname mismatch")
raise EppConnectionError(str(e))
开发者ID:diogovieira,项目名称:eppy,代码行数:18,代码来源:client.py
示例13: _certificate_hostname_mismatch
def _certificate_hostname_mismatch(self, certificate):
"""
Determines whether or not a given certificate matches the previously configured domain.
The ``altSubjectName`` property is checked first, taking into account the explicit and wildcard fields there.
If the ``altSubjectName`` property is not present, the ``commonName`` property of the ``subject`` field is checked.
Arguments:
* ``certificate``: A certificate object as returned by :py:meth:`~peace_of_mind.certificates.CertificateChecker.get_certificate`
Returns False or :py:const:`~peace_of_mind.certificates.ERROR_SSL_CERT_HOST_MISMATCH` if the certificate has expired.
"""
try:
match_hostname(certificate, self._domain)
except CertificateError:
return ERROR_SSL_CERT_HOST_MISMATCH
return False
开发者ID:clintecker,项目名称:python-peace-of-mind,代码行数:19,代码来源:certificates.py
示例14: connect
def connect(self):
"Connect to a host on a given (SSL) port."
if not getattr(self, 'timeout', None):
self.timeout = socket.getdefaulttimeout()
args = [(self.host, self.port), self.timeout]
if hasattr(self, 'source_address'):
args.append(self.source_address)
sock = socket.create_connection(*args)
if getattr(self, '_tunnel_host', None):
self.sock = sock
self._tunnel()
self.sock = ssl.wrap_socket(sock,
ssl_version=ssl.PROTOCOL_TLSv1,
ca_certs=CERT_FILE,
cert_reqs=ssl.CERT_REQUIRED)
try:
match_hostname(self.sock.getpeercert(), self.host)
except CertificateError:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
raise
开发者ID:4teamwork,项目名称:ftw.casauth,代码行数:24,代码来源:https.py
示例15: test_match_ip_address_failure
def test_match_ip_address_failure(self):
with pytest.raises(CertificateError):
match_hostname(self.cert, '192.168.0.25')
开发者ID:docker,项目名称:docker-py,代码行数:3,代码来源:ssladapter_test.py
示例16: _check_ssl_certificate_hostname
def _check_ssl_certificate_hostname(self):
LOGGER.info('SSL peer certificate %s', self.socket.getpeercert())
match_hostname(self.socket.getpeercert(), self.params.host)
开发者ID:lassemaatta,项目名称:pika,代码行数:3,代码来源:base_connection.py
示例17: match_hostname
sock.settimeout(5)
ssl_sock = ssl.wrap_socket(sock,
ssl_version=ssl.PROTOCOL_SSLv3,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs='/etc/pki/tls/cert.pem'
)
try:
ssl_sock.connect((args.hostname, 443))
except ssl.SSLError, error:
print args.hostname + ": Port 443 not open"
sys.exit(1)
try:
match_hostname(ssl_sock.getpeercert(), args.hostname)
except ValueError:
print args.hostname + ": Certificate not valid"
sys.exit(1)
ciphertype = ssl_sock.cipher()[1]
expires = ssl_sock.getpeercert()['notAfter']
from M2Crypto import SSL
SSL.Connection.clientPostConnectionCheck = None
ctx = SSL.Context()
conn = SSL.Connection(ctx)
conn.connect((args.hostname, 443))
cert = conn.get_peer_cert()
certinfo = cert.get_subject().as_text()
开发者ID:thedonkdonk,项目名称:admin-scripts,代码行数:31,代码来源:sslcheck.py
示例18: after_connect
def after_connect(self, sock):
super(SSLConnectionPool, self).after_connect(sock)
if not self.insecure:
match_hostname(sock.getpeercert(), self._host)
开发者ID:Avanpourm,项目名称:geventhttpclient,代码行数:4,代码来源:connectionpool.py
示例19: test_match_ip_address_success
def test_match_ip_address_success(self):
assert match_hostname(self.cert, '127.0.0.1') is None
开发者ID:docker,项目名称:docker-py,代码行数:2,代码来源:ssladapter_test.py
示例20: test_match_localhost_success
def test_match_localhost_success(self):
assert match_hostname(self.cert, 'localhost') is None
开发者ID:docker,项目名称:docker-py,代码行数:2,代码来源:ssladapter_test.py
注:本文中的backports.ssl_match_hostname.match_hostname函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论