Debian Codegraph @

tx_xmpp/server.py

raw
1 # -*- test-case-name: tx_xmpp.test.test.test_server -*-
2 #
3 # Copyright (c) Ralph Meijer.
4 # See LICENSE for details.
5
6 """
7 XMPP Server-to-Server protocol.
8
9 This module implements several aspects of XMPP server-to-server communications
10 as described in XMPP Core (RFC 3920). Refer to that document for the meaning
11 of the used terminology.
12 """
13
14 import binascii
15 from hashlib import sha256
16 import hmac
17
18 from zope.interface import implementer
19
20 from twisted.internet import defer, reactor
21 from twisted.names.srvconnect import SRVConnector
22 from twisted.python import log, randbytes
23 from twisted.words.protocols.jabber import error, ijabber, jid, xmlstream
24 from twisted.words.xish import domish
25
26 from .generic import DeferredXmlStreamFactory, XmlPipe
27
28 NS_DIALBACK = "jabber:server:dialback"
29
30
31 def generateKey(secret, receivingServer, originatingServer, streamID):
32 """
33 Generate a dialback key for server-to-server XMPP Streams.
34
35 The dialback key is generated using the algorithm described in
36 U{XEP-0185<http://xmpp.org/extensions/xep-0185.html>}. The used
37 terminology for the parameters is described in RFC-3920.
38
39 @param secret: the shared secret known to the Originating Server and
40 Authoritive Server.
41 @type secret: L{str}
42 @param receivingServer: the Receiving Server host name.
43 @type receivingServer: L{str}
44 @param originatingServer: the Originating Server host name.
45 @type originatingServer: L{str}
46 @param streamID: the Stream ID as generated by the Receiving Server.
47 @type streamID: L{str}
48 @return: hexadecimal digest of the generated key.
49 @type: L{str}
50 """
51
52 hashObject = sha256()
53 hashObject.update(secret.encode("ascii"))
54 hashedSecret = hashObject.hexdigest()
55 message = " ".join([receivingServer, originatingServer, streamID])
56 hash = hmac.HMAC(
57 hashedSecret.encode("ascii"), message.encode("ascii"), digestmod=sha256
58 )
59 return hash.hexdigest()
60
61
62 def trapStreamError(xs, observer):
63 """
64 Trap stream errors.
65
66 This wraps an observer to catch exceptions. In case of a
67 L{error.StreamError}, it is send over the given XML stream. All other
68 exceptions yield a C{'internal-server-error'} stream error, that is
69 sent over the stream, while the exception is logged.
70
71 @return: Wrapped observer
72 """
73
74 def wrappedObserver(element):
75 try:
76 observer(element)
77 except error.StreamError as exc:
78 xs.sendStreamError(exc)
79 except:
80 log.err()
81 exc = error.StreamError("internal-server-error")
82 xs.sendStreamError(exc)
83
84 return wrappedObserver
85
86
87 class XMPPServerConnector(SRVConnector):
88 def __init__(self, reactor, domain, factory):
89 SRVConnector.__init__(self, reactor, "xmpp-server", domain, factory)
90
91 def pickServer(self):
92 host, port = SRVConnector.pickServer(self)
93
94 if not self.servers and not self.orderedServers:
95 # no SRV record, fall back..
96 port = 5269
97
98 return host, port
99
100
101 class DialbackFailed(Exception):
102 pass
103
104
105 @implementer(ijabber.IInitiatingInitializer)
106 class OriginatingDialbackInitializer:
107 """
108 Server Dialback Initializer for the Orginating Server.
109 """
110
111 _deferred = None
112
113 def __init__(self, xs, thisHost, otherHost, secret):
114 self.xmlstream = xs
115 self.thisHost = thisHost
116 self.otherHost = otherHost
117 self.secret = secret
118
119 def initialize(self):
120 self._deferred = defer.Deferred()
121 self.xmlstream.addObserver(xmlstream.STREAM_ERROR_EVENT, self.onStreamError)
122 self.xmlstream.addObserver("/result[@xmlns='%s']" % NS_DIALBACK, self.onResult)
123
124 key = generateKey(self.secret, self.otherHost, self.thisHost, self.xmlstream.sid)
125
126 result = domish.Element((NS_DIALBACK, "result"))
127 result["from"] = self.thisHost
128 result["to"] = self.otherHost
129 result.addContent(key)
130
131 self.xmlstream.send(result)
132
133 return self._deferred
134
135 def onResult(self, result):
136 self.xmlstream.removeObserver(xmlstream.STREAM_ERROR_EVENT, self.onStreamError)
137 if result["type"] == "valid":
138 self.xmlstream.otherEntity = jid.internJID(self.otherHost)
139 self._deferred.callback(None)
140 else:
141 self._deferred.errback(DialbackFailed())
142
143 def onStreamError(self, failure):
144 self.xmlstream.removeObserver("/result[@xmlns='%s']" % NS_DIALBACK, self.onResult)
145 self._deferred.errback(failure)
146
147
148 @implementer(ijabber.IInitiatingInitializer)
149 class ReceivingDialbackInitializer:
150 """
151 Server Dialback Initializer for the Receiving Server.
152 """
153
154 _deferred = None
155
156 def __init__(self, xs, thisHost, otherHost, originalStreamID, key):
157 self.xmlstream = xs
158 self.thisHost = thisHost
159 self.otherHost = otherHost
160 self.originalStreamID = originalStreamID
161 self.key = key
162
163 def initialize(self):
164 self._deferred = defer.Deferred()
165 self.xmlstream.addObserver(xmlstream.STREAM_ERROR_EVENT, self.onStreamError)
166 self.xmlstream.addObserver("/verify[@xmlns='%s']" % NS_DIALBACK, self.onVerify)
167
168 verify = domish.Element((NS_DIALBACK, "verify"))
169 verify["from"] = self.thisHost
170 verify["to"] = self.otherHost
171 verify["id"] = self.originalStreamID
172 verify.addContent(self.key)
173
174 self.xmlstream.send(verify)
175 return self._deferred
176
177 def onVerify(self, verify):
178 self.xmlstream.removeObserver(xmlstream.STREAM_ERROR_EVENT, self.onStreamError)
179 if verify["id"] != self.originalStreamID:
180 self.xmlstream.sendStreamError(error.StreamError("invalid-id"))
181 self._deferred.errback(DialbackFailed())
182 elif verify["to"] != self.thisHost:
183 self.xmlstream.sendStreamError(error.StreamError("host-unknown"))
184 self._deferred.errback(DialbackFailed())
185 elif verify["from"] != self.otherHost:
186 self.xmlstream.sendStreamError(error.StreamError("invalid-from"))
187 self._deferred.errback(DialbackFailed())
188 elif verify["type"] == "valid":
189 self._deferred.callback(None)
190 else:
191 self._deferred.errback(DialbackFailed())
192
193 def onStreamError(self, failure):
194 self.xmlstream.removeObserver("/verify[@xmlns='%s']" % NS_DIALBACK, self.onVerify)
195 self._deferred.errback(failure)
196
197
198 class XMPPServerConnectAuthenticator(xmlstream.ConnectAuthenticator):
199 """
200 Authenticator for an outgoing XMPP server-to-server connection.
201
202 This authenticator connects to C{otherHost} (the Receiving Server) and then
203 initiates dialback as C{thisHost} (the Originating Server) using
204 L{OriginatingDialbackInitializer}.
205
206 @ivar thisHost: The domain this server connects from (the Originating
207 Server) .
208 @ivar otherHost: The domain of the server this server connects to (the
209 Receiving Server).
210 @ivar secret: The shared secret that is used for verifying the validity
211 of this new connection.
212 """
213
214 namespace = "jabber:server"
215
216 def __init__(self, thisHost, otherHost, secret):
217 self.thisHost = thisHost
218 self.otherHost = otherHost
219 self.secret = secret
220 xmlstream.ConnectAuthenticator.__init__(self, otherHost)
221
222 def connectionMade(self):
223 self.xmlstream.thisEntity = jid.internJID(self.thisHost)
224 self.xmlstream.prefixes = {xmlstream.NS_STREAMS: "stream", NS_DIALBACK: "db"}
225 xmlstream.ConnectAuthenticator.connectionMade(self)
226
227 def associateWithStream(self, xs):
228 xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
229 init = OriginatingDialbackInitializer(
230 xs, self.thisHost, self.otherHost, self.secret
231 )
232 xs.initializers = [init]
233
234
235 class XMPPServerVerifyAuthenticator(xmlstream.ConnectAuthenticator):
236 """
237 Authenticator for an outgoing connection to verify an incoming connection.
238
239 This authenticator connects to C{otherHost} (the Authoritative Server) and
240 then initiates dialback as C{thisHost} (the Receiving Server) using
241 L{ReceivingDialbackInitializer}.
242
243 @ivar thisHost: The domain this server connects from (the Receiving
244 Server) .
245 @ivar otherHost: The domain of the server this server connects to (the
246 Authoritative Server).
247 @ivar originalStreamID: The stream ID of the incoming connection that is
248 being verified.
249 @ivar key: The key provided by the Receving Server to be verified.
250 """
251
252 namespace = "jabber:server"
253
254 def __init__(self, thisHost, otherHost, originalStreamID, key):
255 self.thisHost = thisHost
256 self.otherHost = otherHost
257 self.originalStreamID = originalStreamID
258 self.key = key
259 xmlstream.ConnectAuthenticator.__init__(self, otherHost)
260
261 def connectionMade(self):
262 self.xmlstream.thisEntity = jid.internJID(self.thisHost)
263 self.xmlstream.prefixes = {xmlstream.NS_STREAMS: "stream", NS_DIALBACK: "db"}
264 xmlstream.ConnectAuthenticator.connectionMade(self)
265
266 def associateWithStream(self, xs):
267 xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
268 init = ReceivingDialbackInitializer(
269 xs, self.thisHost, self.otherHost, self.originalStreamID, self.key
270 )
271 xs.initializers = [init]
272
273
274 class XMPPServerListenAuthenticator(xmlstream.ListenAuthenticator):
275 """
276 Authenticator for an incoming XMPP server-to-server connection.
277
278 This authenticator handles two types of incoming connections. Regular
279 server-to-server connections are from the Originating Server to the
280 Receiving Server, where this server is the Receiving Server. These
281 connections start out by receiving a dialback key, verifying the
282 key with the Authoritative Server, and then accept normal XMPP stanzas.
283
284 The other type of connections is from a Receiving Server to an
285 Authoritative Server, where this server acts as the Authoritative Server.
286 These connections are used to verify the validity of an outgoing connection
287 from this server. In this case, this server receives a verification
288 request, checks the key and then returns the result.
289
290 @ivar service: The service that keeps the list of domains we accept
291 connections for.
292 """
293
294 namespace = "jabber:server"
295
296 def __init__(self, service):
297 xmlstream.ListenAuthenticator.__init__(self)
298 self.service = service
299
300 def streamStarted(self, rootElement):
301 xmlstream.ListenAuthenticator.streamStarted(self, rootElement)
302
303 if self.xmlstream.thisEntity:
304 targetDomain = self.xmlstream.thisEntity.host
305 else:
306 targetDomain = self.service.defaultDomain
307
308 def prepareStream(domain):
309 self.xmlstream.namespace = self.namespace
310 self.xmlstream.prefixes = {xmlstream.NS_STREAMS: "stream", NS_DIALBACK: "db"}
311 if domain:
312 self.xmlstream.thisEntity = jid.internJID(domain)
313
314 try:
315 if (
316 xmlstream.NS_STREAMS != rootElement.uri
317 or self.namespace != self.xmlstream.namespace
318 or ("db", NS_DIALBACK) not in rootElement.localPrefixes.items()
319 ):
320 raise error.StreamError("invalid-namespace")
321
322 if targetDomain and targetDomain not in self.service.domains:
323 raise error.StreamError("host-unknown")
324 except error.StreamError as exc:
325 prepareStream(self.service.defaultDomain)
326 self.xmlstream.sendStreamError(exc)
327 return
328
329 self.xmlstream.addObserver(
330 "//verify[@xmlns='%s']" % NS_DIALBACK,
331 trapStreamError(self.xmlstream, self.onVerify),
332 )
333 self.xmlstream.addObserver("//result[@xmlns='%s']" % NS_DIALBACK, self.onResult)
334
335 prepareStream(targetDomain)
336 self.xmlstream.sendHeader()
337
338 if self.xmlstream.version >= (1, 0):
339 features = domish.Element((xmlstream.NS_STREAMS, "features"))
340 self.xmlstream.send(features)
341
342 def onVerify(self, verify):
343 try:
344 receivingServer = jid.JID(verify["from"]).host
345 originatingServer = jid.JID(verify["to"]).host
346 except (KeyError, jid.InvalidFormat):
347 raise error.StreamError("improper-addressing")
348
349 if originatingServer not in self.service.domains:
350 raise error.StreamError("host-unknown")
351
352 if (
353 self.xmlstream.otherEntity
354 and receivingServer != self.xmlstream.otherEntity.host
355 ):
356 raise error.StreamError("invalid-from")
357
358 streamID = verify.getAttribute("id", "")
359 key = str(verify)
360
361 calculatedKey = generateKey(
362 self.service.secret, receivingServer, originatingServer, streamID
363 )
364 validity = (key == calculatedKey) and "valid" or "invalid"
365
366 reply = domish.Element((NS_DIALBACK, "verify"))
367 reply["from"] = originatingServer
368 reply["to"] = receivingServer
369 reply["id"] = streamID
370 reply["type"] = validity
371 self.xmlstream.send(reply)
372
373 def onResult(self, result):
374 def reply(validity):
375 reply = domish.Element((NS_DIALBACK, "result"))
376 reply["from"] = result["to"]
377 reply["to"] = result["from"]
378 reply["type"] = validity
379 self.xmlstream.send(reply)
380
381 def valid(xs):
382 reply("valid")
383 if not self.xmlstream.thisEntity:
384 self.xmlstream.thisEntity = jid.internJID(receivingServer)
385 self.xmlstream.otherEntity = jid.internJID(originatingServer)
386 self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT)
387
388 def invalid(failure):
389 log.err(failure)
390 reply("invalid")
391
392 receivingServer = result["to"]
393 originatingServer = result["from"]
394 key = str(result)
395
396 d = self.service.validateConnection(
397 receivingServer, originatingServer, self.xmlstream.sid, key
398 )
399 d.addCallbacks(valid, invalid)
400 return d
401
402
403 class DeferredS2SClientFactory(DeferredXmlStreamFactory):
404 """
405 Deferred firing factory for initiating XMPP server-to-server connection.
406
407 The deferred has its callbacks called upon succesful authentication with
408 the other server. In case of failed authentication or connection, the
409 deferred will have its errbacks called instead.
410 """
411
412 logTraffic = False
413
414 def __init__(self, authenticator):
415 DeferredXmlStreamFactory.__init__(self, authenticator)
416
417 self.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.onConnectionMade)
418
419 self.serial = 0
420
421 def onConnectionMade(self, xs):
422 xs.serial = self.serial
423 self.serial += 1
424
425 def logDataIn(buf):
426 log.msg("RECV (%d): %r" % (xs.serial, buf))
427
428 def logDataOut(buf):
429 log.msg("SEND (%d): %r" % (xs.serial, buf))
430
431 if self.logTraffic:
432 xs.rawDataInFn = logDataIn
433 xs.rawDataOutFn = logDataOut
434
435
436 def initiateS2S(factory):
437 domain = factory.authenticator.otherHost.encode("idna")
438 c = XMPPServerConnector(reactor, domain, factory)
439 c.connect()
440 return factory.deferred
441
442
443 class XMPPS2SServerFactory(xmlstream.XmlStreamServerFactory):
444 """
445 XMPP Server-to-Server Server factory.
446
447 This factory accepts XMPP server-to-server connections.
448 """
449
450 logTraffic = False
451
452 def __init__(self, service):
453 self.service = service
454
455 def authenticatorFactory():
456 return XMPPServerListenAuthenticator(service)
457
458 xmlstream.XmlStreamServerFactory.__init__(self, authenticatorFactory)
459 self.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.onConnectionMade)
460 self.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.onAuthenticated)
461
462 self.serial = 0
463
464 def onConnectionMade(self, xs):
465 """
466 Called when a server-to-server connection was made.
467
468 This enables traffic debugging on incoming streams.
469 """
470 xs.serial = self.serial
471 self.serial += 1
472
473 def logDataIn(buf):
474 log.msg("RECV (%d): %r" % (xs.serial, buf))
475
476 def logDataOut(buf):
477 log.msg("SEND (%d): %r" % (xs.serial, buf))
478
479 if self.logTraffic:
480 xs.rawDataInFn = logDataIn
481 xs.rawDataOutFn = logDataOut
482
483 xs.addObserver(xmlstream.STREAM_ERROR_EVENT, self.onError)
484
485 def onAuthenticated(self, xs):
486 thisHost = xs.thisEntity.host
487 otherHost = xs.otherEntity.host
488
489 log.msg(
490 "Incoming connection %d from %r to %r established"
491 % (xs.serial, otherHost, thisHost)
492 )
493
494 xs.addObserver(xmlstream.STREAM_END_EVENT, self.onConnectionLost, 0, xs)
495 xs.addObserver("/*", self.onElement, 0, xs)
496
497 def onConnectionLost(self, xs, reason):
498 thisHost = xs.thisEntity.host
499 otherHost = xs.otherEntity.host
500
501 log.msg(
502 "Incoming connection %d from %r to %r disconnected"
503 % (xs.serial, otherHost, thisHost)
504 )
505
506 def onError(self, reason):
507 log.err(reason, "Stream Error")
508
509 def onElement(self, xs, element):
510 """
511 Called when an element was received from one of the connected streams.
512
513 """
514 if element.handled:
515 return
516 else:
517 self.service.dispatch(xs, element)
518
519
520 class ServerService:
521 """
522 Service for managing XMPP server to server connections.
523 """
524
525 logTraffic = False
526
527 def __init__(self, router, domain=None, secret=None):
528 self.router = router
529
530 self.defaultDomain = domain
531 self.domains = set()
532 if self.defaultDomain:
533 self.domains.add(self.defaultDomain)
534
535 if secret is not None:
536 self.secret = secret
537 else:
538 self.secret = binascii.hexlify(randbytes.secureRandom(16))
539
540 self._outgoingStreams = {}
541 self._outgoingQueues = {}
542 self._outgoingConnecting = set()
543 self.serial = 0
544
545 pipe = XmlPipe()
546 self.xmlstream = pipe.source
547 self.router.addRoute(None, pipe.sink)
548 self.xmlstream.addObserver("/*", self.send)
549
550 def outgoingInitialized(self, xs):
551 thisHost = xs.thisEntity.host
552 otherHost = xs.otherEntity.host
553
554 log.msg(
555 "Outgoing connection %d from %r to %r established"
556 % (xs.serial, thisHost, otherHost)
557 )
558
559 self._outgoingStreams[thisHost, otherHost] = xs
560 xs.addObserver(
561 xmlstream.STREAM_END_EVENT, lambda _: self.outgoingDisconnected(xs)
562 )
563
564 if (thisHost, otherHost) in self._outgoingQueues:
565 for element in self._outgoingQueues[thisHost, otherHost]:
566 xs.send(element)
567 del self._outgoingQueues[thisHost, otherHost]
568
569 def outgoingDisconnected(self, xs):
570 thisHost = xs.thisEntity.host
571 otherHost = xs.otherEntity.host
572
573 log.msg(
574 "Outgoing connection %d from %r to %r disconnected"
575 % (xs.serial, thisHost, otherHost)
576 )
577
578 del self._outgoingStreams[thisHost, otherHost]
579
580 def initiateOutgoingStream(self, thisHost, otherHost):
581 """
582 Initiate an outgoing XMPP server-to-server connection.
583 """
584
585 def resetConnecting(_):
586 self._outgoingConnecting.remove((thisHost, otherHost))
587
588 if (thisHost, otherHost) in self._outgoingConnecting:
589 return
590
591 authenticator = XMPPServerConnectAuthenticator(thisHost, otherHost, self.secret)
592 factory = DeferredS2SClientFactory(authenticator)
593 factory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.outgoingInitialized)
594 factory.logTraffic = self.logTraffic
595
596 self._outgoingConnecting.add((thisHost, otherHost))
597
598 d = initiateS2S(factory)
599 d.addBoth(resetConnecting)
600 return d
601
602 def validateConnection(self, thisHost, otherHost, sid, key):
603 """
604 Validate an incoming XMPP server-to-server connection.
605 """
606
607 def connected(xs):
608 # Set up stream for immediate disconnection.
609 def disconnect(_):
610 xs.transport.loseConnection()
611
612 xs.addObserver(xmlstream.STREAM_AUTHD_EVENT, disconnect)
613 xs.addObserver(xmlstream.INIT_FAILED_EVENT, disconnect)
614
615 authenticator = XMPPServerVerifyAuthenticator(thisHost, otherHost, sid, key)
616 factory = DeferredS2SClientFactory(authenticator)
617 factory.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, connected)
618 factory.logTraffic = self.logTraffic
619
620 d = initiateS2S(factory)
621 return d
622
623 def send(self, stanza):
624 """
625 Send stanza to the proper XML Stream.
626
627 This uses addressing embedded in the stanza to find the correct stream
628 to forward the stanza to.
629 """
630
631 otherHost = jid.internJID(stanza["to"]).host
632 thisHost = jid.internJID(stanza["from"]).host
633
634 if (thisHost, otherHost) not in self._outgoingStreams:
635 # There is no connection with the destination (yet). Cache the
636 # outgoing stanza until the connection has been established.
637 # XXX: If the connection cannot be established, the queue should
638 # be emptied at some point.
639 if (thisHost, otherHost) not in self._outgoingQueues:
640 self._outgoingQueues[(thisHost, otherHost)] = []
641 self._outgoingQueues[(thisHost, otherHost)].append(stanza)
642 self.initiateOutgoingStream(thisHost, otherHost)
643 else:
644 self._outgoingStreams[(thisHost, otherHost)].send(stanza)
645
646 def dispatch(self, xs, stanza):
647 """
648 Send on element to be routed within the server.
649 """
650 stanzaFrom = stanza.getAttribute("from")
651 stanzaTo = stanza.getAttribute("to")
652
653 if not stanzaFrom or not stanzaTo:
654 xs.sendStreamError(error.StreamError("improper-addressing"))
655 else:
656 try:
657 sender = jid.internJID(stanzaFrom)
658 jid.internJID(stanzaTo)
659 except jid.InvalidFormat:
660 log.msg("Dropping error stanza with malformed JID")
661
662 if sender.host != xs.otherEntity.host:
663 xs.sendStreamError(error.StreamError("invalid-from"))
664 else:
665 self.xmlstream.send(stanza)