sasl.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. XMPP-specific SASL profile.
  5. """
  6. import re
  7. from base64 import b64decode, b64encode
  8. from twisted.internet import defer
  9. from twisted.words.protocols.jabber import sasl_mechanisms, xmlstream
  10. from twisted.words.xish import domish
  11. NS_XMPP_SASL = "urn:ietf:params:xml:ns:xmpp-sasl"
  12. def get_mechanisms(xs):
  13. """
  14. Parse the SASL feature to extract the available mechanism names.
  15. """
  16. mechanisms = []
  17. for element in xs.features[(NS_XMPP_SASL, "mechanisms")].elements():
  18. if element.name == "mechanism":
  19. mechanisms.append(str(element))
  20. return mechanisms
  21. class SASLError(Exception):
  22. """
  23. SASL base exception.
  24. """
  25. class SASLNoAcceptableMechanism(SASLError):
  26. """
  27. The server did not present an acceptable SASL mechanism.
  28. """
  29. class SASLAuthError(SASLError):
  30. """
  31. SASL Authentication failed.
  32. """
  33. def __init__(self, condition=None):
  34. self.condition = condition
  35. def __str__(self) -> str:
  36. return "SASLAuthError with condition %r" % self.condition
  37. class SASLIncorrectEncodingError(SASLError):
  38. """
  39. SASL base64 encoding was incorrect.
  40. RFC 3920 specifies that any characters not in the base64 alphabet
  41. and padding characters present elsewhere than at the end of the string
  42. MUST be rejected. See also L{fromBase64}.
  43. This exception is raised whenever the encoded string does not adhere
  44. to these additional restrictions or when the decoding itself fails.
  45. The recommended behaviour for so-called receiving entities (like servers in
  46. client-to-server connections, see RFC 3920 for terminology) is to fail the
  47. SASL negotiation with a C{'incorrect-encoding'} condition. For initiating
  48. entities, one should assume the receiving entity to be either buggy or
  49. malevolent. The stream should be terminated and reconnecting is not
  50. advised.
  51. """
  52. base64Pattern = re.compile("^[0-9A-Za-z+/]*[0-9A-Za-z+/=]{,2}$")
  53. def fromBase64(s):
  54. """
  55. Decode base64 encoded string.
  56. This helper performs regular decoding of a base64 encoded string, but also
  57. rejects any characters that are not in the base64 alphabet and padding
  58. occurring elsewhere from the last or last two characters, as specified in
  59. section 14.9 of RFC 3920. This safeguards against various attack vectors
  60. among which the creation of a covert channel that "leaks" information.
  61. """
  62. if base64Pattern.match(s) is None:
  63. raise SASLIncorrectEncodingError()
  64. try:
  65. return b64decode(s)
  66. except Exception as e:
  67. raise SASLIncorrectEncodingError(str(e))
  68. class SASLInitiatingInitializer(xmlstream.BaseFeatureInitiatingInitializer):
  69. """
  70. Stream initializer that performs SASL authentication.
  71. The supported mechanisms by this initializer are C{DIGEST-MD5}, C{PLAIN}
  72. and C{ANONYMOUS}. The C{ANONYMOUS} SASL mechanism is used when the JID, set
  73. on the authenticator, does not have a localpart (username), requesting an
  74. anonymous session where the username is generated by the server.
  75. Otherwise, C{DIGEST-MD5} and C{PLAIN} are attempted, in that order.
  76. """
  77. feature = (NS_XMPP_SASL, "mechanisms")
  78. _deferred = None
  79. def setMechanism(self):
  80. """
  81. Select and setup authentication mechanism.
  82. Uses the authenticator's C{jid} and C{password} attribute for the
  83. authentication credentials. If no supported SASL mechanisms are
  84. advertized by the receiving party, a failing deferred is returned with
  85. a L{SASLNoAcceptableMechanism} exception.
  86. """
  87. jid = self.xmlstream.authenticator.jid
  88. password = self.xmlstream.authenticator.password
  89. mechanisms = get_mechanisms(self.xmlstream)
  90. if jid.user is not None:
  91. if "DIGEST-MD5" in mechanisms:
  92. self.mechanism = sasl_mechanisms.DigestMD5(
  93. "xmpp", jid.host, None, jid.user, password
  94. )
  95. elif "PLAIN" in mechanisms:
  96. self.mechanism = sasl_mechanisms.Plain(None, jid.user, password)
  97. else:
  98. raise SASLNoAcceptableMechanism()
  99. else:
  100. if "ANONYMOUS" in mechanisms:
  101. self.mechanism = sasl_mechanisms.Anonymous()
  102. else:
  103. raise SASLNoAcceptableMechanism()
  104. def start(self):
  105. """
  106. Start SASL authentication exchange.
  107. """
  108. self.setMechanism()
  109. self._deferred = defer.Deferred()
  110. self.xmlstream.addObserver("/challenge", self.onChallenge)
  111. self.xmlstream.addOnetimeObserver("/success", self.onSuccess)
  112. self.xmlstream.addOnetimeObserver("/failure", self.onFailure)
  113. self.sendAuth(self.mechanism.getInitialResponse())
  114. return self._deferred
  115. def sendAuth(self, data=None):
  116. """
  117. Initiate authentication protocol exchange.
  118. If an initial client response is given in C{data}, it will be
  119. sent along.
  120. @param data: initial client response.
  121. @type data: C{str} or L{None}.
  122. """
  123. auth = domish.Element((NS_XMPP_SASL, "auth"))
  124. auth["mechanism"] = self.mechanism.name
  125. if data is not None:
  126. auth.addContent(b64encode(data).decode("ascii") or "=")
  127. self.xmlstream.send(auth)
  128. def sendResponse(self, data=b""):
  129. """
  130. Send response to a challenge.
  131. @param data: client response.
  132. @type data: L{bytes}.
  133. """
  134. response = domish.Element((NS_XMPP_SASL, "response"))
  135. if data:
  136. response.addContent(b64encode(data).decode("ascii"))
  137. self.xmlstream.send(response)
  138. def onChallenge(self, element):
  139. """
  140. Parse challenge and send response from the mechanism.
  141. @param element: the challenge protocol element.
  142. @type element: L{domish.Element}.
  143. """
  144. try:
  145. challenge = fromBase64(str(element))
  146. except SASLIncorrectEncodingError:
  147. self._deferred.errback()
  148. else:
  149. self.sendResponse(self.mechanism.getResponse(challenge))
  150. def onSuccess(self, success):
  151. """
  152. Clean up observers, reset the XML stream and send a new header.
  153. @param success: the success protocol element. For now unused, but
  154. could hold additional data.
  155. @type success: L{domish.Element}
  156. """
  157. self.xmlstream.removeObserver("/challenge", self.onChallenge)
  158. self.xmlstream.removeObserver("/failure", self.onFailure)
  159. self.xmlstream.reset()
  160. self.xmlstream.sendHeader()
  161. self._deferred.callback(xmlstream.Reset)
  162. def onFailure(self, failure):
  163. """
  164. Clean up observers, parse the failure and errback the deferred.
  165. @param failure: the failure protocol element. Holds details on
  166. the error condition.
  167. @type failure: L{domish.Element}
  168. """
  169. self.xmlstream.removeObserver("/challenge", self.onChallenge)
  170. self.xmlstream.removeObserver("/success", self.onSuccess)
  171. try:
  172. condition = failure.firstChildElement().name
  173. except AttributeError:
  174. condition = None
  175. self._deferred.errback(SASLAuthError(condition))