Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

socks.py 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. # -*- test-case-name: twisted.test.test_socks -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Implementation of the SOCKSv4 protocol.
  6. """
  7. import socket
  8. import string
  9. # python imports
  10. import struct
  11. import time
  12. # twisted imports
  13. from twisted.internet import defer, protocol, reactor
  14. from twisted.python import log
  15. class SOCKSv4Outgoing(protocol.Protocol):
  16. def __init__(self, socks):
  17. self.socks = socks
  18. def connectionMade(self):
  19. peer = self.transport.getPeer()
  20. self.socks.makeReply(90, 0, port=peer.port, ip=peer.host)
  21. self.socks.otherConn = self
  22. def connectionLost(self, reason):
  23. self.socks.transport.loseConnection()
  24. def dataReceived(self, data):
  25. self.socks.write(data)
  26. def write(self, data):
  27. self.socks.log(self, data)
  28. self.transport.write(data)
  29. class SOCKSv4Incoming(protocol.Protocol):
  30. def __init__(self, socks):
  31. self.socks = socks
  32. self.socks.otherConn = self
  33. def connectionLost(self, reason):
  34. self.socks.transport.loseConnection()
  35. def dataReceived(self, data):
  36. self.socks.write(data)
  37. def write(self, data):
  38. self.socks.log(self, data)
  39. self.transport.write(data)
  40. class SOCKSv4(protocol.Protocol):
  41. """
  42. An implementation of the SOCKSv4 protocol.
  43. @type logging: L{str} or L{None}
  44. @ivar logging: If not L{None}, the name of the logfile to which connection
  45. information will be written.
  46. @type reactor: object providing L{twisted.internet.interfaces.IReactorTCP}
  47. @ivar reactor: The reactor used to create connections.
  48. @type buf: L{str}
  49. @ivar buf: Part of a SOCKSv4 connection request.
  50. @type otherConn: C{SOCKSv4Incoming}, C{SOCKSv4Outgoing} or L{None}
  51. @ivar otherConn: Until the connection has been established, C{otherConn} is
  52. L{None}. After that, it is the proxy-to-destination protocol instance
  53. along which the client's connection is being forwarded.
  54. """
  55. def __init__(self, logging=None, reactor=reactor):
  56. self.logging = logging
  57. self.reactor = reactor
  58. def connectionMade(self):
  59. self.buf = b""
  60. self.otherConn = None
  61. def dataReceived(self, data):
  62. """
  63. Called whenever data is received.
  64. @type data: L{bytes}
  65. @param data: Part or all of a SOCKSv4 packet.
  66. """
  67. if self.otherConn:
  68. self.otherConn.write(data)
  69. return
  70. self.buf = self.buf + data
  71. completeBuffer = self.buf
  72. if b"\000" in self.buf[8:]:
  73. head, self.buf = self.buf[:8], self.buf[8:]
  74. version, code, port = struct.unpack("!BBH", head[:4])
  75. user, self.buf = self.buf.split(b"\000", 1)
  76. if head[4:7] == b"\000\000\000" and head[7:8] != b"\000":
  77. # An IP address of the form 0.0.0.X, where X is non-zero,
  78. # signifies that this is a SOCKSv4a packet.
  79. # If the complete packet hasn't been received, restore the
  80. # buffer and wait for it.
  81. if b"\000" not in self.buf:
  82. self.buf = completeBuffer
  83. return
  84. server, self.buf = self.buf.split(b"\000", 1)
  85. d = self.reactor.resolve(server)
  86. d.addCallback(self._dataReceived2, user, version, code, port)
  87. d.addErrback(lambda result, self=self: self.makeReply(91))
  88. return
  89. else:
  90. server = socket.inet_ntoa(head[4:8])
  91. self._dataReceived2(server, user, version, code, port)
  92. def _dataReceived2(self, server, user, version, code, port):
  93. """
  94. The second half of the SOCKS connection setup. For a SOCKSv4 packet this
  95. is after the server address has been extracted from the header. For a
  96. SOCKSv4a packet this is after the host name has been resolved.
  97. @type server: L{str}
  98. @param server: The IP address of the destination, represented as a
  99. dotted quad.
  100. @type user: L{str}
  101. @param user: The username associated with the connection.
  102. @type version: L{int}
  103. @param version: The SOCKS protocol version number.
  104. @type code: L{int}
  105. @param code: The command code. 1 means establish a TCP/IP stream
  106. connection, and 2 means establish a TCP/IP port binding.
  107. @type port: L{int}
  108. @param port: The port number associated with the connection.
  109. """
  110. assert version == 4, "Bad version code: %s" % version
  111. if not self.authorize(code, server, port, user):
  112. self.makeReply(91)
  113. return
  114. if code == 1: # CONNECT
  115. d = self.connectClass(server, port, SOCKSv4Outgoing, self)
  116. d.addErrback(lambda result, self=self: self.makeReply(91))
  117. elif code == 2: # BIND
  118. d = self.listenClass(0, SOCKSv4IncomingFactory, self, server)
  119. d.addCallback(lambda x, self=self: self.makeReply(90, 0, x[1], x[0]))
  120. else:
  121. raise RuntimeError(f"Bad Connect Code: {code}")
  122. assert self.buf == b"", "hmm, still stuff in buffer... %s" % repr(self.buf)
  123. def connectionLost(self, reason):
  124. if self.otherConn:
  125. self.otherConn.transport.loseConnection()
  126. def authorize(self, code, server, port, user):
  127. log.msg(
  128. "code %s connection to %s:%s (user %s) authorized"
  129. % (code, server, port, user)
  130. )
  131. return 1
  132. def connectClass(self, host, port, klass, *args):
  133. return protocol.ClientCreator(reactor, klass, *args).connectTCP(host, port)
  134. def listenClass(self, port, klass, *args):
  135. serv = reactor.listenTCP(port, klass(*args))
  136. return defer.succeed(serv.getHost()[1:])
  137. def makeReply(self, reply, version=0, port=0, ip="0.0.0.0"):
  138. self.transport.write(
  139. struct.pack("!BBH", version, reply, port) + socket.inet_aton(ip)
  140. )
  141. if reply != 90:
  142. self.transport.loseConnection()
  143. def write(self, data):
  144. self.log(self, data)
  145. self.transport.write(data)
  146. def log(self, proto, data):
  147. if not self.logging:
  148. return
  149. peer = self.transport.getPeer()
  150. their_peer = self.otherConn.transport.getPeer()
  151. f = open(self.logging, "a")
  152. f.write(
  153. "%s\t%s:%d %s %s:%d\n"
  154. % (
  155. time.ctime(),
  156. peer.host,
  157. peer.port,
  158. ((proto == self and "<") or ">"),
  159. their_peer.host,
  160. their_peer.port,
  161. )
  162. )
  163. while data:
  164. p, data = data[:16], data[16:]
  165. f.write(string.join(map(lambda x: "%02X" % ord(x), p), " ") + " ")
  166. f.write((16 - len(p)) * 3 * " ")
  167. for c in p:
  168. if len(repr(c)) > 3:
  169. f.write(".")
  170. else:
  171. f.write(c)
  172. f.write("\n")
  173. f.write("\n")
  174. f.close()
  175. class SOCKSv4Factory(protocol.Factory):
  176. """
  177. A factory for a SOCKSv4 proxy.
  178. Constructor accepts one argument, a log file name.
  179. """
  180. def __init__(self, log):
  181. self.logging = log
  182. def buildProtocol(self, addr):
  183. return SOCKSv4(self.logging, reactor)
  184. class SOCKSv4IncomingFactory(protocol.Factory):
  185. """
  186. A utility class for building protocols for incoming connections.
  187. """
  188. def __init__(self, socks, ip):
  189. self.socks = socks
  190. self.ip = ip
  191. def buildProtocol(self, addr):
  192. if addr[0] == self.ip:
  193. self.ip = ""
  194. self.socks.makeReply(90, 0)
  195. return SOCKSv4Incoming(self.socks)
  196. elif self.ip == "":
  197. return None
  198. else:
  199. self.socks.makeReply(91, 0)
  200. self.ip = ""
  201. return None