1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.vfs2.provider.sftp;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.net.Socket;
24
25 import org.apache.commons.vfs2.FileSystemOptions;
26
27 import com.jcraft.jsch.ChannelExec;
28 import com.jcraft.jsch.Proxy;
29 import com.jcraft.jsch.Session;
30 import com.jcraft.jsch.SocketFactory;
31
32
33
34
35
36
37
38
39
40
41 public class SftpStreamProxy implements Proxy {
42
43
44
45 public static final String BASH_TCP_COMMAND = "/bin/bash -c 'exec 3<>/dev/tcp/%s/%d; cat <&3 & cat >&3; kill $!";
46
47
48
49
50 public static final String NETCAT_COMMAND = "nc -q 0 %s %d";
51
52 private ChannelExec channel;
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74 private final String commandFormat;
75
76
77
78
79 private final String proxyHost;
80
81
82
83
84 private final FileSystemOptions proxyOptions;
85
86
87
88
89 private final String proxyPassword;
90
91
92
93
94 private final int proxyPort;
95
96
97
98
99 private final String proxyUser;
100
101 private Session session;
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116 public SftpStreamProxy(final String commandFormat, final String proxyUser, final String proxyHost,
117 final int proxyPort, final String proxyPassword, final FileSystemOptions proxyOptions) {
118 this.proxyHost = proxyHost;
119 this.proxyPort = proxyPort;
120 this.proxyUser = proxyUser;
121 this.proxyPassword = proxyPassword;
122 this.commandFormat = commandFormat;
123 this.proxyOptions = proxyOptions;
124 }
125
126 @Override
127 public void close() {
128 if (channel != null) {
129 channel.disconnect();
130 }
131 if (session != null) {
132 session.disconnect();
133 }
134 }
135
136 @Override
137 public void connect(final SocketFactory socketFactory, final String targetHost, final int targetPort,
138 final int timeout) throws Exception {
139 session = SftpClientFactory.createConnection(proxyHost, proxyPort, proxyUser.toCharArray(),
140 proxyPassword.toCharArray(), proxyOptions);
141 channel = (ChannelExec) session.openChannel("exec");
142 channel.setCommand(String.format(commandFormat, targetHost, targetPort));
143 channel.connect(timeout);
144 }
145
146 @Override
147 public InputStream getInputStream() {
148 try {
149 return channel.getInputStream();
150 } catch (final IOException e) {
151 throw new IllegalStateException("IOException getting the SSH proxy input stream", e);
152 }
153 }
154
155 @Override
156 public OutputStream getOutputStream() {
157 try {
158 return channel.getOutputStream();
159 } catch (final IOException e) {
160 throw new IllegalStateException("IOException getting the SSH proxy output stream", e);
161 }
162 }
163
164 @Override
165 public Socket getSocket() {
166 return null;
167 }
168 }