Advertisement
Guest User

Untitled

a guest
Mar 17th, 2018
732
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 35.69 KB | None | 0 0
  1. /**
  2.     SOCKS 4
  3.     SOCKS: A protocol for TCP proxy across firewalls
  4.  
  5.             Ying-Da Lee
  6.         Principal Member Technical Staff
  7.           NEC Systems Laboratory, CSTC
  8.             ylee@syl.dl.nec.com
  9.  
  10. SOCKS was originally developed by David Koblas and subsequently modified
  11. and extended by me to its current running version -- version 4. It is a
  12. protocol that relays TCP sessions at a firewall host to allow application
  13. users transparent access across the firewall. Because the protocol is
  14. independent of application protocols, it can be (and has been) used for
  15. many different services, such as telnet, ftp, finger, whois, gopher, WWW,
  16. etc. Access control can be applied at the beginning of each TCP session;
  17. thereafter the server simply relays the data between the client and the
  18. application server, incurring minimum processing overhead. Since SOCKS
  19. never has to know anything about the application protocol, it should also
  20. be easy for it to accommodate applications which use encryption to protect
  21. their traffic from nosey snoopers.
  22.  
  23. Two operations are defined: CONNECT and BIND.
  24.  
  25. 1) CONNECT
  26.  
  27. The client connects to the SOCKS server and sends a CONNECT request when
  28. it wants to establish a connection to an application server. The client
  29. includes in the request packet the IP address and the port number of the
  30. destination host, and userid, in the following format.
  31.  
  32.         +----+----+----+----+----+----+----+----+----+----+....+----+
  33.         | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|
  34.         +----+----+----+----+----+----+----+----+----+----+....+----+
  35.  # of bytes:       1    1      2              4           variable       1
  36.  
  37. VN is the SOCKS protocol version number and should be 4. CD is the
  38. SOCKS command code and should be 1 for CONNECT request. NULL is a byte
  39. of all zero bits.
  40.  
  41. The SOCKS server checks to see whether such a request should be granted
  42. based on any combination of source IP address, destination IP address,
  43. destination port number, the userid, and information it may obtain by
  44. consulting IDENT, cf. RFC 1413.  If the request is granted, the SOCKS
  45. server makes a connection to the specified port of the destination host.
  46. A reply packet is sent to the client when this connection is established,
  47. or when the request is rejected or the operation fails.
  48.  
  49.         +----+----+----+----+----+----+----+----+
  50.         | VN | CD | DSTPORT |      DSTIP        |
  51.         +----+----+----+----+----+----+----+----+
  52.  # of bytes:       1    1      2              4
  53.  
  54. VN is the version of the reply code and should be 0. CD is the result
  55. code with one of the following values:
  56.  
  57.     90: request granted
  58.     91: request rejected or failed
  59.     92: request rejected becasue SOCKS server cannot connect to
  60.         identd on the client
  61.     93: request rejected because the client program and identd
  62.         report different user-ids
  63.  
  64. The remaining fields are ignored.
  65.  
  66. The SOCKS server closes its connection immediately after notifying
  67. the client of a failed or rejected request. For a successful request,
  68. the SOCKS server gets ready to relay traffic on both directions. This
  69. enables the client to do I/O on its connection as if it were directly
  70. connected to the application server.
  71.  
  72.  
  73. 2) BIND
  74.  
  75. The client connects to the SOCKS server and sends a BIND request when
  76. it wants to prepare for an inbound connection from an application server.
  77. This should only happen after a primary connection to the application
  78. server has been established with a CONNECT.  Typically, this is part of
  79. the sequence of actions:
  80.  
  81. -bind(): obtain a socket
  82. -getsockname(): get the IP address and port number of the socket
  83. -listen(): ready to accept call from the application server
  84. -use the primary connection to inform the application server of
  85.  the IP address and the port number that it should connect to.
  86. -accept(): accept a connection from the application server
  87.  
  88. The purpose of SOCKS BIND operation is to support such a sequence
  89. but using a socket on the SOCKS server rather than on the client.
  90.  
  91. The client includes in the request packet the IP address of the
  92. application server, the destination port used in the primary connection,
  93. and the userid.
  94.  
  95.         +----+----+----+----+----+----+----+----+----+----+....+----+
  96.         | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|
  97.         +----+----+----+----+----+----+----+----+----+----+....+----+
  98.  # of bytes:       1    1      2              4           variable       1
  99.  
  100. VN is again 4 for the SOCKS protocol version number. CD must be 2 to
  101. indicate BIND request.
  102.  
  103. The SOCKS server uses the client information to decide whether the
  104. request is to be granted. The reply it sends back to the client has
  105. the same format as the reply for CONNECT request, i.e.,
  106.  
  107.         +----+----+----+----+----+----+----+----+
  108.         | VN | CD | DSTPORT |      DSTIP        |
  109.         +----+----+----+----+----+----+----+----+
  110.  # of bytes:       1    1      2              4
  111.  
  112. VN is the version of the reply code and should be 0. CD is the result
  113. code with one of the following values:
  114.  
  115.     90: request granted
  116.     91: request rejected or failed
  117.     92: request rejected becasue SOCKS server cannot connect to
  118.         identd on the client
  119.     93: request rejected because the client program and identd
  120.         report different user-ids.
  121.  
  122. However, for a granted request (CD is 90), the DSTPORT and DSTIP fields
  123. are meaningful.  In that case, the SOCKS server obtains a socket to wait
  124. for an incoming connection and sends the port number and the IP address
  125. of that socket to the client in DSTPORT and DSTIP, respectively. If the
  126. DSTIP in the reply is 0 (the value of constant INADDR_ANY), then the
  127. client should replace it by the IP address of the SOCKS server to which
  128. the cleint is connected. (This happens if the SOCKS server is not a
  129. multi-homed host.)  In the typical scenario, these two numbers are
  130. made available to the application client prgram via the result of the
  131. subsequent getsockname() call.  The application protocol must provide a
  132. way for these two pieces of information to be sent from the client to
  133. the application server so that it can initiate the connection, which
  134. connects it to the SOCKS server rather than directly to the application
  135. client as it normally would.
  136.  
  137. The SOCKS server sends a second reply packet to the client when the
  138. anticipated connection from the application server is established.
  139. The SOCKS server checks the IP address of the originating host against
  140. the value of DSTIP specified in the client's BIND request.  If a mismatch
  141. is found, the CD field in the second reply is set to 91 and the SOCKS
  142. server closes both connections.  If the two match, CD in the second
  143. reply is set to 90 and the SOCKS server gets ready to relay the traffic
  144. on its two connections. From then on the client does I/O on its connection
  145. to the SOCKS server as if it were directly connected to the application
  146. server.
  147.  
  148.  
  149.  
  150. For both CONNECT and BIND operations, the server sets a time limit
  151. (2 minutes in current CSTC implementation) for the establishment of its
  152. connection with the application server. If the connection is still not
  153. establiched when the time limit expires, the server closes its connection
  154. to the client and gives up.    
  155.  */
  156.  
  157. /**
  158.  
  159.  
  160. Network Working Group                                           M. Leech
  161. Request for Comments: 1928                    Bell-Northern Research Ltd
  162. Category: Standards Track                                       M. Ganis
  163.                                          International Business Machines
  164.                                                                   Y. Lee
  165.                                                   NEC Systems Laboratory
  166.                                                                 R. Kuris
  167.                                                        Unify Corporation
  168.                                                                D. Koblas
  169.                                                   Independent Consultant
  170.                                                                 L. Jones
  171.                                                  Hewlett-Packard Company
  172.                                                               March 1996
  173.  
  174.  
  175.                         SOCKS Protocol Version 5
  176.  
  177. Status of this Memo
  178.  
  179.    This document specifies an Internet standards track protocol for the
  180.    Internet community, and requests discussion and suggestions for
  181.    improvements.  Please refer to the current edition of the "Internet
  182.    Official Protocol Standards" (STD 1) for the standardization state
  183.    and status of this protocol.  Distribution of this memo is unlimited.
  184.  
  185. Acknowledgments
  186.  
  187.    This memo describes a protocol that is an evolution of the previous
  188.    version of the protocol, version 4 [1]. This new protocol stems from
  189.    active discussions and prototype implementations.  The key
  190.    contributors are: Marcus Leech: Bell-Northern Research, David Koblas:
  191.    Independent Consultant, Ying-Da Lee: NEC Systems Laboratory, LaMont
  192.    Jones: Hewlett-Packard Company, Ron Kuris: Unify Corporation, Matt
  193.    Ganis: International Business Machines.
  194.  
  195. 1.  Introduction
  196.  
  197.    The use of network firewalls, systems that effectively isolate an
  198.    organizations internal network structure from an exterior network,
  199.    such as the INTERNET is becoming increasingly popular.  These
  200.    firewall systems typically act as application-layer gateways between
  201.    networks, usually offering controlled TELNET, FTP, and SMTP access.
  202.    With the emergence of more sophisticated application layer protocols
  203.    designed to facilitate global information discovery, there exists a
  204.    need to provide a general framework for these protocols to
  205.    transparently and securely traverse a firewall.
  206.  
  207.  
  208.  
  209.  
  210.  
  211. Leech, et al                Standards Track                     [Page 1]
  212.  
  213.  
  214. RFC 1928                SOCKS Protocol Version 5              March 1996
  215.  
  216.  
  217.    There exists, also, a need for strong authentication of such
  218.    traversal in as fine-grained a manner as is practical. This
  219.    requirement stems from the realization that client-server
  220.    relationships emerge between the networks of various organizations,
  221.    and that such relationships need to be controlled and often strongly
  222.    authenticated.
  223.  
  224.    The protocol described here is designed to provide a framework for
  225.    client-server applications in both the TCP and UDP domains to
  226.    conveniently and securely use the services of a network firewall.
  227.    The protocol is conceptually a "shim-layer" between the application
  228.    layer and the transport layer, and as such does not provide network-
  229.    layer gateway services, such as forwarding of ICMP messages.
  230.  
  231. 2.  Existing practice
  232.  
  233.    There currently exists a protocol, SOCKS Version 4, that provides for
  234.    unsecured firewall traversal for TCP-based client-server
  235.    applications, including TELNET, FTP and the popular information-
  236.    discovery protocols such as HTTP, WAIS and GOPHER.
  237.  
  238.    This new protocol extends the SOCKS Version 4 model to include UDP,
  239.    and extends the framework to include provisions for generalized
  240.    strong authentication schemes, and extends the addressing scheme to
  241.    encompass domain-name and V6 IP addresses.
  242.  
  243.    The implementation of the SOCKS protocol typically involves the
  244.    recompilation or relinking of TCP-based client applications to use
  245.    the appropriate encapsulation routines in the SOCKS library.
  246.  
  247. Note:
  248.  
  249.    Unless otherwise noted, the decimal numbers appearing in packet-
  250.    format diagrams represent the length of the corresponding field, in
  251.    octets.  Where a given octet must take on a specific value, the
  252.    syntax X'hh' is used to denote the value of the single octet in that
  253.    field. When the word 'Variable' is used, it indicates that the
  254.    corresponding field has a variable length defined either by an
  255.    associated (one or two octet) length field, or by a data type field.
  256.  
  257. 3.  Procedure for TCP-based clients
  258.  
  259.    When a TCP-based client wishes to establish a connection to an object
  260.    that is reachable only via a firewall (such determination is left up
  261.    to the implementation), it must open a TCP connection to the
  262.    appropriate SOCKS port on the SOCKS server system.  The SOCKS service
  263.    is conventionally located on TCP port 1080.  If the connection
  264.    request succeeds, the client enters a negotiation for the
  265.  
  266.  
  267.  
  268. Leech, et al                Standards Track                     [Page 2]
  269.  
  270.  
  271. RFC 1928                SOCKS Protocol Version 5              March 1996
  272.  
  273.  
  274.    authentication method to be used, authenticates with the chosen
  275.    method, then sends a relay request.  The SOCKS server evaluates the
  276.    request, and either establishes the appropriate connection or denies
  277.    it.
  278.  
  279.    Unless otherwise noted, the decimal numbers appearing in packet-
  280.    format diagrams represent the length of the corresponding field, in
  281.    octets.  Where a given octet must take on a specific value, the
  282.    syntax X'hh' is used to denote the value of the single octet in that
  283.    field. When the word 'Variable' is used, it indicates that the
  284.    corresponding field has a variable length defined either by an
  285.    associated (one or two octet) length field, or by a data type field.
  286.  
  287.    The client connects to the server, and sends a version
  288.    identifier/method selection message:
  289.  
  290.                    +----+----------+----------+
  291.                    |VER | NMETHODS | METHODS  |
  292.                    +----+----------+----------+
  293.                    | 1  |    1     | 1 to 255 |
  294.                    +----+----------+----------+
  295.  
  296.    The VER field is set to X'05' for this version of the protocol.  The
  297.    NMETHODS field contains the number of method identifier octets that
  298.    appear in the METHODS field.
  299.  
  300.    The server selects from one of the methods given in METHODS, and
  301.    sends a METHOD selection message:
  302.  
  303.                          +----+--------+
  304.                          |VER | METHOD |
  305.                          +----+--------+
  306.                          | 1  |   1    |
  307.                          +----+--------+
  308.  
  309.    If the selected METHOD is X'FF', none of the methods listed by the
  310.    client are acceptable, and the client MUST close the connection.
  311.  
  312.    The values currently defined for METHOD are:
  313.  
  314.           o  X'00' NO AUTHENTICATION REQUIRED
  315.           o  X'01' GSSAPI
  316.           o  X'02' USERNAME/PASSWORD
  317.           o  X'03' to X'7F' IANA ASSIGNED
  318.           o  X'80' to X'FE' RESERVED FOR PRIVATE METHODS
  319.           o  X'FF' NO ACCEPTABLE METHODS
  320.  
  321.    The client and server then enter a method-specific sub-negotiation.
  322.  
  323.  
  324.  
  325. Leech, et al                Standards Track                     [Page 3]
  326.  
  327.  
  328. RFC 1928                SOCKS Protocol Version 5              March 1996
  329.  
  330.  
  331.    Descriptions of the method-dependent sub-negotiations appear in
  332.    separate memos.
  333.  
  334.    Developers of new METHOD support for this protocol should contact
  335.    IANA for a METHOD number.  The ASSIGNED NUMBERS document should be
  336.    referred to for a current list of METHOD numbers and their
  337.    corresponding protocols.
  338.  
  339.    Compliant implementations MUST support GSSAPI and SHOULD support
  340.    USERNAME/PASSWORD authentication methods.
  341.  
  342. 4.  Requests
  343.  
  344.    Once the method-dependent subnegotiation has completed, the client
  345.    sends the request details.  If the negotiated method includes
  346.    encapsulation for purposes of integrity checking and/or
  347.    confidentiality, these requests MUST be encapsulated in the method-
  348.    dependent encapsulation.
  349.  
  350.    The SOCKS request is formed as follows:
  351.  
  352.         +----+-----+-------+------+----------+----------+
  353.         |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
  354.         +----+-----+-------+------+----------+----------+
  355.         | 1  |  1  | X'00' |  1   | Variable |    2     |
  356.         +----+-----+-------+------+----------+----------+
  357.  
  358.      Where:
  359.  
  360.           o  VER    protocol version: X'05'
  361.           o  CMD
  362.              o  CONNECT X'01'
  363.              o  BIND X'02'
  364.              o  UDP ASSOCIATE X'03'
  365.           o  RSV    RESERVED
  366.           o  ATYP   address type of following address
  367.              o  IP V4 address: X'01'
  368.              o  DOMAINNAME: X'03'
  369.              o  IP V6 address: X'04'
  370.           o  DST.ADDR       desired destination address
  371.           o  DST.PORT desired destination port in network octet
  372.              order
  373.  
  374.    The SOCKS server will typically evaluate the request based on source
  375.    and destination addresses, and return one or more reply messages, as
  376.    appropriate for the request type.
  377.  
  378.  
  379.  
  380.  
  381.  
  382. Leech, et al                Standards Track                     [Page 4]
  383.  
  384.  
  385. RFC 1928                SOCKS Protocol Version 5              March 1996
  386.  
  387.  
  388. 5.  Addressing
  389.  
  390.    In an address field (DST.ADDR, BND.ADDR), the ATYP field specifies
  391.    the type of address contained within the field:
  392.  
  393.           o  X'01'
  394.  
  395.    the address is a version-4 IP address, with a length of 4 octets
  396.  
  397.           o  X'03'
  398.  
  399.    the address field contains a fully-qualified domain name.  The first
  400.    octet of the address field contains the number of octets of name that
  401.    follow, there is no terminating NUL octet.
  402.  
  403.           o  X'04'
  404.  
  405.    the address is a version-6 IP address, with a length of 16 octets.
  406.  
  407. 6.  Replies
  408.  
  409.    The SOCKS request information is sent by the client as soon as it has
  410.    established a connection to the SOCKS server, and completed the
  411.    authentication negotiations.  The server evaluates the request, and
  412.    returns a reply formed as follows:
  413.  
  414.         +----+-----+-------+------+----------+----------+
  415.         |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
  416.         +----+-----+-------+------+----------+----------+
  417.         | 1  |  1  | X'00' |  1   | Variable |    2     |
  418.         +----+-----+-------+------+----------+----------+
  419.  
  420.      Where:
  421.  
  422.           o  VER    protocol version: X'05'
  423.           o  REP    Reply field:
  424.              o  X'00' succeeded
  425.              o  X'01' general SOCKS server failure
  426.              o  X'02' connection not allowed by ruleset
  427.              o  X'03' Network unreachable
  428.              o  X'04' Host unreachable
  429.              o  X'05' Connection refused
  430.              o  X'06' TTL expired
  431.              o  X'07' Command not supported
  432.              o  X'08' Address type not supported
  433.              o  X'09' to X'FF' unassigned
  434.           o  RSV    RESERVED
  435.           o  ATYP   address type of following address
  436.  
  437.  
  438.  
  439. Leech, et al                Standards Track                     [Page 5]
  440.  
  441.  
  442. RFC 1928                SOCKS Protocol Version 5              March 1996
  443.  
  444.  
  445.              o  IP V4 address: X'01'
  446.              o  DOMAINNAME: X'03'
  447.              o  IP V6 address: X'04'
  448.           o  BND.ADDR       server bound address
  449.           o  BND.PORT       server bound port in network octet order
  450.  
  451.    Fields marked RESERVED (RSV) must be set to X'00'.
  452.  
  453.    If the chosen method includes encapsulation for purposes of
  454.    authentication, integrity and/or confidentiality, the replies are
  455.    encapsulated in the method-dependent encapsulation.
  456.  
  457. CONNECT
  458.  
  459.    In the reply to a CONNECT, BND.PORT contains the port number that the
  460.    server assigned to connect to the target host, while BND.ADDR
  461.    contains the associated IP address.  The supplied BND.ADDR is often
  462.    different from the IP address that the client uses to reach the SOCKS
  463.    server, since such servers are often multi-homed.  It is expected
  464.    that the SOCKS server will use DST.ADDR and DST.PORT, and the
  465.    client-side source address and port in evaluating the CONNECT
  466.    request.
  467.  
  468. BIND
  469.  
  470.    The BIND request is used in protocols which require the client to
  471.    accept connections from the server.  FTP is a well-known example,
  472.    which uses the primary client-to-server connection for commands and
  473.    status reports, but may use a server-to-client connection for
  474.    transferring data on demand (e.g. LS, GET, PUT).
  475.  
  476.    It is expected that the client side of an application protocol will
  477.    use the BIND request only to establish secondary connections after a
  478.    primary connection is established using CONNECT.  In is expected that
  479.    a SOCKS server will use DST.ADDR and DST.PORT in evaluating the BIND
  480.    request.
  481.  
  482.    Two replies are sent from the SOCKS server to the client during a
  483.    BIND operation.  The first is sent after the server creates and binds
  484.    a new socket.  The BND.PORT field contains the port number that the
  485.    SOCKS server assigned to listen for an incoming connection.  The
  486.    BND.ADDR field contains the associated IP address.  The client will
  487.    typically use these pieces of information to notify (via the primary
  488.    or control connection) the application server of the rendezvous
  489.    address.  The second reply occurs only after the anticipated incoming
  490.    connection succeeds or fails.
  491.  
  492.  
  493.  
  494.  
  495.  
  496. Leech, et al                Standards Track                     [Page 6]
  497.  
  498.  
  499. RFC 1928                SOCKS Protocol Version 5              March 1996
  500.  
  501.  
  502.    In the second reply, the BND.PORT and BND.ADDR fields contain the
  503.    address and port number of the connecting host.
  504.  
  505. UDP ASSOCIATE
  506.  
  507.    The UDP ASSOCIATE request is used to establish an association within
  508.    the UDP relay process to handle UDP datagrams.  The DST.ADDR and
  509.    DST.PORT fields contain the address and port that the client expects
  510.    to use to send UDP datagrams on for the association.  The server MAY
  511.    use this information to limit access to the association.  If the
  512.    client is not in possesion of the information at the time of the UDP
  513.    ASSOCIATE, the client MUST use a port number and address of all
  514.    zeros.
  515.  
  516.    A UDP association terminates when the TCP connection that the UDP
  517.    ASSOCIATE request arrived on terminates.
  518.  
  519.    In the reply to a UDP ASSOCIATE request, the BND.PORT and BND.ADDR
  520.    fields indicate the port number/address where the client MUST send
  521.    UDP request messages to be relayed.
  522.  
  523. Reply Processing
  524.  
  525.    When a reply (REP value other than X'00') indicates a failure, the
  526.    SOCKS server MUST terminate the TCP connection shortly after sending
  527.    the reply.  This must be no more than 10 seconds after detecting the
  528.    condition that caused a failure.
  529.  
  530.    If the reply code (REP value of X'00') indicates a success, and the
  531.    request was either a BIND or a CONNECT, the client may now start
  532.    passing data.  If the selected authentication method supports
  533.    encapsulation for the purposes of integrity, authentication and/or
  534.    confidentiality, the data are encapsulated using the method-dependent
  535.    encapsulation.  Similarly, when data arrives at the SOCKS server for
  536.    the client, the server MUST encapsulate the data as appropriate for
  537.    the authentication method in use.
  538.  
  539. 7.  Procedure for UDP-based clients
  540.  
  541.    A UDP-based client MUST send its datagrams to the UDP relay server at
  542.    the UDP port indicated by BND.PORT in the reply to the UDP ASSOCIATE
  543.    request.  If the selected authentication method provides
  544.    encapsulation for the purposes of authenticity, integrity, and/or
  545.    confidentiality, the datagram MUST be encapsulated using the
  546.    appropriate encapsulation.  Each UDP datagram carries a UDP request
  547.    header with it:
  548.  
  549.  
  550.  
  551.  
  552.  
  553. Leech, et al                Standards Track                     [Page 7]
  554.  
  555.  
  556. RFC 1928                SOCKS Protocol Version 5              March 1996
  557.  
  558.  
  559.       +----+------+------+----------+----------+----------+
  560.       |RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
  561.       +----+------+------+----------+----------+----------+
  562.       | 2  |  1   |  1   | Variable |    2     | Variable |
  563.       +----+------+------+----------+----------+----------+
  564.  
  565.      The fields in the UDP request header are:
  566.  
  567.           o  RSV  Reserved X'0000'
  568.           o  FRAG    Current fragment number
  569.           o  ATYP    address type of following addresses:
  570.              o  IP V4 address: X'01'
  571.              o  DOMAINNAME: X'03'
  572.              o  IP V6 address: X'04'
  573.           o  DST.ADDR       desired destination address
  574.           o  DST.PORT       desired destination port
  575.           o  DATA     user data
  576.  
  577.    When a UDP relay server decides to relay a UDP datagram, it does so
  578.    silently, without any notification to the requesting client.
  579.    Similarly, it will drop datagrams it cannot or will not relay.  When
  580.    a UDP relay server receives a reply datagram from a remote host, it
  581.    MUST encapsulate that datagram using the above UDP request header,
  582.    and any authentication-method-dependent encapsulation.
  583.  
  584.    The UDP relay server MUST acquire from the SOCKS server the expected
  585.    IP address of the client that will send datagrams to the BND.PORT
  586.    given in the reply to UDP ASSOCIATE.  It MUST drop any datagrams
  587.    arriving from any source IP address other than the one recorded for
  588.    the particular association.
  589.  
  590.    The FRAG field indicates whether or not this datagram is one of a
  591.    number of fragments.  If implemented, the high-order bit indicates
  592.    end-of-fragment sequence, while a value of X'00' indicates that this
  593.    datagram is standalone.  Values between 1 and 127 indicate the
  594.    fragment position within a fragment sequence.  Each receiver will
  595.    have a REASSEMBLY QUEUE and a REASSEMBLY TIMER associated with these
  596.    fragments.  The reassembly queue must be reinitialized and the
  597.    associated fragments abandoned whenever the REASSEMBLY TIMER expires,
  598.    or a new datagram arrives carrying a FRAG field whose value is less
  599.    than the highest FRAG value processed for this fragment sequence.
  600.    The reassembly timer MUST be no less than 5 seconds.  It is
  601.    recommended that fragmentation be avoided by applications wherever
  602.    possible.
  603.  
  604.    Implementation of fragmentation is optional; an implementation that
  605.    does not support fragmentation MUST drop any datagram whose FRAG
  606.    field is other than X'00'.
  607.  
  608.  
  609.  
  610. Leech, et al                Standards Track                     [Page 8]
  611.  
  612.  
  613. RFC 1928                SOCKS Protocol Version 5              March 1996
  614.  
  615.  
  616.    The programming interface for a SOCKS-aware UDP MUST report an
  617.    available buffer space for UDP datagrams that is smaller than the
  618.    actual space provided by the operating system:
  619.  
  620.           o  if ATYP is X'01' - 10+method_dependent octets smaller
  621.           o  if ATYP is X'03' - 262+method_dependent octets smaller
  622.           o  if ATYP is X'04' - 20+method_dependent octets smaller
  623.  
  624. 8.  Security Considerations
  625.  
  626.    This document describes a protocol for the application-layer
  627.    traversal of IP network firewalls.  The security of such traversal is
  628.    highly dependent on the particular authentication and encapsulation
  629.    methods provided in a particular implementation, and selected during
  630.    negotiation between SOCKS client and SOCKS server.
  631.  
  632.    Careful consideration should be given by the administrator to the
  633.    selection of authentication methods.
  634.  
  635. 9.  References
  636.  
  637.    [1] Koblas, D., "SOCKS", Proceedings: 1992 Usenix Security Symposium.
  638.  
  639. Author's Address
  640.  
  641.        Marcus Leech
  642.        Bell-Northern Research Ltd
  643.        P.O. Box 3511, Stn. C,
  644.        Ottawa, ON
  645.        CANADA K1Y 4H7
  646.  
  647.        Phone: (613) 763-9145
  648.        EMail: mleech@bnr.ca
  649.  
  650.  
  651. Leech, et al                Standards Track                     [Page 9]
  652.  
  653.  */
  654.  
  655.  import java.net.*;
  656.  import java.io.*;
  657.  
  658. public class Main {
  659.  
  660.   ServerSocket server=null;
  661.   Socket client=null;
  662.  
  663.   public Main() {
  664.     initServerSocket();
  665.    
  666.   }
  667.  
  668.   private void initServerSocket(){
  669.     if(server==null){
  670.       try{
  671.         server=new ServerSocket(1080,5,InetAddress.getLocalHost());
  672.         Main.print("Server opened on:"+server.toString());
  673.         while(true){
  674.          final Socket s=server.accept();
  675.           new Thread(new Runnable(){
  676.             public void run(){
  677.               try{
  678.                 Main.print("Client logged on from:"+s.toString());
  679.                 autenticateClient(s);
  680.               }catch(Exception e){
  681.                 e.printStackTrace();
  682.               }            
  683.             }
  684.           }).start();
  685.         }        
  686.       }catch(Exception ex){
  687.         ex.printStackTrace();
  688.       }finally{
  689.         try{
  690.           server.close();
  691.         }catch(Exception e){
  692.         }
  693.       }
  694.     }
  695.   }
  696.  
  697.   private synchronized void autenticateClient(Socket client)throws Exception{
  698.     final InputStream in=client.getInputStream();
  699.     final OutputStream out=client.getOutputStream();
  700.     byte version=0;
  701.     //this is the version of the protocol. It should be 5
  702.     version=(byte)in.read();    
  703.     Main.print("Version of socks is:"+version);
  704.    
  705.     switch(version){
  706.       case 4:
  707.         socks4Auth(in,out);
  708.         break;
  709.       case 5:
  710.         socks5Auth(in,out);
  711.         break;
  712.       default:
  713.         throw new InternalError("Must be SOCKS version 5 or 4. Where did you hear about version "+version+"? ");
  714.     }    
  715.   }
  716.  
  717.   private void socks4Auth(InputStream in, OutputStream out)throws Exception {
  718.     //cd byte
  719.     byte cd=(byte)in.read();
  720.     Main.print("Received CD byte:"+cd);
  721.     switch(cd){
  722.       case 1:
  723.         Main.print("CONNECT");
  724.         break;
  725.       case 2:
  726.         Main.print("BIND");
  727.         break;
  728.     }
  729.  
  730.     byte[] dst_port=new byte[2];
  731.     in.read(dst_port);
  732.    
  733.    //network byte order decoder.
  734.     int port = dst_port[1] & 0xFF;
  735.     port     |= ((dst_port[0]<<8) & 0xFF00);
  736.  
  737.     Main.print("DST_PORT:"+port);
  738.    
  739.     byte[] dst_addr=null;
  740.  
  741.         Main.print("IPV4");
  742.         dst_addr=new byte[4];
  743.         in.read(dst_addr);                
  744.     InetAddress the_requested_address=null;
  745.    
  746.     if(dst_addr!=null){
  747.     int address  = dst_addr[3] & 0xFF;
  748.     address |= ((dst_addr[2] << 8) & 0xFF00);
  749.     address |= ((dst_addr[1] << 16) & 0xFF0000);
  750.     address |= ((dst_addr[0] << 24) & 0xFF000000);
  751.      
  752.       the_requested_address=InetAddress.getByName(((address >>> 24) & 0xFF) + "." +
  753.                 ((address >>> 16) & 0xFF) + "." +
  754.                 ((address >>>  8) & 0xFF) + "." +
  755.                 ((address >>>  0) & 0xFF));
  756.     }
  757.    
  758.     byte[] determined_ip=new byte[4];
  759.     //it could be the IP we've just received, or the IP determined by the domain name.
  760.     determined_ip=the_requested_address.getAddress();
  761.    
  762.     Main.print("The requested address name is:"+the_requested_address.getHostName());
  763.    
  764.     //NOW read the user_id (MUST FIND OUT WHAT THE HECK IS THAT)
  765.     java.util.Vector user_idVector=new java.util.Vector();
  766.     byte uid_byte_read=1;
  767.     while(uid_byte_read!=0){
  768.       uid_byte_read=(byte)in.read();
  769.       user_idVector.addElement(new Byte(uid_byte_read));
  770.     }  
  771.    
  772.     Main.print("USER ID received is:"+user_idVector);
  773.    
  774.     //reply SUCCESS no matter what, for now
  775.     out.write(new byte[]{0,90,dst_port[0],dst_port[1],determined_ip[0],determined_ip[1],determined_ip[2],determined_ip[3]});
  776.    
  777.     //next we must connect to a server witch must connect us to where we want . This is where PHP comes in
  778.     Socket toServerSocket=new Socket(the_requested_address,port);  
  779.     //start a thread that connects us to the application, and the other end
  780.     talk(in,out,toServerSocket.getInputStream(),toServerSocket.getOutputStream());      
  781.   }
  782.  
  783.   private void socks5Auth(InputStream in, OutputStream out)throws Exception {
  784.     int version=5;
  785.     //number of methods identifiers
  786.     byte nrMethods=(byte)in.read();
  787.     Main.print("number of methods identifiers :"+nrMethods);    
  788.     byte[] methods=new byte[nrMethods];
  789.     int methodsRead=in.read(methods);
  790.     Main.print("I have read :"+methodsRead+" methods occtets");
  791.    
  792.     for(int i=0;i<methodsRead;i++){
  793.       Main.print("Method:"+i+" has value:"+methods[i]);      
  794.     }
  795.    
  796.     //next we return to the c;lient the following response: ver:5 and methods:0 (NO AUTHENTICATION REQUIRED)
  797.     out.write(new byte[]{5,0});
  798.    
  799.    
  800.     //entering the subnegotiations
  801.     Main.print("Entering the subnegotiations");
  802.            
  803.     version=(byte)in.read();    
  804.     Main.print("Version of socks is:"+version);
  805.    
  806.     if(version!=5){
  807.       throw new InternalError("Must be SOCKS version 5. Thats what you said at first !!!!!!.");
  808.     }
  809.     //cmd byte
  810.     byte cmd=(byte)in.read();
  811.     Main.print("Received CMD byte:"+cmd);
  812.     switch(cmd){
  813.       case 1:
  814.         Main.print("CONNECT");
  815.         break;
  816.       case 2:
  817.         Main.print("BIND");
  818.         break;
  819.       case 3:
  820.         Main.print("UDP CONNECTION");
  821.         break;        
  822.     }
  823.    
  824.     byte rsv=(byte)in.read(); //reserved byte
  825.    
  826.     byte atyp=(byte)in.read(); //type of adress
  827.     Main.print("Received ATYP byte:"+atyp);
  828.     byte[] dst_addr=null;
  829.     String domainName=null; //used if we will receive a domain name
  830.     switch(atyp){
  831.       case 1:
  832.         Main.print("IPV4");
  833.         dst_addr=new byte[4];
  834.         in.read(dst_addr);      
  835.         break;
  836.       case 3:
  837.         Main.print("DOMAIN NAME");
  838.         byte nrOfDomainBytes=(byte)in.read(); //nr of bytes witch compose the domain name
  839.         byte[] domain=new byte[nrOfDomainBytes];
  840.         int domainLength=in.read(domain);        
  841.         domainName=new String(domain,0,domainLength);
  842.         Main.print("Domain read:"+domainName);
  843.         break;
  844.       case 4:
  845.         Main.print("IPV6");
  846.         throw new InternalError("IPV6 !!!!!!!!");            
  847.     }
  848.    
  849.     byte[] dst_port=new byte[2];
  850.     in.read(dst_port);
  851.    
  852.    //network byte order decoder.
  853.     int port = dst_port[1] & 0xFF;
  854.     port     |= ((dst_port[0]<<8) & 0xFF00);
  855.  
  856.     Main.print("DST_PORT:"+port);
  857.    
  858.     InetAddress the_requested_address=null;
  859.    
  860.     if(dst_addr!=null){
  861.     int address  = dst_addr[3] & 0xFF;
  862.     address |= ((dst_addr[2] << 8) & 0xFF00);
  863.     address |= ((dst_addr[1] << 16) & 0xFF0000);
  864.     address |= ((dst_addr[0] << 24) & 0xFF000000);
  865.      
  866.       the_requested_address=InetAddress.getByName(((address >>> 24) & 0xFF) + "." +
  867.                 ((address >>> 16) & 0xFF) + "." +
  868.                 ((address >>>  8) & 0xFF) + "." +
  869.                 ((address >>>  0) & 0xFF));
  870.     }else{
  871.       the_requested_address=InetAddress.getByName(domainName);
  872.     }
  873.    
  874.     byte[] determined_ip=new byte[4];
  875.     //it could be the IP we've just received, or the IP determined by the domain name.
  876.     determined_ip=the_requested_address.getAddress();
  877.     //reply SUCCESS no matter what, for now
  878.     out.write(new byte[]{5,0,0,1,determined_ip[0],determined_ip[1],determined_ip[2],determined_ip[3],dst_port[0],dst_port[1]});
  879.    
  880.     //next we must connect to a server witch must connect us to where we want . This is where PHP comes in
  881.     Socket toServerSocket=new Socket(the_requested_address,port);
  882.    
  883.     //start a thread that connects us to the application, and the other end
  884.     talk(in,out,toServerSocket.getInputStream(),toServerSocket.getOutputStream());  
  885.   }  
  886.  
  887.   /**
  888.    * This method simply passes the bytes received from one part to another
  889.    * @throws Exception
  890.    */
  891.   private void talk(final InputStream clientIn,final OutputStream clientOut,final InputStream serverIn,final OutputStream serverOut) throws Exception{
  892.      
  893.       //pass to server what client says  
  894.       new Thread(new Runnable(){
  895.         public void run(){
  896.           try{
  897.           int read=1;
  898.           while(read>=0){
  899.             read=clientIn.read();
  900.             serverOut.write(read);
  901.           }
  902.           }catch(Exception e){e.printStackTrace();}
  903.           finally{
  904.             try{
  905.               clientIn.close();
  906.               serverOut.close();
  907.             }catch(Exception ignored){}
  908.           }
  909.         }
  910.       }).start();
  911.      
  912.  
  913.       //pass to client what server says
  914.       new Thread(new Runnable(){
  915.         public void run(){
  916.         try{
  917.           int read=1;
  918.           while(read>=0){
  919.             read=serverIn.read();
  920.             clientOut.write(read);
  921.           }
  922.         }catch(Exception e){e.printStackTrace();}
  923.           finally{
  924.             try{
  925.               serverIn.close();
  926.               clientOut.close();
  927.             }catch(Exception ignored){}
  928.           }
  929.        
  930.         }
  931.       }).start();
  932.   }
  933.  
  934.   public static void main(String[] args) {
  935.     Main main1 = new Main();
  936.   }
  937.  
  938.   private static void print(Object o){
  939.     System.err.println(o);
  940.   }
  941. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement