ssl_peer_verification.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. """ndg_httpsclient - module containing SSL peer verification class.
  2. """
  3. __author__ = "P J Kershaw (STFC)"
  4. __date__ = "09/12/11"
  5. __copyright__ = "(C) 2012 Science and Technology Facilities Council"
  6. __license__ = "BSD - see LICENSE file in top-level directory"
  7. __contact__ = "Philip.Kershaw@stfc.ac.uk"
  8. __revision__ = '$Id$'
  9. import re
  10. import logging
  11. log = logging.getLogger(__name__)
  12. try:
  13. from ndg.httpsclient.subj_alt_name import SubjectAltName
  14. from pyasn1.codec.der import decoder as der_decoder
  15. subj_alt_name_support = True
  16. except ImportError, e:
  17. subj_alt_name_support = False
  18. class ServerSSLCertVerification(object):
  19. """Check server identity. If hostname doesn't match, allow match of
  20. host's Distinguished Name against server DN setting"""
  21. DN_LUT = {
  22. 'commonName': 'CN',
  23. 'organisationalUnitName': 'OU',
  24. 'organisation': 'O',
  25. 'countryName': 'C',
  26. 'emailAddress': 'EMAILADDRESS',
  27. 'localityName': 'L',
  28. 'stateOrProvinceName': 'ST',
  29. 'streetAddress': 'STREET',
  30. 'domainComponent': 'DC',
  31. 'userid': 'UID'
  32. }
  33. SUBJ_ALT_NAME_EXT_NAME = 'subjectAltName'
  34. PARSER_RE_STR = '/(%s)=' % '|'.join(DN_LUT.keys() + DN_LUT.values())
  35. PARSER_RE = re.compile(PARSER_RE_STR)
  36. __slots__ = ('__hostname', '__certDN', '__subj_alt_name_match')
  37. def __init__(self, certDN=None, hostname=None, subj_alt_name_match=True):
  38. """Override parent class __init__ to enable setting of certDN
  39. setting
  40. @type certDN: string
  41. @param certDN: Set the expected Distinguished Name of the
  42. server to avoid errors matching hostnames. This is useful
  43. where the hostname is not fully qualified
  44. @type hostname: string
  45. @param hostname: hostname to match against peer certificate
  46. subjectAltNames or subject common name
  47. @type subj_alt_name_match: bool
  48. @param subj_alt_name_match: flag to enable/disable matching of hostname
  49. against peer certificate subjectAltNames. Nb. A setting of True will
  50. be ignored if the pyasn1 package is not installed
  51. """
  52. self.__certDN = None
  53. self.__hostname = None
  54. if certDN is not None:
  55. self.certDN = certDN
  56. if hostname is not None:
  57. self.hostname = hostname
  58. if subj_alt_name_match:
  59. if not subj_alt_name_support:
  60. log.warning('Overriding "subj_alt_name_match" keyword setting: '
  61. 'peer verification with subjectAltNames is disabled')
  62. self.__subj_alt_name_match = False
  63. self.__subj_alt_name_match = True
  64. else:
  65. log.debug('Disabling peer verification with subject '
  66. 'subjectAltNames!')
  67. self.__subj_alt_name_match = False
  68. def __call__(self, connection, peerCert, errorStatus, errorDepth,
  69. preverifyOK):
  70. """Verify server certificate
  71. @type connection: OpenSSL.SSL.Connection
  72. @param connection: SSL connection object
  73. @type peerCert: basestring
  74. @param peerCert: server host certificate as OpenSSL.crypto.X509
  75. instance
  76. @type errorStatus: int
  77. @param errorStatus: error status passed from caller. This is the value
  78. returned by the OpenSSL C function X509_STORE_CTX_get_error(). Look-up
  79. x509_vfy.h in the OpenSSL source to get the meanings of the different
  80. codes. PyOpenSSL doesn't help you!
  81. @type errorDepth: int
  82. @param errorDepth: a non-negative integer representing where in the
  83. certificate chain the error occurred. If it is zero it occured in the
  84. end entity certificate, one if it is the certificate which signed the
  85. end entity certificate and so on.
  86. @type preverifyOK: int
  87. @param preverifyOK: the error status - 0 = Error, 1 = OK of the current
  88. SSL context irrespective of any verification checks done here. If this
  89. function yields an OK status, it should enforce the preverifyOK value
  90. so that any error set upstream overrides and is honoured.
  91. @rtype: int
  92. @return: status code - 0/False = Error, 1/True = OK
  93. """
  94. if peerCert.has_expired():
  95. # Any expired certificate in the chain should result in an error
  96. log.error('Certificate %r in peer certificate chain has expired',
  97. peerCert.get_subject())
  98. return False
  99. elif errorDepth == 0:
  100. # Only interested in DN of last certificate in the chain - this must
  101. # match the expected Server DN setting
  102. peerCertSubj = peerCert.get_subject()
  103. peerCertDN = peerCertSubj.get_components()
  104. peerCertDN.sort()
  105. if self.certDN is None:
  106. # Check hostname against peer certificate CN field instead:
  107. if self.hostname is None:
  108. log.error('No "hostname" or "certDN" set to check peer '
  109. 'certificate against')
  110. return False
  111. # Check for subject alternative names
  112. if self.__subj_alt_name_match:
  113. dns_names = self._get_subj_alt_name(peerCert)
  114. if self.hostname in dns_names:
  115. return preverifyOK
  116. # If no subjectAltNames, default to check of subject Common Name
  117. if peerCertSubj.commonName == self.hostname:
  118. return preverifyOK
  119. else:
  120. log.error('Peer certificate CN %r doesn\'t match the '
  121. 'expected CN %r', peerCertSubj.commonName,
  122. self.hostname)
  123. return False
  124. else:
  125. if peerCertDN == self.certDN:
  126. return preverifyOK
  127. else:
  128. log.error('Peer certificate DN %r doesn\'t match the '
  129. 'expected DN %r', peerCertDN, self.certDN)
  130. return False
  131. else:
  132. return preverifyOK
  133. @classmethod
  134. def _get_subj_alt_name(cls, peer_cert):
  135. '''Extract subjectAltName DNS name settings from certificate extensions
  136. @param peer_cert: peer certificate in SSL connection. subjectAltName
  137. settings if any will be extracted from this
  138. @type peer_cert: OpenSSL.crypto.X509
  139. '''
  140. # Search through extensions
  141. dns_name = []
  142. general_names = SubjectAltName()
  143. for i in range(peer_cert.get_extension_count()):
  144. ext = peer_cert.get_extension(i)
  145. ext_name = ext.get_short_name()
  146. if ext_name == cls.SUBJ_ALT_NAME_EXT_NAME:
  147. # PyOpenSSL returns extension data in ASN.1 encoded form
  148. ext_dat = ext.get_data()
  149. decoded_dat = der_decoder.decode(ext_dat,
  150. asn1Spec=general_names)
  151. for name in decoded_dat:
  152. if isinstance(name, SubjectAltName):
  153. for entry in range(len(name)):
  154. component = name.getComponentByPosition(entry)
  155. dns_name.append(str(component.getComponent()))
  156. return dns_name
  157. def _getCertDN(self):
  158. return self.__certDN
  159. def _setCertDN(self, val):
  160. if isinstance(val, basestring):
  161. # Allow for quoted DN
  162. certDN = val.strip('"')
  163. dnFields = self.__class__.PARSER_RE.split(certDN)
  164. if len(dnFields) < 2:
  165. raise TypeError('Error parsing DN string: "%s"' % certDN)
  166. self.__certDN = zip(dnFields[1::2], dnFields[2::2])
  167. self.__certDN.sort()
  168. elif not isinstance(val, list):
  169. for i in val:
  170. if not len(i) == 2:
  171. raise TypeError('Expecting list of two element DN field, '
  172. 'DN field value pairs for "certDN" '
  173. 'attribute')
  174. self.__certDN = val
  175. else:
  176. raise TypeError('Expecting list or string type for "certDN" '
  177. 'attribute')
  178. certDN = property(fget=_getCertDN,
  179. fset=_setCertDN,
  180. doc="Distinguished Name for Server Certificate")
  181. # Get/Set Property methods
  182. def _getHostname(self):
  183. return self.__hostname
  184. def _setHostname(self, val):
  185. if not isinstance(val, basestring):
  186. raise TypeError("Expecting string type for hostname "
  187. "attribute")
  188. self.__hostname = val
  189. hostname = property(fget=_getHostname,
  190. fset=_setHostname,
  191. doc="hostname of server")