ident.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 failure, log
  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) -> str:
  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 (
  62. _MIN_PORT <= portOnServer <= _MAX_PORT
  63. and _MIN_PORT <= portOnClient <= _MAX_PORT
  64. ):
  65. self.validQuery(portOnServer, portOnClient)
  66. else:
  67. self._ebLookup(
  68. failure.Failure(InvalidPort()), portOnServer, portOnClient
  69. )
  70. def invalidQuery(self):
  71. self.transport.loseConnection()
  72. def validQuery(self, portOnServer, portOnClient):
  73. """
  74. Called when a valid query is received to look up and deliver the
  75. response.
  76. @param portOnServer: The server port from the query.
  77. @param portOnClient: The client port from the query.
  78. """
  79. serverAddr = self.transport.getHost().host, portOnServer
  80. clientAddr = self.transport.getPeer().host, portOnClient
  81. defer.maybeDeferred(self.lookup, serverAddr, clientAddr).addCallback(
  82. self._cbLookup, portOnServer, portOnClient
  83. ).addErrback(self._ebLookup, portOnServer, portOnClient)
  84. def _cbLookup(self, result, sport, cport):
  85. (sysName, userId) = result
  86. self.sendLine("%d, %d : USERID : %s : %s" % (sport, cport, sysName, userId))
  87. def _ebLookup(self, failure, sport, cport):
  88. if failure.check(IdentError):
  89. self.sendLine("%d, %d : ERROR : %s" % (sport, cport, failure.value))
  90. else:
  91. log.err(failure)
  92. self.sendLine(
  93. "%d, %d : ERROR : %s" % (sport, cport, IdentError(failure.value))
  94. )
  95. def lookup(self, serverAddress, clientAddress):
  96. """
  97. Lookup user information about the specified address pair.
  98. Return value should be a two-tuple of system name and username.
  99. Acceptable values for the system name may be found online at::
  100. U{http://www.iana.org/assignments/operating-system-names}
  101. This method may also raise any IdentError subclass (or IdentError
  102. itself) to indicate user information will not be provided for the
  103. given query.
  104. A Deferred may also be returned.
  105. @param serverAddress: A two-tuple representing the server endpoint
  106. of the address being queried. The first element is a string holding
  107. a dotted-quad IP address. The second element is an integer
  108. representing the port.
  109. @param clientAddress: Like I{serverAddress}, but represents the
  110. client endpoint of the address being queried.
  111. """
  112. raise IdentError()
  113. class ProcServerMixin:
  114. """Implements lookup() to grab entries for responses from /proc/net/tcp"""
  115. SYSTEM_NAME = "LINUX"
  116. try:
  117. from pwd import getpwuid # type:ignore[misc]
  118. def getUsername(self, uid, getpwuid=getpwuid):
  119. return getpwuid(uid)[0]
  120. del getpwuid
  121. except ImportError:
  122. def getUsername(self, uid, getpwuid=None):
  123. raise IdentError()
  124. def entries(self):
  125. with open("/proc/net/tcp") as f:
  126. f.readline()
  127. for L in f:
  128. yield L.strip()
  129. def dottedQuadFromHexString(self, hexstr):
  130. return ".".join(
  131. map(str, struct.unpack("4B", struct.pack("=L", int(hexstr, 16))))
  132. )
  133. def unpackAddress(self, packed):
  134. addr, port = packed.split(":")
  135. addr = self.dottedQuadFromHexString(addr)
  136. port = int(port, 16)
  137. return addr, port
  138. def parseLine(self, line):
  139. parts = line.strip().split()
  140. localAddr, localPort = self.unpackAddress(parts[1])
  141. remoteAddr, remotePort = self.unpackAddress(parts[2])
  142. uid = int(parts[7])
  143. return (localAddr, localPort), (remoteAddr, remotePort), uid
  144. def lookup(self, serverAddress, clientAddress):
  145. for ent in self.entries():
  146. localAddr, remoteAddr, uid = self.parseLine(ent)
  147. if remoteAddr == clientAddress and localAddr[1] == serverAddress[1]:
  148. return (self.SYSTEM_NAME, self.getUsername(uid))
  149. raise NoUser()
  150. class IdentClient(basic.LineOnlyReceiver):
  151. errorTypes = (IdentError, NoUser, InvalidPort, HiddenUser)
  152. def __init__(self):
  153. self.queries = []
  154. def lookup(self, portOnServer, portOnClient):
  155. """
  156. Lookup user information about the specified address pair.
  157. """
  158. self.queries.append((defer.Deferred(), portOnServer, portOnClient))
  159. if len(self.queries) > 1:
  160. return self.queries[-1][0]
  161. self.sendLine("%d, %d" % (portOnServer, portOnClient))
  162. return self.queries[-1][0]
  163. def lineReceived(self, line):
  164. if not self.queries:
  165. log.msg(f"Unexpected server response: {line!r}")
  166. else:
  167. d, _, _ = self.queries.pop(0)
  168. self.parseResponse(d, line)
  169. if self.queries:
  170. self.sendLine("%d, %d" % (self.queries[0][1], self.queries[0][2]))
  171. def connectionLost(self, reason):
  172. for q in self.queries:
  173. q[0].errback(IdentError(reason))
  174. self.queries = []
  175. def parseResponse(self, deferred, line):
  176. parts = line.split(":", 2)
  177. if len(parts) != 3:
  178. deferred.errback(IdentError(line))
  179. else:
  180. ports, type, addInfo = map(str.strip, parts)
  181. if type == "ERROR":
  182. for et in self.errorTypes:
  183. if et.identDescription == addInfo:
  184. deferred.errback(et(line))
  185. return
  186. deferred.errback(IdentError(line))
  187. else:
  188. deferred.callback((type, addInfo))
  189. __all__ = [
  190. "IdentError",
  191. "NoUser",
  192. "InvalidPort",
  193. "HiddenUser",
  194. "IdentServer",
  195. "IdentClient",
  196. "ProcServerMixin",
  197. ]