Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_implementation.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. """The match_hostname() function from Python 3.3.3, essential when using SSL."""
  2. # Note: This file is under the PSF license as the code comes from the python
  3. # stdlib. http://docs.python.org/3/license.html
  4. import re
  5. import sys
  6. # ipaddress has been backported to 2.6+ in pypi. If it is installed on the
  7. # system, use it to handle IPAddress ServerAltnames (this was added in
  8. # python-3.5) otherwise only do DNS matching. This allows
  9. # backports.ssl_match_hostname to continue to be used all the way back to
  10. # python-2.4.
  11. try:
  12. from pip._vendor import ipaddress
  13. except ImportError:
  14. ipaddress = None
  15. __version__ = '3.5.0.1'
  16. class CertificateError(ValueError):
  17. pass
  18. def _dnsname_match(dn, hostname, max_wildcards=1):
  19. """Matching according to RFC 6125, section 6.4.3
  20. http://tools.ietf.org/html/rfc6125#section-6.4.3
  21. """
  22. pats = []
  23. if not dn:
  24. return False
  25. # Ported from python3-syntax:
  26. # leftmost, *remainder = dn.split(r'.')
  27. parts = dn.split(r'.')
  28. leftmost = parts[0]
  29. remainder = parts[1:]
  30. wildcards = leftmost.count('*')
  31. if wildcards > max_wildcards:
  32. # Issue #17980: avoid denials of service by refusing more
  33. # than one wildcard per fragment. A survey of established
  34. # policy among SSL implementations showed it to be a
  35. # reasonable choice.
  36. raise CertificateError(
  37. "too many wildcards in certificate DNS name: " + repr(dn))
  38. # speed up common case w/o wildcards
  39. if not wildcards:
  40. return dn.lower() == hostname.lower()
  41. # RFC 6125, section 6.4.3, subitem 1.
  42. # The client SHOULD NOT attempt to match a presented identifier in which
  43. # the wildcard character comprises a label other than the left-most label.
  44. if leftmost == '*':
  45. # When '*' is a fragment by itself, it matches a non-empty dotless
  46. # fragment.
  47. pats.append('[^.]+')
  48. elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
  49. # RFC 6125, section 6.4.3, subitem 3.
  50. # The client SHOULD NOT attempt to match a presented identifier
  51. # where the wildcard character is embedded within an A-label or
  52. # U-label of an internationalized domain name.
  53. pats.append(re.escape(leftmost))
  54. else:
  55. # Otherwise, '*' matches any dotless string, e.g. www*
  56. pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
  57. # add the remaining fragments, ignore any wildcards
  58. for frag in remainder:
  59. pats.append(re.escape(frag))
  60. pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
  61. return pat.match(hostname)
  62. def _to_unicode(obj):
  63. if isinstance(obj, str) and sys.version_info < (3,):
  64. obj = unicode(obj, encoding='ascii', errors='strict')
  65. return obj
  66. def _ipaddress_match(ipname, host_ip):
  67. """Exact matching of IP addresses.
  68. RFC 6125 explicitly doesn't define an algorithm for this
  69. (section 1.7.2 - "Out of Scope").
  70. """
  71. # OpenSSL may add a trailing newline to a subjectAltName's IP address
  72. # Divergence from upstream: ipaddress can't handle byte str
  73. ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())
  74. return ip == host_ip
  75. def match_hostname(cert, hostname):
  76. """Verify that *cert* (in decoded format as returned by
  77. SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
  78. rules are followed, but IP addresses are not accepted for *hostname*.
  79. CertificateError is raised on failure. On success, the function
  80. returns nothing.
  81. """
  82. if not cert:
  83. raise ValueError("empty or no certificate, match_hostname needs a "
  84. "SSL socket or SSL context with either "
  85. "CERT_OPTIONAL or CERT_REQUIRED")
  86. try:
  87. # Divergence from upstream: ipaddress can't handle byte str
  88. host_ip = ipaddress.ip_address(_to_unicode(hostname))
  89. except ValueError:
  90. # Not an IP address (common case)
  91. host_ip = None
  92. except UnicodeError:
  93. # Divergence from upstream: Have to deal with ipaddress not taking
  94. # byte strings. addresses should be all ascii, so we consider it not
  95. # an ipaddress in this case
  96. host_ip = None
  97. except AttributeError:
  98. # Divergence from upstream: Make ipaddress library optional
  99. if ipaddress is None:
  100. host_ip = None
  101. else:
  102. raise
  103. dnsnames = []
  104. san = cert.get('subjectAltName', ())
  105. for key, value in san:
  106. if key == 'DNS':
  107. if host_ip is None and _dnsname_match(value, hostname):
  108. return
  109. dnsnames.append(value)
  110. elif key == 'IP Address':
  111. if host_ip is not None and _ipaddress_match(value, host_ip):
  112. return
  113. dnsnames.append(value)
  114. if not dnsnames:
  115. # The subject is only checked when there is no dNSName entry
  116. # in subjectAltName
  117. for sub in cert.get('subject', ()):
  118. for key, value in sub:
  119. # XXX according to RFC 2818, the most specific Common Name
  120. # must be used.
  121. if key == 'commonName':
  122. if _dnsname_match(value, hostname):
  123. return
  124. dnsnames.append(value)
  125. if len(dnsnames) > 1:
  126. raise CertificateError("hostname %r "
  127. "doesn't match either of %s"
  128. % (hostname, ', '.join(map(repr, dnsnames))))
  129. elif len(dnsnames) == 1:
  130. raise CertificateError("hostname %r "
  131. "doesn't match %r"
  132. % (hostname, dnsnames[0]))
  133. else:
  134. raise CertificateError("no appropriate commonName or "
  135. "subjectAltName fields were found")