ident.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # -*- test-case-name: twisted.test.test_ident -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Ident protocol implementation.
  6. """
  7. import struct
  8. from twisted.internet import defer
  9. from twisted.protocols import basic
  10. from twisted.python import log, failure
  11. _MIN_PORT = 1
  12. _MAX_PORT = 2 ** 16 - 1
  13. class IdentError(Exception):
  14. """
  15. Can't determine connection owner; reason unknown.
  16. """
  17. identDescription = 'UNKNOWN-ERROR'
  18. def __str__(self):
  19. return self.identDescription
  20. class NoUser(IdentError):
  21. """
  22. The connection specified by the port pair is not currently in use or
  23. currently not owned by an identifiable entity.
  24. """
  25. identDescription = 'NO-USER'
  26. class InvalidPort(IdentError):
  27. """
  28. Either the local or foreign port was improperly specified. This should
  29. be returned if either or both of the port ids were out of range (TCP
  30. port numbers are from 1-65535), negative integers, reals or in any
  31. fashion not recognized as a non-negative integer.
  32. """
  33. identDescription = 'INVALID-PORT'
  34. class HiddenUser(IdentError):
  35. """
  36. The server was able to identify the user of this port, but the
  37. information was not returned at the request of the user.
  38. """
  39. identDescription = 'HIDDEN-USER'
  40. class IdentServer(basic.LineOnlyReceiver):
  41. """
  42. The Identification Protocol (a.k.a., "ident", a.k.a., "the Ident
  43. Protocol") provides a means to determine the identity of a user of a
  44. particular TCP connection. Given a TCP port number pair, it returns a
  45. character string which identifies the owner of that connection on the
  46. server's system.
  47. Server authors should subclass this class and override the lookup method.
  48. The default implementation returns an UNKNOWN-ERROR response for every
  49. query.
  50. """
  51. def lineReceived(self, line):
  52. parts = line.split(',')
  53. if len(parts) != 2:
  54. self.invalidQuery()
  55. else:
  56. try:
  57. portOnServer, portOnClient = map(int, parts)
  58. except ValueError:
  59. self.invalidQuery()
  60. else:
  61. if _MIN_PORT <= portOnServer <= _MAX_PORT and _MIN_PORT <= portOnClient <= _MAX_PORT:
  62. self.validQuery(portOnServer, portOnClient)
  63. else:
  64. self._ebLookup(failure.Failure(InvalidPort()), portOnServer, portOnClient)
  65. def invalidQuery(self):
  66. self.transport.loseConnection()
  67. def validQuery(self, portOnServer, portOnClient):
  68. """
  69. Called when a valid query is received to look up and deliver the
  70. response.
  71. @param portOnServer: The server port from the query.
  72. @param portOnClient: The client port from the query.
  73. """
  74. serverAddr = self.transport.getHost().host, portOnServer
  75. clientAddr = self.transport.getPeer().host, portOnClient
  76. defer.maybeDeferred(self.lookup, serverAddr, clientAddr
  77. ).addCallback(self._cbLookup, portOnServer, portOnClient
  78. ).addErrback(self._ebLookup, portOnServer, portOnClient
  79. )
  80. def _cbLookup(self, result, sport, cport):
  81. (sysName, userId) = result
  82. self.sendLine('%d, %d : USERID : %s : %s' % (sport, cport, sysName, userId))
  83. def _ebLookup(self, failure, sport, cport):
  84. if failure.check(IdentError):
  85. self.sendLine('%d, %d : ERROR : %s' % (sport, cport, failure.value))
  86. else:
  87. log.err(failure)
  88. self.sendLine('%d, %d : ERROR : %s' % (sport, cport, IdentError(failure.value)))
  89. def lookup(self, serverAddress, clientAddress):
  90. """
  91. Lookup user information about the specified address pair.
  92. Return value should be a two-tuple of system name and username.
  93. Acceptable values for the system name may be found online at::
  94. U{http://www.iana.org/assignments/operating-system-names}
  95. This method may also raise any IdentError subclass (or IdentError
  96. itself) to indicate user information will not be provided for the
  97. given query.
  98. A Deferred may also be returned.
  99. @param serverAddress: A two-tuple representing the server endpoint
  100. of the address being queried. The first element is a string holding
  101. a dotted-quad IP address. The second element is an integer
  102. representing the port.
  103. @param clientAddress: Like I{serverAddress}, but represents the
  104. client endpoint of the address being queried.
  105. """
  106. raise IdentError()
  107. class ProcServerMixin:
  108. """Implements lookup() to grab entries for responses from /proc/net/tcp
  109. """
  110. SYSTEM_NAME = 'LINUX'
  111. try:
  112. from pwd import getpwuid
  113. def getUsername(self, uid, getpwuid=getpwuid):
  114. return getpwuid(uid)[0]
  115. del getpwuid
  116. except ImportError:
  117. def getUsername(self, uid):
  118. raise IdentError()
  119. def entries(self):
  120. with open('/proc/net/tcp') as f:
  121. f.readline()
  122. for L in f:
  123. yield L.strip()
  124. def dottedQuadFromHexString(self, hexstr):
  125. return '.'.join(map(str, struct.unpack('4B', struct.pack('=L', int(hexstr, 16)))))
  126. def unpackAddress(self, packed):
  127. addr, port = packed.split(':')
  128. addr = self.dottedQuadFromHexString(addr)
  129. port = int(port, 16)
  130. return addr, port
  131. def parseLine(self, line):
  132. parts = line.strip().split()
  133. localAddr, localPort = self.unpackAddress(parts[1])
  134. remoteAddr, remotePort = self.unpackAddress(parts[2])
  135. uid = int(parts[7])
  136. return (localAddr, localPort), (remoteAddr, remotePort), uid
  137. def lookup(self, serverAddress, clientAddress):
  138. for ent in self.entries():
  139. localAddr, remoteAddr, uid = self.parseLine(ent)
  140. if remoteAddr == clientAddress and localAddr[1] == serverAddress[1]:
  141. return (self.SYSTEM_NAME, self.getUsername(uid))
  142. raise NoUser()
  143. class IdentClient(basic.LineOnlyReceiver):
  144. errorTypes = (IdentError, NoUser, InvalidPort, HiddenUser)
  145. def __init__(self):
  146. self.queries = []
  147. def lookup(self, portOnServer, portOnClient):
  148. """
  149. Lookup user information about the specified address pair.
  150. """
  151. self.queries.append((defer.Deferred(), portOnServer, portOnClient))
  152. if len(self.queries) > 1:
  153. return self.queries[-1][0]
  154. self.sendLine('%d, %d' % (portOnServer, portOnClient))
  155. return self.queries[-1][0]
  156. def lineReceived(self, line):
  157. if not self.queries:
  158. log.msg("Unexpected server response: %r" % (line,))
  159. else:
  160. d, _, _ = self.queries.pop(0)
  161. self.parseResponse(d, line)
  162. if self.queries:
  163. self.sendLine('%d, %d' % (self.queries[0][1], self.queries[0][2]))
  164. def connectionLost(self, reason):
  165. for q in self.queries:
  166. q[0].errback(IdentError(reason))
  167. self.queries = []
  168. def parseResponse(self, deferred, line):
  169. parts = line.split(':', 2)
  170. if len(parts) != 3:
  171. deferred.errback(IdentError(line))
  172. else:
  173. ports, type, addInfo = map(str.strip, parts)
  174. if type == 'ERROR':
  175. for et in self.errorTypes:
  176. if et.identDescription == addInfo:
  177. deferred.errback(et(line))
  178. return
  179. deferred.errback(IdentError(line))
  180. else:
  181. deferred.callback((type, addInfo))
  182. __all__ = ['IdentError', 'NoUser', 'InvalidPort', 'HiddenUser',
  183. 'IdentServer', 'IdentClient',
  184. 'ProcServerMixin']