ssl_peer_verification.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """
  2. """
  3. __author__ = "P J Kershaw"
  4. __date__ = "02/06/05"
  5. __copyright__ = "(C) 2010 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: client.py 7928 2011-08-12 13:16:26Z pjkersha $'
  9. import logging
  10. log = logging.getLogger(__name__)
  11. import re
  12. class ServerSSLCertVerification(object):
  13. """Check server identity. If hostname doesn't match, allow match of
  14. host's Distinguished Name against server DN setting"""
  15. DN_LUT = {
  16. 'commonName': 'CN',
  17. 'organisationalUnitName': 'OU',
  18. 'organisation': 'O',
  19. 'countryName': 'C',
  20. 'emailAddress': 'EMAILADDRESS',
  21. 'localityName': 'L',
  22. 'stateOrProvinceName': 'ST',
  23. 'streetAddress': 'STREET',
  24. 'domainComponent': 'DC',
  25. 'userid': 'UID'
  26. }
  27. PARSER_RE_STR = '/(%s)=' % '|'.join(DN_LUT.keys() + DN_LUT.values())
  28. PARSER_RE = re.compile(PARSER_RE_STR)
  29. __slots__ = ('__hostname', '__certDN')
  30. def __init__(self, certDN=None, hostname=None):
  31. """Override parent class __init__ to enable setting of certDN
  32. setting
  33. @type certDN: string
  34. @param certDN: Set the expected Distinguished Name of the
  35. server to avoid errors matching hostnames. This is useful
  36. where the hostname is not fully qualified
  37. """
  38. self.__certDN = None
  39. self.__hostname = None
  40. if certDN is not None:
  41. self.certDN = certDN
  42. if hostname is not None:
  43. self.hostname = hostname
  44. def __call__(self, connection, peerCert, errorStatus, errorDepth,
  45. preverifyOK):
  46. """Verify server certificate
  47. @type connection: OpenSSL.SSL.Connection
  48. @param connection: SSL connection object
  49. @type peerCert: basestring
  50. @param peerCert: server host certificate as OpenSSL.crypto.X509
  51. instance
  52. @type errorStatus: int
  53. @param errorStatus: error status passed from caller. This is the value
  54. returned by the OpenSSL C function X509_STORE_CTX_get_error(). Look-up
  55. x509_vfy.h in the OpenSSL source to get the meanings of the different
  56. codes. PyOpenSSL doesn't help you!
  57. @type errorDepth: int
  58. @param errorDepth: a non-negative integer representing where in the
  59. certificate chain the error occurred. If it is zero it occured in the
  60. end entity certificate, one if it is the certificate which signed the
  61. end entity certificate and so on.
  62. @type preverifyOK: int
  63. @param preverifyOK: the error status - 0 = Error, 1 = OK of the current
  64. SSL context irrespective of any verification checks done here. If this
  65. function yields an OK status, it should enforce the preverifyOK value
  66. so that any error set upstream overrides and is honoured.
  67. @rtype: int
  68. @return: status code - 0/False = Error, 1/True = OK
  69. """
  70. if peerCert.has_expired():
  71. # Any expired certificate in the chain should result in an error
  72. log.error('Certificate %r in peer certificate chain has expired',
  73. peerCert.get_subject())
  74. return False
  75. elif errorDepth == 0:
  76. # Only interested in DN of last certificate in the chain - this must
  77. # match the expected Server DN setting
  78. peerCertSubj = peerCert.get_subject()
  79. peerCertDN = peerCertSubj.get_components()
  80. peerCertDN.sort()
  81. if self.certDN is None:
  82. # Check hostname against peer certificate CN field instead:
  83. if self.hostname is None:
  84. log.error('No "hostname" or "certDN" set to check peer '
  85. 'certificate against')
  86. return False
  87. acceptableCNs = [pfx + self.hostname
  88. for pfx in self.serverCNPrefixes]
  89. if peerCertSubj.commonName in acceptableCNs:
  90. return preverifyOK
  91. else:
  92. log.error('Peer certificate CN %r doesn\'t match the '
  93. 'expected CN %r', peerCertSubj.commonName,
  94. acceptableCNs)
  95. return False
  96. else:
  97. if peerCertDN == self.certDN:
  98. return preverifyOK
  99. else:
  100. log.error('Peer certificate DN %r doesn\'t match the '
  101. 'expected DN %r', peerCertDN, self.certDN)
  102. return False
  103. else:
  104. return preverifyOK
  105. def _getCertDN(self):
  106. return self.__certDN
  107. def _setCertDN(self, val):
  108. if isinstance(val, basestring):
  109. # Allow for quoted DN
  110. certDN = val.strip('"')
  111. dnFields = self.__class__.PARSER_RE.split(certDN)
  112. if len(dnFields) < 2:
  113. raise TypeError('Error parsing DN string: "%s"' % certDN)
  114. self.__certDN = zip(dnFields[1::2], dnFields[2::2])
  115. self.__certDN.sort()
  116. elif not isinstance(val, list):
  117. for i in val:
  118. if not len(i) == 2:
  119. raise TypeError('Expecting list of two element DN field, '
  120. 'DN field value pairs for "certDN" '
  121. 'attribute')
  122. self.__certDN = val
  123. else:
  124. raise TypeError('Expecting list or string type for "certDN" '
  125. 'attribute')
  126. certDN = property(fget=_getCertDN,
  127. fset=_setCertDN,
  128. doc="Distinguished Name for Server Certificate")
  129. # Get/Set Property methods
  130. def _getHostname(self):
  131. return self.__hostname
  132. def _setHostname(self, val):
  133. if not isinstance(val, basestring):
  134. raise TypeError("Expecting string type for hostname "
  135. "attribute")
  136. self.__hostname = val
  137. hostname = property(fget=_getHostname,
  138. fset=_setHostname,
  139. doc="hostname of server")