001/* 002 * 003 * Copyright the original author or authors 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smackx.bytestreams.socks5; 018 019import java.io.DataInputStream; 020import java.io.DataOutputStream; 021import java.io.IOException; 022import java.net.InetSocketAddress; 023import java.net.Socket; 024import java.net.SocketAddress; 025import java.nio.charset.StandardCharsets; 026import java.util.Arrays; 027import java.util.concurrent.Callable; 028import java.util.concurrent.ExecutionException; 029import java.util.concurrent.FutureTask; 030import java.util.concurrent.TimeUnit; 031import java.util.concurrent.TimeoutException; 032import java.util.logging.Logger; 033 034import org.jivesoftware.smack.SmackException.NoResponseException; 035import org.jivesoftware.smack.SmackException.NotConnectedException; 036import org.jivesoftware.smack.SmackException.SmackMessageException; 037import org.jivesoftware.smack.XMPPException; 038import org.jivesoftware.smack.util.Async; 039import org.jivesoftware.smack.util.CloseableUtil; 040 041import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost; 042 043/** 044 * The SOCKS5 client class handles establishing a connection to a SOCKS5 proxy. Connecting to a 045 * SOCKS5 proxy requires authentication. This implementation only supports the no-authentication 046 * authentication method. 047 * 048 * @author Henning Staib 049 */ 050public class Socks5Client { 051 052 private static final Logger LOGGER = Logger.getLogger(Socks5Client.class.getName()); 053 054 /* stream host containing network settings and name of the SOCKS5 proxy */ 055 protected StreamHost streamHost; 056 057 /* SHA-1 digest identifying the SOCKS5 stream */ 058 protected String digest; 059 060 /** 061 * Constructor for a SOCKS5 client. 062 * 063 * @param streamHost containing network settings of the SOCKS5 proxy 064 * @param digest identifying the SOCKS5 Bytestream 065 */ 066 public Socks5Client(StreamHost streamHost, String digest) { 067 this.streamHost = streamHost; 068 this.digest = digest; 069 } 070 071 /** 072 * Returns the initialized socket that can be used to transfer data between peers via the SOCKS5 073 * proxy. 074 * 075 * @param timeout timeout to connect to SOCKS5 proxy in milliseconds 076 * @return socket the initialized socket 077 * @throws IOException if initializing the socket failed due to a network error 078 * @throws TimeoutException if connecting to SOCKS5 proxy timed out 079 * @throws InterruptedException if the current thread was interrupted while waiting 080 * @throws XMPPException if an XMPP protocol error was received. 081 * @throws SmackMessageException if there was an error. 082 * @throws NotConnectedException if the XMPP connection is not connected. 083 * @throws NoResponseException if there was no response from the remote entity. 084 */ 085 public Socket getSocket(int timeout) throws IOException, InterruptedException, 086 TimeoutException, XMPPException, SmackMessageException, NotConnectedException, NoResponseException { 087 // wrap connecting in future for timeout 088 FutureTask<Socket> futureTask = new FutureTask<>(new Callable<Socket>() { 089 090 @Override 091 public Socket call() throws IOException, SmackMessageException { 092 093 // initialize socket 094 Socket socket = new Socket(); 095 SocketAddress socketAddress = new InetSocketAddress(streamHost.getAddress().asInetAddress(), 096 streamHost.getPort()); 097 socket.connect(socketAddress); 098 099 // initialize connection to SOCKS5 proxy 100 try { 101 establish(socket); 102 } 103 catch (IOException e) { 104 if (!socket.isClosed()) { 105 CloseableUtil.maybeClose(socket, LOGGER); 106 } 107 throw e; 108 } 109 110 return socket; 111 } 112 113 }); 114 Async.go(futureTask, "SOCKS5 client connecting to " + streamHost); 115 116 // get connection to initiator with timeout 117 try { 118 return futureTask.get(timeout, TimeUnit.MILLISECONDS); 119 } 120 catch (ExecutionException e) { 121 var causingException = e.getCause(); 122 if (causingException instanceof IOException) 123 throw (IOException) causingException; 124 throw new IOException("ExecutionException while SOCKS5 client attempting to connect to " + streamHost, e); 125 } 126 127 } 128 129 /** 130 * Initializes the connection to the SOCKS5 proxy by negotiating authentication method and 131 * requesting a stream for the given digest. Currently only the no-authentication method is 132 * supported by the Socks5Client. 133 * 134 * @param socket connected to a SOCKS5 proxy 135 * @throws IOException if an I/O error occurred. 136 */ 137 protected void establish(Socket socket) throws IOException { 138 139 byte[] connectionRequest; 140 byte[] connectionResponse; 141 /* 142 * use DataInputStream/DataOutputStream to assure read and write is completed in a single 143 * statement 144 */ 145 DataInputStream in = new DataInputStream(socket.getInputStream()); 146 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); 147 148 // authentication negotiation 149 byte[] cmd = new byte[3]; 150 151 cmd[0] = (byte) 0x05; // protocol version 5 152 cmd[1] = (byte) 0x01; // number of authentication methods supported 153 cmd[2] = (byte) 0x00; // authentication method: no-authentication required 154 155 out.write(cmd); 156 out.flush(); 157 158 byte[] response = new byte[2]; 159 in.readFully(response); 160 161 // check if server responded with correct version and no-authentication method 162 if (response[0] != (byte) 0x05 || response[1] != (byte) 0x00) { 163 throw new IOException("Remote SOCKS5 server responded with unexpected version: " + response[0] + ' ' + response[1] + ". Should be 0x05 0x00."); 164 } 165 166 // request SOCKS5 connection with given address/digest 167 connectionRequest = createSocks5ConnectRequest(); 168 out.write(connectionRequest); 169 out.flush(); 170 171 // receive response 172 connectionResponse = Socks5Utils.receiveSocks5Message(in); 173 174 // verify response 175 connectionRequest[1] = (byte) 0x00; // set expected return status to 0 176 if (!Arrays.equals(connectionRequest, connectionResponse)) { 177 throw new IOException( 178 "Connection request does not equal connection response. Response: " 179 + Arrays.toString(connectionResponse) + ". Request: " 180 + Arrays.toString(connectionRequest)); 181 } 182 } 183 184 /** 185 * Returns a SOCKS5 connection request message. It contains the command "connect", the address 186 * type "domain" and the digest as address. 187 * <p> 188 * (see <a href="http://tools.ietf.org/html/rfc1928">RFC1928</a>) 189 * 190 * @return SOCKS5 connection request message 191 */ 192 private byte[] createSocks5ConnectRequest() { 193 byte[] addr = digest.getBytes(StandardCharsets.UTF_8); 194 195 byte[] data = new byte[7 + addr.length]; 196 data[0] = (byte) 0x05; // version (SOCKS5) 197 data[1] = (byte) 0x01; // command (1 - connect) 198 data[2] = (byte) 0x00; // reserved byte (always 0) 199 data[3] = (byte) 0x03; // address type (3 - domain name) 200 data[4] = (byte) addr.length; // address length 201 System.arraycopy(addr, 0, data, 5, addr.length); // address 202 data[data.length - 2] = (byte) 0; // address port (2 bytes always 0) 203 data[data.length - 1] = (byte) 0; 204 205 return data; 206 } 207 208}