0
|
1 /*
|
|
2 * ConnectBot: simple, powerful, open-source SSH client for Android
|
|
3 * Copyright 2007 Kenny Root, Jeffrey Sharkey
|
|
4 *
|
|
5 * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6 * you may not use this file except in compliance with the License.
|
|
7 * You may obtain a copy of the License at
|
|
8 *
|
|
9 * http://www.apache.org/licenses/LICENSE-2.0
|
|
10 *
|
|
11 * Unless required by applicable law or agreed to in writing, software
|
|
12 * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14 * See the License for the specific language governing permissions and
|
|
15 * limitations under the License.
|
|
16 */
|
|
17
|
|
18 package com.five_ten_sg.connectbot.transport;
|
|
19
|
|
20 import java.io.File;
|
|
21 import java.io.IOException;
|
|
22 import java.io.InputStream;
|
|
23 import java.io.OutputStream;
|
|
24 import java.net.InetAddress;
|
|
25 import java.net.InetSocketAddress;
|
|
26 import java.net.URL;
|
|
27 import java.net.MalformedURLException;
|
|
28 import java.security.KeyPair;
|
|
29 import java.security.NoSuchAlgorithmException;
|
|
30 import java.security.PrivateKey;
|
|
31 import java.security.PublicKey;
|
|
32 import java.security.interfaces.DSAPrivateKey;
|
|
33 import java.security.interfaces.DSAPublicKey;
|
|
34 import java.security.interfaces.RSAPrivateKey;
|
|
35 import java.security.interfaces.RSAPublicKey;
|
|
36 import java.security.spec.InvalidKeySpecException;
|
|
37 import java.util.Arrays;
|
|
38 import java.util.HashMap;
|
|
39 import java.util.LinkedList;
|
|
40 import java.util.List;
|
|
41 import java.util.Locale;
|
|
42 import java.util.Map;
|
|
43 import java.util.Map.Entry;
|
|
44 import java.util.regex.Matcher;
|
|
45 import java.util.regex.Pattern;
|
|
46
|
|
47 import com.five_ten_sg.connectbot.R;
|
|
48 import com.five_ten_sg.connectbot.bean.HostBean;
|
|
49 import com.five_ten_sg.connectbot.bean.PortForwardBean;
|
|
50 import com.five_ten_sg.connectbot.bean.PubkeyBean;
|
|
51 import com.five_ten_sg.connectbot.service.TerminalBridge;
|
|
52 import com.five_ten_sg.connectbot.service.TerminalManager;
|
|
53 import com.five_ten_sg.connectbot.service.TerminalManager.KeyHolder;
|
|
54 import com.five_ten_sg.connectbot.util.HostDatabase;
|
|
55 import com.five_ten_sg.connectbot.util.PubkeyDatabase;
|
|
56 import com.five_ten_sg.connectbot.util.PubkeyUtils;
|
|
57 import android.content.Context;
|
|
58 import android.net.Uri;
|
|
59 import android.os.Environment;
|
|
60 import android.util.Log;
|
|
61
|
|
62 import com.trilead.ssh2.AuthAgentCallback;
|
|
63 import com.trilead.ssh2.ChannelCondition;
|
|
64 import com.trilead.ssh2.Connection;
|
|
65 import com.trilead.ssh2.ConnectionInfo;
|
|
66 import com.trilead.ssh2.ConnectionMonitor;
|
|
67 import com.trilead.ssh2.DynamicPortForwarder;
|
|
68 import com.trilead.ssh2.InteractiveCallback;
|
|
69 import com.trilead.ssh2.KnownHosts;
|
|
70 import com.trilead.ssh2.LocalPortForwarder;
|
|
71 import com.trilead.ssh2.SCPClient;
|
|
72 import com.trilead.ssh2.ServerHostKeyVerifier;
|
|
73 import com.trilead.ssh2.Session;
|
|
74 import com.trilead.ssh2.HTTPProxyData;
|
|
75 import com.trilead.ssh2.HTTPProxyException;
|
|
76 import com.trilead.ssh2.crypto.PEMDecoder;
|
|
77 import com.trilead.ssh2.signature.DSASHA1Verify;
|
|
78 import com.trilead.ssh2.signature.RSASHA1Verify;
|
|
79
|
|
80 /**
|
|
81 * @author Kenny Root
|
|
82 *
|
|
83 */
|
|
84 public class SSH extends AbsTransport implements ConnectionMonitor, InteractiveCallback, AuthAgentCallback {
|
|
85 public SSH() {
|
|
86 super();
|
|
87 }
|
|
88
|
|
89 /**
|
8
|
90 * @param host
|
0
|
91 * @param bridge
|
8
|
92 * @param manager
|
0
|
93 */
|
|
94 public SSH(HostBean host, TerminalBridge bridge, TerminalManager manager) {
|
|
95 super(host, bridge, manager);
|
|
96 }
|
|
97
|
|
98 private static final String PROTOCOL = "ssh";
|
|
99 private static final String TAG = "ConnectBot.SSH";
|
|
100 private static final int DEFAULT_PORT = 22;
|
|
101
|
|
102 private static final String AUTH_PUBLICKEY = "publickey",
|
|
103 AUTH_PASSWORD = "password",
|
|
104 AUTH_KEYBOARDINTERACTIVE = "keyboard-interactive";
|
|
105
|
|
106 private final static int AUTH_TRIES = 20;
|
|
107
|
|
108 static final Pattern hostmask;
|
|
109 static {
|
|
110 hostmask = Pattern.compile("^(.+)@([0-9a-z.-]+)(:(\\d+))?$", Pattern.CASE_INSENSITIVE);
|
|
111 }
|
|
112
|
|
113 private boolean compression = false;
|
|
114 private String httpproxy = null;
|
|
115 private volatile boolean authenticated = false;
|
|
116 private volatile boolean connected = false;
|
|
117 private volatile boolean sessionOpen = false;
|
|
118
|
|
119 private boolean pubkeysExhausted = false;
|
|
120 private boolean interactiveCanContinue = true;
|
|
121
|
|
122 private Connection connection;
|
|
123 private Session session;
|
|
124 private ConnectionInfo connectionInfo;
|
|
125
|
|
126 private OutputStream stdin;
|
|
127 private InputStream stdout;
|
|
128 private InputStream stderr;
|
|
129
|
|
130 private static final int conditions = ChannelCondition.STDOUT_DATA
|
|
131 | ChannelCondition.STDERR_DATA
|
|
132 | ChannelCondition.CLOSED
|
|
133 | ChannelCondition.EOF;
|
|
134
|
|
135 private List<PortForwardBean> portForwards = new LinkedList<PortForwardBean>();
|
|
136
|
|
137 private int columns;
|
|
138 private int rows;
|
|
139
|
|
140 private int width;
|
|
141 private int height;
|
|
142
|
|
143 private String useAuthAgent = HostDatabase.AUTHAGENT_NO;
|
|
144 private String agentLockPassphrase;
|
|
145
|
|
146 public class HostKeyVerifier implements ServerHostKeyVerifier {
|
|
147 public boolean verifyServerHostKey(String hostname, int port,
|
|
148 String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException {
|
|
149 // read in all known hosts from hostdb
|
|
150 KnownHosts hosts = manager.hostdb.getKnownHosts();
|
|
151 Boolean result;
|
|
152 String matchName = String.format(Locale.US, "%s:%d", hostname, port);
|
|
153 String fingerprint = KnownHosts.createHexFingerprint(serverHostKeyAlgorithm, serverHostKey);
|
|
154 String algorithmName;
|
|
155
|
|
156 if ("ssh-rsa".equals(serverHostKeyAlgorithm))
|
|
157 algorithmName = "RSA";
|
|
158 else if ("ssh-dss".equals(serverHostKeyAlgorithm))
|
|
159 algorithmName = "DSA";
|
|
160 else if (serverHostKeyAlgorithm.startsWith("ecdsa-"))
|
|
161 algorithmName = "EC";
|
|
162 else
|
|
163 algorithmName = serverHostKeyAlgorithm;
|
|
164
|
|
165 switch (hosts.verifyHostkey(matchName, serverHostKeyAlgorithm, serverHostKey)) {
|
|
166 case KnownHosts.HOSTKEY_IS_OK:
|
|
167 bridge.outputLine(manager.res.getString(R.string.terminal_sucess, algorithmName, fingerprint));
|
|
168 return true;
|
|
169
|
|
170 case KnownHosts.HOSTKEY_IS_NEW:
|
|
171 // prompt user
|
|
172 bridge.outputLine(manager.res.getString(R.string.host_authenticity_warning, hostname));
|
|
173 bridge.outputLine(manager.res.getString(R.string.host_fingerprint, algorithmName, fingerprint));
|
|
174 result = bridge.promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting));
|
|
175
|
|
176 if (result == null) return false;
|
|
177
|
|
178 if (result.booleanValue()) {
|
|
179 // save this key in known database
|
|
180 manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey);
|
|
181 }
|
|
182
|
|
183 return result.booleanValue();
|
|
184
|
|
185 case KnownHosts.HOSTKEY_HAS_CHANGED:
|
|
186 String header = String.format("@ %s @",
|
|
187 manager.res.getString(R.string.host_verification_failure_warning_header));
|
|
188 char[] atsigns = new char[header.length()];
|
|
189 Arrays.fill(atsigns, '@');
|
|
190 String border = new String(atsigns);
|
|
191 bridge.outputLine(border);
|
|
192 bridge.outputLine(manager.res.getString(R.string.host_verification_failure_warning));
|
|
193 bridge.outputLine(border);
|
|
194 bridge.outputLine(String.format(manager.res.getString(R.string.host_fingerprint),
|
|
195 algorithmName, fingerprint));
|
|
196 // Users have no way to delete keys, so we'll prompt them for now.
|
|
197 result = bridge.promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting));
|
|
198
|
|
199 if (result == null) return false;
|
|
200
|
|
201 if (result.booleanValue()) {
|
|
202 // save this key in known database
|
|
203 manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey);
|
|
204 }
|
|
205
|
|
206 return result.booleanValue();
|
|
207
|
|
208 default:
|
|
209 return false;
|
|
210 }
|
|
211 }
|
|
212
|
|
213 }
|
|
214
|
|
215 private void authenticate() {
|
|
216 try {
|
|
217 if (connection.authenticateWithNone(host.getUsername())) {
|
|
218 finishConnection();
|
|
219 return;
|
|
220 }
|
|
221 }
|
|
222 catch (Exception e) {
|
|
223 Log.d(TAG, "Host does not support 'none' authentication.");
|
|
224 }
|
|
225
|
|
226 bridge.outputLine(manager.res.getString(R.string.terminal_auth));
|
|
227
|
|
228 try {
|
|
229 long pubkeyId = host.getPubkeyId();
|
|
230
|
|
231 if (!pubkeysExhausted &&
|
|
232 pubkeyId != HostDatabase.PUBKEYID_NEVER &&
|
|
233 connection.isAuthMethodAvailable(host.getUsername(), AUTH_PUBLICKEY)) {
|
|
234 // if explicit pubkey defined for this host, then prompt for password as needed
|
|
235 // otherwise just try all in-memory keys held in terminalmanager
|
|
236 if (pubkeyId == HostDatabase.PUBKEYID_ANY) {
|
|
237 // try each of the in-memory keys
|
|
238 bridge.outputLine(manager.res
|
|
239 .getString(R.string.terminal_auth_pubkey_any));
|
|
240
|
|
241 for (Entry<String, KeyHolder> entry : manager.loadedKeypairs.entrySet()) {
|
|
242 if (entry.getValue().bean.isConfirmUse()
|
|
243 && !promptForPubkeyUse(entry.getKey()))
|
|
244 continue;
|
|
245
|
|
246 if (this.tryPublicKey(host.getUsername(), entry.getKey(),
|
|
247 entry.getValue().pair)) {
|
|
248 finishConnection();
|
|
249 break;
|
|
250 }
|
|
251 }
|
|
252 }
|
|
253 else {
|
|
254 bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_specific));
|
|
255 // use a specific key for this host, as requested
|
|
256 PubkeyBean pubkey = manager.pubkeydb.findPubkeyById(pubkeyId);
|
|
257
|
|
258 if (pubkey == null)
|
|
259 bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_invalid));
|
|
260 else if (tryPublicKey(pubkey))
|
|
261 finishConnection();
|
|
262 }
|
|
263
|
|
264 pubkeysExhausted = true;
|
|
265 }
|
|
266 else if (interactiveCanContinue &&
|
|
267 connection.isAuthMethodAvailable(host.getUsername(), AUTH_KEYBOARDINTERACTIVE)) {
|
|
268 // this auth method will talk with us using InteractiveCallback interface
|
|
269 // it blocks until authentication finishes
|
|
270 bridge.outputLine(manager.res.getString(R.string.terminal_auth_ki));
|
|
271 interactiveCanContinue = false;
|
|
272
|
|
273 if (connection.authenticateWithKeyboardInteractive(host.getUsername(), this)) {
|
|
274 finishConnection();
|
|
275 }
|
|
276 else {
|
|
277 bridge.outputLine(manager.res.getString(R.string.terminal_auth_ki_fail));
|
|
278 }
|
|
279 }
|
|
280 else if (connection.isAuthMethodAvailable(host.getUsername(), AUTH_PASSWORD)) {
|
|
281 bridge.outputLine(manager.res.getString(R.string.terminal_auth_pass));
|
|
282 String password = bridge.getPromptHelper().requestPasswordPrompt(null,
|
|
283 manager.res.getString(R.string.prompt_password));
|
|
284
|
|
285 if (password != null
|
|
286 && connection.authenticateWithPassword(host.getUsername(), password)) {
|
|
287 finishConnection();
|
|
288 }
|
|
289 else {
|
|
290 bridge.outputLine(manager.res.getString(R.string.terminal_auth_pass_fail));
|
|
291 }
|
|
292 }
|
|
293 else {
|
|
294 bridge.outputLine(manager.res.getString(R.string.terminal_auth_fail));
|
|
295 }
|
|
296 }
|
|
297 catch (IllegalStateException e) {
|
|
298 Log.e(TAG, "Connection went away while we were trying to authenticate", e);
|
|
299 return;
|
|
300 }
|
|
301 catch (Exception e) {
|
|
302 Log.e(TAG, "Problem during handleAuthentication()", e);
|
|
303 }
|
|
304 }
|
|
305
|
|
306 /**
|
|
307 * Attempt connection with database row pointed to by cursor.
|
|
308 * @param cursor
|
|
309 * @return true for successful authentication
|
|
310 * @throws NoSuchAlgorithmException
|
|
311 * @throws InvalidKeySpecException
|
|
312 * @throws IOException
|
|
313 */
|
|
314 private boolean tryPublicKey(PubkeyBean pubkey) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
|
|
315 KeyPair pair = null;
|
|
316
|
|
317 if (manager.isKeyLoaded(pubkey.getNickname())) {
|
|
318 // load this key from memory if its already there
|
|
319 Log.d(TAG, String.format("Found unlocked key '%s' already in-memory", pubkey.getNickname()));
|
|
320
|
|
321 if (pubkey.isConfirmUse()) {
|
|
322 if (!promptForPubkeyUse(pubkey.getNickname()))
|
|
323 return false;
|
|
324 }
|
|
325
|
|
326 pair = manager.getKey(pubkey.getNickname());
|
|
327 }
|
|
328 else {
|
|
329 // otherwise load key from database and prompt for password as needed
|
|
330 String password = null;
|
|
331
|
|
332 if (pubkey.isEncrypted()) {
|
|
333 password = bridge.getPromptHelper().requestPasswordPrompt(null,
|
|
334 manager.res.getString(R.string.prompt_pubkey_password, pubkey.getNickname()));
|
|
335
|
|
336 // Something must have interrupted the prompt.
|
|
337 if (password == null)
|
|
338 return false;
|
|
339 }
|
|
340
|
|
341 if (PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) {
|
|
342 // load specific key using pem format
|
|
343 pair = PEMDecoder.decode(new String(pubkey.getPrivateKey()).toCharArray(), password);
|
|
344 }
|
|
345 else {
|
|
346 // load using internal generated format
|
|
347 PrivateKey privKey;
|
|
348
|
|
349 try {
|
|
350 privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(),
|
|
351 pubkey.getType(), password);
|
|
352 }
|
|
353 catch (Exception e) {
|
|
354 String message = String.format("Bad password for key '%s'. Authentication failed.", pubkey.getNickname());
|
|
355 Log.e(TAG, message, e);
|
|
356 bridge.outputLine(message);
|
|
357 return false;
|
|
358 }
|
|
359
|
|
360 PublicKey pubKey = PubkeyUtils.decodePublic(pubkey.getPublicKey(), pubkey.getType());
|
|
361 // convert key to trilead format
|
|
362 pair = new KeyPair(pubKey, privKey);
|
|
363 Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey));
|
|
364 }
|
|
365
|
|
366 Log.d(TAG, String.format("Unlocked key '%s'", pubkey.getNickname()));
|
|
367 // save this key in memory
|
|
368 manager.addKey(pubkey, pair);
|
|
369 }
|
|
370
|
|
371 return tryPublicKey(host.getUsername(), pubkey.getNickname(), pair);
|
|
372 }
|
|
373
|
|
374 private boolean tryPublicKey(String username, String keyNickname, KeyPair pair) throws IOException {
|
|
375 //bridge.outputLine(String.format("Attempting 'publickey' with key '%s' [%s]...", keyNickname, trileadKey.toString()));
|
|
376 boolean success = connection.authenticateWithPublicKey(username, pair);
|
|
377
|
|
378 if (!success)
|
|
379 bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_fail, keyNickname));
|
|
380
|
|
381 return success;
|
|
382 }
|
|
383
|
|
384 /**
|
|
385 * Internal method to request actual PTY terminal once we've finished
|
|
386 * authentication. If called before authenticated, it will just fail.
|
|
387 */
|
|
388 private void finishConnection() {
|
|
389 authenticated = true;
|
|
390
|
|
391 for (PortForwardBean portForward : portForwards) {
|
|
392 try {
|
|
393 enablePortForward(portForward);
|
|
394 bridge.outputLine(manager.res.getString(R.string.terminal_enable_portfoward, portForward.getDescription()));
|
|
395 }
|
|
396 catch (Exception e) {
|
|
397 Log.e(TAG, "Error setting up port forward during connect", e);
|
|
398 }
|
|
399 }
|
|
400
|
|
401 if (!host.getWantSession()) {
|
|
402 bridge.outputLine(manager.res.getString(R.string.terminal_no_session));
|
|
403 bridge.onConnected();
|
|
404 return;
|
|
405 }
|
|
406
|
|
407 try {
|
|
408 session = connection.openSession();
|
|
409
|
|
410 if (!useAuthAgent.equals(HostDatabase.AUTHAGENT_NO))
|
|
411 session.requestAuthAgentForwarding(this);
|
|
412
|
|
413 if (host.getWantX11Forward()) {
|
|
414 try {
|
|
415 session.requestX11Forwarding(host.getX11Host(), host.getX11Port(), null, false);
|
|
416 }
|
|
417 catch (IOException e2) {
|
|
418 Log.e(TAG, "Problem while trying to setup X11 forwarding in finishConnection()", e2);
|
|
419 }
|
|
420 }
|
|
421
|
|
422 session.requestPTY(getEmulation(), columns, rows, width, height, null);
|
|
423 session.startShell();
|
|
424 stdin = session.getStdin();
|
|
425 stdout = session.getStdout();
|
|
426 stderr = session.getStderr();
|
|
427 sessionOpen = true;
|
|
428 bridge.onConnected();
|
|
429 }
|
|
430 catch (IOException e1) {
|
|
431 Log.e(TAG, "Problem while trying to create PTY in finishConnection()", e1);
|
|
432 }
|
|
433 }
|
|
434
|
|
435 @Override
|
|
436 public void connect() {
|
|
437 connection = new Connection(host.getHostname(), host.getPort());
|
|
438 connection.addConnectionMonitor(this);
|
|
439
|
|
440 try {
|
|
441 connection.setCompression(compression);
|
|
442 }
|
|
443 catch (IOException e) {
|
|
444 Log.e(TAG, "Could not enable compression!", e);
|
|
445 }
|
|
446
|
|
447 if (httpproxy != null && httpproxy.length() > 0) {
|
|
448 Log.d(TAG, "Want HTTP Proxy: " + httpproxy, null);
|
|
449
|
|
450 try {
|
|
451 URL u;
|
|
452
|
|
453 if (httpproxy.startsWith("http://")) {
|
|
454 u = new URL(httpproxy);
|
|
455 }
|
|
456 else {
|
|
457 u = new URL("http://" + httpproxy);
|
|
458 }
|
|
459
|
|
460 connection.setProxyData(new HTTPProxyData(
|
|
461 u.getHost(),
|
|
462 u.getPort(),
|
|
463 u.getUserInfo(),
|
|
464 u.getAuthority()));
|
|
465 bridge.outputLine("Connecting via proxy: " + httpproxy);
|
|
466 }
|
|
467 catch (MalformedURLException e) {
|
|
468 Log.e(TAG, "Could not parse proxy " + httpproxy, e);
|
|
469 // Display the reason in the text.
|
|
470 bridge.outputLine("Bad proxy URL: " + httpproxy);
|
|
471 onDisconnect();
|
|
472 return;
|
|
473 }
|
|
474 }
|
|
475
|
|
476 try {
|
|
477 /* Uncomment when debugging SSH protocol:
|
|
478 DebugLogger logger = new DebugLogger() {
|
|
479
|
|
480 public void log(int level, String className, String message) {
|
|
481 Log.d("SSH", message);
|
|
482 }
|
|
483
|
|
484 };
|
|
485 Logger.enabled = true;
|
|
486 Logger.logger = logger;
|
|
487 */
|
|
488 connectionInfo = connection.connect(new HostKeyVerifier());
|
|
489 connected = true;
|
|
490
|
|
491 if (connectionInfo.clientToServerCryptoAlgorithm
|
|
492 .equals(connectionInfo.serverToClientCryptoAlgorithm)
|
|
493 && connectionInfo.clientToServerMACAlgorithm
|
|
494 .equals(connectionInfo.serverToClientMACAlgorithm)) {
|
|
495 bridge.outputLine(manager.res.getString(R.string.terminal_using_algorithm,
|
|
496 connectionInfo.clientToServerCryptoAlgorithm,
|
|
497 connectionInfo.clientToServerMACAlgorithm));
|
|
498 }
|
|
499 else {
|
|
500 bridge.outputLine(manager.res.getString(
|
|
501 R.string.terminal_using_c2s_algorithm,
|
|
502 connectionInfo.clientToServerCryptoAlgorithm,
|
|
503 connectionInfo.clientToServerMACAlgorithm));
|
|
504 bridge.outputLine(manager.res.getString(
|
|
505 R.string.terminal_using_s2c_algorithm,
|
|
506 connectionInfo.serverToClientCryptoAlgorithm,
|
|
507 connectionInfo.serverToClientMACAlgorithm));
|
|
508 }
|
|
509 }
|
|
510 catch (HTTPProxyException e) {
|
|
511 Log.e(TAG, "Failed to connect to HTTP Proxy", e);
|
|
512 // Display the reason in the text.
|
|
513 bridge.outputLine("Failed to connect to HTTP Proxy.");
|
|
514 onDisconnect();
|
|
515 return;
|
|
516 }
|
|
517 catch (IOException e) {
|
|
518 Log.e(TAG, "Problem in SSH connection thread during authentication", e);
|
|
519 // Display the reason in the text.
|
|
520 bridge.outputLine(e.getCause().getMessage());
|
|
521 onDisconnect();
|
|
522 return;
|
|
523 }
|
|
524
|
|
525 try {
|
|
526 // enter a loop to keep trying until authentication
|
|
527 int tries = 0;
|
|
528
|
|
529 while (connected && !connection.isAuthenticationComplete() && tries++ < AUTH_TRIES) {
|
|
530 authenticate();
|
|
531 // sleep to make sure we dont kill system
|
|
532 Thread.sleep(1000);
|
|
533 }
|
|
534 }
|
|
535 catch (Exception e) {
|
|
536 Log.e(TAG, "Problem in SSH connection thread during authentication", e);
|
|
537 }
|
|
538 }
|
|
539
|
|
540 @Override
|
|
541 public void close() {
|
|
542 connected = false;
|
|
543
|
|
544 if (session != null) {
|
|
545 session.close();
|
|
546 session = null;
|
|
547 }
|
|
548
|
|
549 if (connection != null) {
|
|
550 connection.close();
|
|
551 connection = null;
|
|
552 }
|
|
553 }
|
|
554
|
|
555 private void onDisconnect() {
|
|
556 close();
|
|
557 bridge.dispatchDisconnect(false);
|
|
558 }
|
|
559
|
|
560 @Override
|
|
561 public void flush() throws IOException {
|
|
562 if (stdin != null)
|
|
563 stdin.flush();
|
|
564 }
|
|
565
|
|
566 @Override
|
|
567 public boolean willBlock() {
|
|
568 if (stdout == null) return true;
|
|
569 try {
|
|
570 return stdout.available() == 0;
|
|
571 } catch (Exception e) {
|
|
572 return true;
|
|
573 }
|
|
574 }
|
|
575
|
|
576 @Override
|
|
577 public int read(byte[] buffer, int start, int len) throws IOException {
|
|
578 int bytesRead = 0;
|
|
579
|
|
580 if (session == null)
|
|
581 return 0;
|
|
582
|
|
583 int newConditions = session.waitForCondition(conditions, 0);
|
|
584
|
|
585 if ((newConditions & ChannelCondition.STDOUT_DATA) != 0) {
|
|
586 bytesRead = stdout.read(buffer, start, len);
|
|
587 }
|
|
588
|
|
589 if ((newConditions & ChannelCondition.STDERR_DATA) != 0) {
|
|
590 byte discard[] = new byte[256];
|
|
591
|
|
592 while (stderr.available() > 0) {
|
|
593 stderr.read(discard);
|
|
594 }
|
|
595 }
|
|
596
|
|
597 if ((newConditions & ChannelCondition.EOF) != 0) {
|
|
598 onDisconnect();
|
|
599 throw new IOException("Remote end closed connection");
|
|
600 }
|
|
601
|
|
602 return bytesRead;
|
|
603 }
|
|
604
|
|
605 @Override
|
|
606 public void write(byte[] buffer) throws IOException {
|
|
607 if (stdin != null)
|
|
608 stdin.write(buffer);
|
|
609 }
|
|
610
|
|
611 @Override
|
|
612 public void write(int c) throws IOException {
|
|
613 if (stdin != null)
|
|
614 stdin.write(c);
|
|
615 }
|
|
616
|
|
617 @Override
|
|
618 public Map<String, String> getOptions() {
|
|
619 Map<String, String> options = new HashMap<String, String>();
|
|
620 options.put("compression", Boolean.toString(compression));
|
|
621
|
|
622 if (httpproxy != null)
|
|
623 options.put("httpproxy", httpproxy);
|
|
624
|
|
625 return options;
|
|
626 }
|
|
627
|
|
628 @Override
|
|
629 public void setOptions(Map<String, String> options) {
|
|
630 if (options.containsKey("compression"))
|
|
631 compression = Boolean.parseBoolean(options.get("compression"));
|
|
632
|
|
633 if (options.containsKey("httpproxy"))
|
|
634 httpproxy = options.get("httpproxy");
|
|
635 }
|
|
636
|
11
|
637 /**
|
|
638 * @return protocol part of the URI
|
|
639 */
|
0
|
640 public static String getProtocolName() {
|
|
641 return PROTOCOL;
|
|
642 }
|
|
643
|
|
644 @Override
|
|
645 public boolean isSessionOpen() {
|
|
646 return sessionOpen;
|
|
647 }
|
|
648
|
|
649 @Override
|
|
650 public boolean isConnected() {
|
|
651 return connected;
|
|
652 }
|
|
653
|
|
654 @Override
|
|
655 public boolean isAuthenticated() {
|
|
656 return authenticated;
|
|
657 }
|
|
658
|
|
659 public void connectionLost(Throwable reason) {
|
|
660 onDisconnect();
|
|
661 }
|
|
662
|
|
663 @Override
|
|
664 public boolean canForwardPorts() {
|
|
665 return true;
|
|
666 }
|
|
667
|
|
668 @Override
|
|
669 public List<PortForwardBean> getPortForwards() {
|
|
670 return portForwards;
|
|
671 }
|
|
672
|
|
673 @Override
|
|
674 public boolean addPortForward(PortForwardBean portForward) {
|
|
675 return portForwards.add(portForward);
|
|
676 }
|
|
677
|
|
678 @Override
|
|
679 public boolean removePortForward(PortForwardBean portForward) {
|
|
680 // Make sure we don't have a phantom forwarder.
|
|
681 disablePortForward(portForward);
|
|
682 return portForwards.remove(portForward);
|
|
683 }
|
|
684
|
|
685 @Override
|
|
686 public boolean enablePortForward(PortForwardBean portForward) {
|
|
687 if (!portForwards.contains(portForward)) {
|
|
688 Log.e(TAG, "Attempt to enable port forward not in list");
|
|
689 return false;
|
|
690 }
|
|
691
|
|
692 if (!authenticated)
|
|
693 return false;
|
|
694
|
|
695 if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) {
|
|
696 LocalPortForwarder lpf = null;
|
|
697
|
|
698 try {
|
|
699 lpf = connection.createLocalPortForwarder(
|
|
700 new InetSocketAddress(InetAddress.getLocalHost(), portForward.getSourcePort()),
|
|
701 portForward.getDestAddr(), portForward.getDestPort());
|
|
702 }
|
|
703 catch (Exception e) {
|
|
704 Log.e(TAG, "Could not create local port forward", e);
|
|
705 return false;
|
|
706 }
|
|
707
|
|
708 if (lpf == null) {
|
|
709 Log.e(TAG, "returned LocalPortForwarder object is null");
|
|
710 return false;
|
|
711 }
|
|
712
|
|
713 portForward.setIdentifier(lpf);
|
|
714 portForward.setEnabled(true);
|
|
715 return true;
|
|
716 }
|
|
717 else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) {
|
|
718 try {
|
|
719 connection.requestRemotePortForwarding("", portForward.getSourcePort(), portForward.getDestAddr(), portForward.getDestPort());
|
|
720 }
|
|
721 catch (Exception e) {
|
|
722 Log.e(TAG, "Could not create remote port forward", e);
|
|
723 return false;
|
|
724 }
|
|
725
|
|
726 portForward.setEnabled(true);
|
|
727 return true;
|
|
728 }
|
|
729 else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) {
|
|
730 DynamicPortForwarder dpf = null;
|
|
731
|
|
732 try {
|
|
733 dpf = connection.createDynamicPortForwarder(
|
|
734 new InetSocketAddress(InetAddress.getLocalHost(), portForward.getSourcePort()));
|
|
735 }
|
|
736 catch (Exception e) {
|
|
737 Log.e(TAG, "Could not create dynamic port forward", e);
|
|
738 return false;
|
|
739 }
|
|
740
|
|
741 portForward.setIdentifier(dpf);
|
|
742 portForward.setEnabled(true);
|
|
743 return true;
|
|
744 }
|
|
745 else {
|
|
746 // Unsupported type
|
|
747 Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType()));
|
|
748 return false;
|
|
749 }
|
|
750 }
|
|
751
|
|
752 @Override
|
|
753 public boolean disablePortForward(PortForwardBean portForward) {
|
|
754 if (!portForwards.contains(portForward)) {
|
|
755 Log.e(TAG, "Attempt to disable port forward not in list");
|
|
756 return false;
|
|
757 }
|
|
758
|
|
759 if (!authenticated)
|
|
760 return false;
|
|
761
|
|
762 if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) {
|
|
763 LocalPortForwarder lpf = null;
|
|
764 lpf = (LocalPortForwarder)portForward.getIdentifier();
|
|
765
|
|
766 if (!portForward.isEnabled() || lpf == null) {
|
|
767 Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname()));
|
|
768 return false;
|
|
769 }
|
|
770
|
|
771 portForward.setEnabled(false);
|
|
772
|
|
773 try {
|
|
774 lpf.close();
|
|
775 }
|
|
776 catch (IOException e) {
|
|
777 Log.e(TAG, "Could not stop local port forwarder, setting enabled to false", e);
|
|
778 return false;
|
|
779 }
|
|
780
|
|
781 return true;
|
|
782 }
|
|
783 else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) {
|
|
784 portForward.setEnabled(false);
|
|
785
|
|
786 try {
|
|
787 connection.cancelRemotePortForwarding(portForward.getSourcePort());
|
|
788 }
|
|
789 catch (IOException e) {
|
|
790 Log.e(TAG, "Could not stop remote port forwarding, setting enabled to false", e);
|
|
791 return false;
|
|
792 }
|
|
793
|
|
794 return true;
|
|
795 }
|
|
796 else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) {
|
|
797 DynamicPortForwarder dpf = null;
|
|
798 dpf = (DynamicPortForwarder)portForward.getIdentifier();
|
|
799
|
|
800 if (!portForward.isEnabled() || dpf == null) {
|
|
801 Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname()));
|
|
802 return false;
|
|
803 }
|
|
804
|
|
805 portForward.setEnabled(false);
|
|
806
|
|
807 try {
|
|
808 dpf.close();
|
|
809 }
|
|
810 catch (IOException e) {
|
|
811 Log.e(TAG, "Could not stop dynamic port forwarder, setting enabled to false", e);
|
|
812 return false;
|
|
813 }
|
|
814
|
|
815 return true;
|
|
816 }
|
|
817 else {
|
|
818 // Unsupported type
|
|
819 Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType()));
|
|
820 return false;
|
|
821 }
|
|
822 }
|
|
823
|
|
824 @Override
|
|
825 public boolean canTransferFiles() {
|
|
826 return true;
|
|
827 }
|
|
828
|
|
829 @Override
|
|
830 public boolean downloadFile(String remoteFile, String localFolder) {
|
|
831 try {
|
|
832 SCPClient client = new SCPClient(connection);
|
|
833
|
|
834 if (localFolder == null || localFolder == "")
|
|
835 localFolder = Environment.getExternalStorageDirectory().getAbsolutePath();
|
|
836
|
|
837 File dir = new File(localFolder);
|
|
838 dir.mkdirs();
|
|
839 client.get(remoteFile, localFolder);
|
|
840 return true;
|
|
841 }
|
|
842 catch (IOException e) {
|
|
843 Log.e(TAG, "Could not download remote file", e);
|
|
844 return false;
|
|
845 }
|
|
846 }
|
|
847
|
|
848 @Override
|
|
849 public boolean uploadFile(String localFile, String remoteFile,
|
|
850 String remoteFolder, String mode) {
|
|
851 try {
|
|
852 SCPClient client = new SCPClient(connection);
|
|
853
|
|
854 if (remoteFolder == null)
|
|
855 remoteFolder = "";
|
|
856
|
|
857 if (remoteFile == null || remoteFile == "")
|
|
858 client.put(localFile, remoteFolder, mode);
|
|
859 else
|
|
860 client.put(localFile, remoteFile, remoteFolder, mode);
|
|
861
|
|
862 return true;
|
|
863 }
|
|
864 catch (IOException e) {
|
|
865 Log.e(TAG, "Could not upload local file", e);
|
|
866 return false;
|
|
867 }
|
|
868 }
|
|
869
|
|
870 @Override
|
|
871 public void setDimensions(int columns, int rows, int width, int height) {
|
|
872 this.columns = columns;
|
|
873 this.rows = rows;
|
|
874
|
|
875 if (sessionOpen) {
|
|
876 try {
|
|
877 session.resizePTY(columns, rows, width, height);
|
|
878 }
|
|
879 catch (IOException e) {
|
|
880 Log.e(TAG, "Couldn't send resize PTY packet", e);
|
|
881 }
|
|
882 }
|
|
883 }
|
|
884
|
|
885 @Override
|
|
886 public int getDefaultPort() {
|
|
887 return DEFAULT_PORT;
|
|
888 }
|
|
889
|
|
890 @Override
|
|
891 public String getDefaultNickname(String username, String hostname, int port) {
|
|
892 if (port == DEFAULT_PORT) {
|
|
893 return String.format(Locale.US, "%s@%s", username, hostname);
|
|
894 }
|
|
895 else {
|
|
896 return String.format(Locale.US, "%s@%s:%d", username, hostname, port);
|
|
897 }
|
|
898 }
|
|
899
|
|
900 public static Uri getUri(String input) {
|
|
901 Matcher matcher = hostmask.matcher(input);
|
|
902
|
|
903 if (!matcher.matches())
|
|
904 return null;
|
|
905
|
|
906 StringBuilder sb = new StringBuilder();
|
|
907 sb.append(PROTOCOL)
|
|
908 .append("://")
|
|
909 .append(Uri.encode(matcher.group(1)))
|
|
910 .append('@')
|
|
911 .append(matcher.group(2));
|
|
912 String portString = matcher.group(4);
|
|
913 int port = DEFAULT_PORT;
|
|
914
|
|
915 if (portString != null) {
|
|
916 try {
|
|
917 port = Integer.parseInt(portString);
|
|
918
|
|
919 if (port < 1 || port > 65535) {
|
|
920 port = DEFAULT_PORT;
|
|
921 }
|
|
922 }
|
|
923 catch (NumberFormatException nfe) {
|
|
924 // Keep the default port
|
|
925 }
|
|
926 }
|
|
927
|
|
928 if (port != DEFAULT_PORT) {
|
|
929 sb.append(':')
|
|
930 .append(port);
|
|
931 }
|
|
932
|
|
933 sb.append("/#")
|
|
934 .append(Uri.encode(input));
|
|
935 Uri uri = Uri.parse(sb.toString());
|
|
936 return uri;
|
|
937 }
|
|
938
|
|
939 /**
|
|
940 * Handle challenges from keyboard-interactive authentication mode.
|
|
941 */
|
|
942 public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) {
|
|
943 interactiveCanContinue = true;
|
|
944 String[] responses = new String[numPrompts];
|
|
945
|
|
946 for (int i = 0; i < numPrompts; i++) {
|
|
947 // request response from user for each prompt
|
|
948 responses[i] = bridge.promptHelper.requestPasswordPrompt(instruction, prompt[i]);
|
|
949 }
|
|
950
|
|
951 return responses;
|
|
952 }
|
|
953
|
|
954 @Override
|
|
955 public HostBean createHost(Uri uri) {
|
|
956 HostBean host = new HostBean();
|
|
957 host.setProtocol(PROTOCOL);
|
|
958 host.setHostname(uri.getHost());
|
|
959 int port = uri.getPort();
|
|
960
|
|
961 if (port < 0)
|
|
962 port = DEFAULT_PORT;
|
|
963
|
|
964 host.setPort(port);
|
|
965 host.setUsername(uri.getUserInfo());
|
|
966 String nickname = uri.getFragment();
|
|
967
|
|
968 if (nickname == null || nickname.length() == 0) {
|
|
969 host.setNickname(getDefaultNickname(host.getUsername(),
|
|
970 host.getHostname(), host.getPort()));
|
|
971 }
|
|
972 else {
|
|
973 host.setNickname(uri.getFragment());
|
|
974 }
|
|
975
|
|
976 return host;
|
|
977 }
|
|
978
|
|
979 @Override
|
|
980 public void getSelectionArgs(Uri uri, Map<String, String> selection) {
|
|
981 selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
|
|
982 selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
|
|
983 selection.put(HostDatabase.FIELD_HOST_HOSTNAME, uri.getHost());
|
|
984 int port = uri.getPort();
|
|
985
|
|
986 if (port < 0)
|
|
987 port = DEFAULT_PORT;
|
|
988
|
|
989 selection.put(HostDatabase.FIELD_HOST_PORT, Integer.toString(port));
|
|
990 selection.put(HostDatabase.FIELD_HOST_USERNAME, uri.getUserInfo());
|
|
991 }
|
|
992
|
|
993 @Override
|
|
994 public void setCompression(boolean compression) {
|
|
995 this.compression = compression;
|
|
996 }
|
|
997
|
|
998 @Override
|
|
999 public void setHttpproxy(String httpproxy) {
|
|
1000 this.httpproxy = httpproxy;
|
|
1001 }
|
|
1002
|
|
1003 public static String getFormatHint(Context context) {
|
|
1004 return String.format("%s@%s:%s",
|
|
1005 context.getString(R.string.format_username),
|
|
1006 context.getString(R.string.format_hostname),
|
|
1007 context.getString(R.string.format_port));
|
|
1008 }
|
|
1009
|
|
1010 @Override
|
|
1011 public void setUseAuthAgent(String useAuthAgent) {
|
|
1012 this.useAuthAgent = useAuthAgent;
|
|
1013 }
|
|
1014
|
|
1015 public Map<String, byte[]> retrieveIdentities() {
|
|
1016 Map<String, byte[]> pubKeys = new HashMap<String, byte[]> (manager.loadedKeypairs.size());
|
|
1017
|
|
1018 for (Entry<String, KeyHolder> entry : manager.loadedKeypairs.entrySet()) {
|
|
1019 KeyPair pair = entry.getValue().pair;
|
|
1020
|
|
1021 try {
|
|
1022 PrivateKey privKey = pair.getPrivate();
|
|
1023
|
|
1024 if (privKey instanceof RSAPrivateKey) {
|
|
1025 RSAPublicKey pubkey = (RSAPublicKey) pair.getPublic();
|
|
1026 pubKeys.put(entry.getKey(), RSASHA1Verify.encodeSSHRSAPublicKey(pubkey));
|
|
1027 }
|
|
1028 else if (privKey instanceof DSAPrivateKey) {
|
|
1029 DSAPublicKey pubkey = (DSAPublicKey) pair.getPublic();
|
|
1030 pubKeys.put(entry.getKey(), DSASHA1Verify.encodeSSHDSAPublicKey(pubkey));
|
|
1031 }
|
|
1032 else
|
|
1033 continue;
|
|
1034 }
|
|
1035 catch (IOException e) {
|
|
1036 continue;
|
|
1037 }
|
|
1038 }
|
|
1039
|
|
1040 return pubKeys;
|
|
1041 }
|
|
1042
|
|
1043 public KeyPair getKeyPair(byte[] publicKey) {
|
|
1044 String nickname = manager.getKeyNickname(publicKey);
|
|
1045
|
|
1046 if (nickname == null)
|
|
1047 return null;
|
|
1048
|
|
1049 if (useAuthAgent.equals(HostDatabase.AUTHAGENT_NO)) {
|
|
1050 Log.e(TAG, "");
|
|
1051 return null;
|
|
1052 }
|
|
1053 else if (useAuthAgent.equals(HostDatabase.AUTHAGENT_CONFIRM) ||
|
|
1054 manager.loadedKeypairs.get(nickname).bean.isConfirmUse()) {
|
|
1055 if (!promptForPubkeyUse(nickname))
|
|
1056 return null;
|
|
1057 }
|
|
1058
|
|
1059 return manager.getKey(nickname);
|
|
1060 }
|
|
1061
|
|
1062 private boolean promptForPubkeyUse(String nickname) {
|
|
1063 Boolean result = bridge.promptHelper.requestBooleanPrompt(null,
|
|
1064 manager.res.getString(R.string.prompt_allow_agent_to_use_key,
|
|
1065 nickname));
|
|
1066 return result;
|
|
1067 }
|
|
1068
|
|
1069 public boolean addIdentity(KeyPair pair, String comment, boolean confirmUse, int lifetime) {
|
|
1070 PubkeyBean pubkey = new PubkeyBean();
|
|
1071 // pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
|
|
1072 pubkey.setNickname(comment);
|
|
1073 pubkey.setConfirmUse(confirmUse);
|
|
1074 pubkey.setLifetime(lifetime);
|
|
1075 manager.addKey(pubkey, pair);
|
|
1076 return true;
|
|
1077 }
|
|
1078
|
|
1079 public boolean removeAllIdentities() {
|
|
1080 manager.loadedKeypairs.clear();
|
|
1081 return true;
|
|
1082 }
|
|
1083
|
|
1084 public boolean removeIdentity(byte[] publicKey) {
|
|
1085 return manager.removeKey(publicKey);
|
|
1086 }
|
|
1087
|
|
1088 public boolean isAgentLocked() {
|
|
1089 return agentLockPassphrase != null;
|
|
1090 }
|
|
1091
|
|
1092 public boolean requestAgentUnlock(String unlockPassphrase) {
|
|
1093 if (agentLockPassphrase == null)
|
|
1094 return false;
|
|
1095
|
|
1096 if (agentLockPassphrase.equals(unlockPassphrase))
|
|
1097 agentLockPassphrase = null;
|
|
1098
|
|
1099 return agentLockPassphrase == null;
|
|
1100 }
|
|
1101
|
|
1102 public boolean setAgentLock(String lockPassphrase) {
|
|
1103 if (agentLockPassphrase != null)
|
|
1104 return false;
|
|
1105
|
|
1106 agentLockPassphrase = lockPassphrase;
|
|
1107 return true;
|
|
1108 }
|
|
1109
|
|
1110 /* (non-Javadoc)
|
|
1111 * @see com.five_ten_sg.connectbot.transport.AbsTransport#usesNetwork()
|
|
1112 */
|
|
1113 @Override
|
|
1114 public boolean usesNetwork() {
|
|
1115 return true;
|
|
1116 }
|
|
1117 }
|