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 private final String commandFormat;
73
74
75
76
77 private final String proxyHost;
78
79
80
81
82 private final FileSystemOptions proxyOptions;
83
84
85
86
87 private final String proxyPassword;
88
89
90
91
92 private final int proxyPort;
93
94
95
96
97 private final String proxyUser;
98
99 private Session session;
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114 public SftpStreamProxy(final String commandFormat, final String proxyUser, final String proxyHost,
115 final int proxyPort, final String proxyPassword, final FileSystemOptions proxyOptions) {
116 this.proxyHost = proxyHost;
117 this.proxyPort = proxyPort;
118 this.proxyUser = proxyUser;
119 this.proxyPassword = proxyPassword;
120 this.commandFormat = commandFormat;
121 this.proxyOptions = proxyOptions;
122 }
123
124 @Override
125 public void close() {
126 if (channel != null) {
127 channel.disconnect();
128 }
129 if (session != null) {
130 session.disconnect();
131 }
132 }
133
134 @Override
135 public void connect(final SocketFactory socketFactory, final String targetHost, final int targetPort,
136 final int timeout) throws Exception {
137 session = SftpClientFactory.createConnection(proxyHost, proxyPort, proxyUser.toCharArray(),
138 proxyPassword.toCharArray(), proxyOptions);
139 channel = (ChannelExec) session.openChannel("exec");
140 channel.setCommand(String.format(commandFormat, targetHost, targetPort));
141 channel.connect(timeout);
142 }
143
144 @Override
145 public InputStream getInputStream() {
146 try {
147 return channel.getInputStream();
148 } catch (final IOException e) {
149 throw new IllegalStateException("IOException getting the SSH proxy input stream", e);
150 }
151 }
152
153 @Override
154 public OutputStream getOutputStream() {
155 try {
156 return channel.getOutputStream();
157 } catch (final IOException e) {
158 throw new IllegalStateException("IOException getting the SSH proxy output stream", e);
159 }
160 }
161
162 @Override
163 public Socket getSocket() {
164 return null;
165 }
166 }