本文整理汇总了Python中backports.ssl_match_hostname.match_hostname函数的典型用法代码示例。如果您正苦于以下问题:Python match_hostname函数的具体用法?Python match_hostname怎么用?Python match_hostname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了match_hostname函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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])
示例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)))
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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')
示例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)
示例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')
示例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))
示例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
示例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
示例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')