code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
package com.trilead.ssh2;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A very basic <code>SCPClient</code> that can be used to copy files from/to
* the SSH-2 server. On the server side, the "scp" program must be in the PATH.
* <p>
* This scp client is thread safe - you can download (and upload) different sets
* of files concurrently without any troubles. The <code>SCPClient</code> is
* actually mapping every request to a distinct {@link Session}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SCPClient.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class SCPClient
{
Connection conn;
class LenNamePair
{
long length;
String filename;
}
public SCPClient(Connection conn)
{
if (conn == null)
throw new IllegalArgumentException("Cannot accept null argument!");
this.conn = conn;
}
private void readResponse(InputStream is) throws IOException
{
int c = is.read();
if (c == 0)
return;
if (c == -1)
throw new IOException("Remote scp terminated unexpectedly.");
if ((c != 1) && (c != 2))
throw new IOException("Remote scp sent illegal error code.");
if (c == 2)
throw new IOException("Remote scp terminated with error.");
String err = receiveLine(is);
throw new IOException("Remote scp terminated with error (" + err + ").");
}
private String receiveLine(InputStream is) throws IOException
{
StringBuffer sb = new StringBuffer(30);
while (true)
{
/*
* This is a random limit - if your path names are longer, then
* adjust it
*/
if (sb.length() > 8192)
throw new IOException("Remote scp sent a too long line");
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
if (c == '\n')
break;
sb.append((char) c);
}
return sb.toString();
}
private LenNamePair parseCLine(String line) throws IOException
{
/* Minimum line: "xxxx y z" ---> 8 chars */
long len;
if (line.length() < 8)
throw new IOException("Malformed C line sent by remote SCP binary, line too short.");
if ((line.charAt(4) != ' ') || (line.charAt(5) == ' '))
throw new IOException("Malformed C line sent by remote SCP binary.");
int length_name_sep = line.indexOf(' ', 5);
if (length_name_sep == -1)
throw new IOException("Malformed C line sent by remote SCP binary.");
String length_substring = line.substring(5, length_name_sep);
String name_substring = line.substring(length_name_sep + 1);
if ((length_substring.length() <= 0) || (name_substring.length() <= 0))
throw new IOException("Malformed C line sent by remote SCP binary.");
if ((6 + length_substring.length() + name_substring.length()) != line.length())
throw new IOException("Malformed C line sent by remote SCP binary.");
try
{
len = Long.parseLong(length_substring);
}
catch (NumberFormatException e)
{
throw new IOException("Malformed C line sent by remote SCP binary, cannot parse file length.");
}
if (len < 0)
throw new IOException("Malformed C line sent by remote SCP binary, illegal file length.");
LenNamePair lnp = new LenNamePair();
lnp.length = len;
lnp.filename = name_substring;
return lnp;
}
private void sendBytes(Session sess, byte[] data, String fileName, String mode) throws IOException
{
OutputStream os = sess.getStdin();
InputStream is = new BufferedInputStream(sess.getStdout(), 512);
readResponse(is);
String cline = "C" + mode + " " + data.length + " " + fileName + "\n";
os.write(cline.getBytes("ISO-8859-1"));
os.flush();
readResponse(is);
os.write(data, 0, data.length);
os.write(0);
os.flush();
readResponse(is);
os.write("E\n".getBytes("ISO-8859-1"));
os.flush();
}
private void sendFiles(Session sess, String[] files, String[] remoteFiles, String mode) throws IOException
{
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 40000);
InputStream is = new BufferedInputStream(sess.getStdout(), 512);
readResponse(is);
for (int i = 0; i < files.length; i++)
{
File f = new File(files[i]);
long remain = f.length();
String remoteName;
if ((remoteFiles != null) && (remoteFiles.length > i) && (remoteFiles[i] != null))
remoteName = remoteFiles[i];
else
remoteName = f.getName();
String cline = "C" + mode + " " + remain + " " + remoteName + "\n";
os.write(cline.getBytes("ISO-8859-1"));
os.flush();
readResponse(is);
FileInputStream fis = null;
try
{
fis = new FileInputStream(f);
while (remain > 0)
{
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
if (fis.read(buffer, 0, trans) != trans)
throw new IOException("Cannot read enough from local file " + files[i]);
os.write(buffer, 0, trans);
remain -= trans;
}
}
finally
{
if (fis != null)
fis.close();
}
os.write(0);
os.flush();
readResponse(is);
}
os.write("E\n".getBytes("ISO-8859-1"));
os.flush();
}
private void receiveFiles(Session sess, OutputStream[] targets) throws IOException
{
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
os.write(0x0);
os.flush();
for (int i = 0; i < targets.length; i++)
{
LenNamePair lnp = null;
while (true)
{
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
String line = receiveLine(is);
if (c == 'T')
{
/* Ignore modification times */
continue;
}
if ((c == 1) || (c == 2))
throw new IOException("Remote SCP error: " + line);
if (c == 'C')
{
lnp = parseCLine(line);
break;
}
throw new IOException("Remote SCP error: " + ((char) c) + line);
}
os.write(0x0);
os.flush();
long remain = lnp.length;
while (remain > 0)
{
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
int this_time_received = is.read(buffer, 0, trans);
if (this_time_received < 0)
{
throw new IOException("Remote scp terminated connection unexpectedly");
}
targets[i].write(buffer, 0, this_time_received);
remain -= this_time_received;
}
readResponse(is);
os.write(0x0);
os.flush();
}
}
private void receiveFiles(Session sess, String[] files, String target) throws IOException
{
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
os.write(0x0);
os.flush();
for (int i = 0; i < files.length; i++)
{
LenNamePair lnp = null;
while (true)
{
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
String line = receiveLine(is);
if (c == 'T')
{
/* Ignore modification times */
continue;
}
if ((c == 1) || (c == 2))
throw new IOException("Remote SCP error: " + line);
if (c == 'C')
{
lnp = parseCLine(line);
break;
}
throw new IOException("Remote SCP error: " + ((char) c) + line);
}
os.write(0x0);
os.flush();
File f = new File(target + File.separatorChar + lnp.filename);
FileOutputStream fop = null;
try
{
fop = new FileOutputStream(f);
long remain = lnp.length;
while (remain > 0)
{
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
int this_time_received = is.read(buffer, 0, trans);
if (this_time_received < 0)
{
throw new IOException("Remote scp terminated connection unexpectedly");
}
fop.write(buffer, 0, this_time_received);
remain -= this_time_received;
}
}
finally
{
if (fop != null)
fop.close();
}
readResponse(is);
os.write(0x0);
os.flush();
}
}
/**
* Copy a local file to a remote directory, uses mode 0600 when creating the
* file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory) throws IOException
{
put(new String[] { localFile }, remoteTargetDirectory, "0600");
}
/**
* Copy a set of local files to a remote directory, uses mode 0600 when
* creating files on the remote side.
*
* @param localFiles
* Paths and names of local file names.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory) throws IOException
{
put(localFiles, remoteTargetDirectory, "0600");
}
/**
* Copy a local file to a remote directory, uses the specified mode when
* creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory, String mode) throws IOException
{
put(new String[] { localFile }, remoteTargetDirectory, mode);
}
/**
* Copy a local file to a remote directory, uses the specified mode and
* remote filename when creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteFileName, String remoteTargetDirectory, String mode)
throws IOException
{
put(new String[] { localFile }, new String[] { remoteFileName }, remoteTargetDirectory, mode);
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. Uses mode 0600 for creating the remote file.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @throws IOException
*/
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory) throws IOException
{
put(data, remoteFileName, remoteTargetDirectory, "0600");
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. The method use the specified mode when creating the file on the
* remote side.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory, String mode) throws IOException
{
Session sess = null;
if ((remoteFileName == null) || (remoteTargetDirectory == null) || (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
try
{
sess = conn.openSession();
sess.execCommand(cmd);
sendBytes(sess, data, remoteFileName, mode);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
/**
* Copy a set of local files to a remote directory, uses the specified mode
* when creating the files on the remote side.
*
* @param localFiles
* Paths and names of the local files.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory, String mode) throws IOException
{
put(localFiles, null, remoteTargetDirectory, mode);
}
public void put(String[] localFiles, String[] remoteFiles, String remoteTargetDirectory, String mode)
throws IOException
{
Session sess = null;
/*
* remoteFiles may be null, indicating that the local filenames shall be
* used
*/
if ((localFiles == null) || (remoteTargetDirectory == null) || (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
if (localFiles.length == 0)
return;
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
for (int i = 0; i < localFiles.length; i++)
{
if (localFiles[i] == null)
throw new IllegalArgumentException("Cannot accept null filename.");
}
try
{
sess = conn.openSession();
sess.execCommand(cmd);
sendFiles(sess, localFiles, remoteFiles, mode);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
/**
* Download a file from the remote server to a local directory.
*
* @param remoteFile
* Path and name of the remote file.
* @param localTargetDirectory
* Local directory to put the downloaded file.
*
* @throws IOException
*/
public void get(String remoteFile, String localTargetDirectory) throws IOException
{
get(new String[] { remoteFile }, localTargetDirectory);
}
/**
* Download a file from the remote server and pipe its contents into an
* <code>OutputStream</code>. Please note that, to enable flexible usage
* of this method, the <code>OutputStream</code> will not be closed nor
* flushed.
*
* @param remoteFile
* Path and name of the remote file.
* @param target
* OutputStream where the contents of the file will be sent to.
* @throws IOException
*/
public void get(String remoteFile, OutputStream target) throws IOException
{
get(new String[] { remoteFile }, new OutputStream[] { target });
}
private void get(String remoteFiles[], OutputStream[] targets) throws IOException
{
Session sess = null;
if ((remoteFiles == null) || (targets == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length != targets.length)
throw new IllegalArgumentException("Length of arguments does not match.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++)
{
if (remoteFiles[i] == null)
throw new IllegalArgumentException("Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException("Cannot accept empty filename.");
cmd += (" " + tmp);
}
try
{
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, targets);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
/**
* Download a set of files from the remote server to a local directory.
*
* @param remoteFiles
* Paths and names of the remote files.
* @param localTargetDirectory
* Local directory to put the downloaded files.
*
* @throws IOException
*/
public void get(String remoteFiles[], String localTargetDirectory) throws IOException
{
Session sess = null;
if ((remoteFiles == null) || (localTargetDirectory == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++)
{
if (remoteFiles[i] == null)
throw new IllegalArgumentException("Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException("Cannot accept empty filename.");
cmd += (" " + tmp);
}
try
{
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, remoteFiles, localTargetDirectory);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/SCPClient.java | Java | asf20 | 19,045 |
package com.trilead.ssh2;
import java.io.IOException;
/**
* May be thrown upon connect() if a HTTP proxy is being used.
*
* @see Connection#connect()
* @see Connection#setProxyData(ProxyData)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HTTPProxyException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class HTTPProxyException extends IOException
{
private static final long serialVersionUID = 2241537397104426186L;
public final String httpResponse;
public final int httpErrorCode;
public HTTPProxyException(String httpResponse, int httpErrorCode)
{
super("HTTP Proxy Error (" + httpErrorCode + " " + httpResponse + ")");
this.httpResponse = httpResponse;
this.httpErrorCode = httpErrorCode;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/HTTPProxyException.java | Java | asf20 | 787 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Error Codes
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ErrorCodes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class ErrorCodes
{
public static final int SSH_FX_OK = 0;
public static final int SSH_FX_EOF = 1;
public static final int SSH_FX_NO_SUCH_FILE = 2;
public static final int SSH_FX_PERMISSION_DENIED = 3;
public static final int SSH_FX_FAILURE = 4;
public static final int SSH_FX_BAD_MESSAGE = 5;
public static final int SSH_FX_NO_CONNECTION = 6;
public static final int SSH_FX_CONNECTION_LOST = 7;
public static final int SSH_FX_OP_UNSUPPORTED = 8;
public static final int SSH_FX_INVALID_HANDLE = 9;
public static final int SSH_FX_NO_SUCH_PATH = 10;
public static final int SSH_FX_FILE_ALREADY_EXISTS = 11;
public static final int SSH_FX_WRITE_PROTECT = 12;
public static final int SSH_FX_NO_MEDIA = 13;
public static final int SSH_FX_NO_SPACE_ON_FILESYSTEM = 14;
public static final int SSH_FX_QUOTA_EXCEEDED = 15;
public static final int SSH_FX_UNKNOWN_PRINCIPAL = 16;
public static final int SSH_FX_LOCK_CONFLICT = 17;
public static final int SSH_FX_DIR_NOT_EMPTY = 18;
public static final int SSH_FX_NOT_A_DIRECTORY = 19;
public static final int SSH_FX_INVALID_FILENAME = 20;
public static final int SSH_FX_LINK_LOOP = 21;
public static final int SSH_FX_CANNOT_DELETE = 22;
public static final int SSH_FX_INVALID_PARAMETER = 23;
public static final int SSH_FX_FILE_IS_A_DIRECTORY = 24;
public static final int SSH_FX_BYTE_RANGE_LOCK_CONFLICT = 25;
public static final int SSH_FX_BYTE_RANGE_LOCK_REFUSED = 26;
public static final int SSH_FX_DELETE_PENDING = 27;
public static final int SSH_FX_FILE_CORRUPT = 28;
public static final int SSH_FX_OWNER_INVALID = 29;
public static final int SSH_FX_GROUP_INVALID = 30;
public static final int SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK = 31;
private static final String[][] messages = {
{ "SSH_FX_OK", "Indicates successful completion of the operation." },
{ "SSH_FX_EOF",
"An attempt to read past the end-of-file was made; or, there are no more directory entries to return." },
{ "SSH_FX_NO_SUCH_FILE", "A reference was made to a file which does not exist." },
{ "SSH_FX_PERMISSION_DENIED", "The user does not have sufficient permissions to perform the operation." },
{ "SSH_FX_FAILURE", "An error occurred, but no specific error code exists to describe the failure." },
{ "SSH_FX_BAD_MESSAGE", "A badly formatted packet or other SFTP protocol incompatibility was detected." },
{ "SSH_FX_NO_CONNECTION", "There is no connection to the server." },
{ "SSH_FX_CONNECTION_LOST", "The connection to the server was lost." },
{ "SSH_FX_OP_UNSUPPORTED",
"An attempted operation could not be completed by the server because the server does not support the operation." },
{ "SSH_FX_INVALID_HANDLE", "The handle value was invalid." },
{ "SSH_FX_NO_SUCH_PATH", "The file path does not exist or is invalid." },
{ "SSH_FX_FILE_ALREADY_EXISTS", "The file already exists." },
{ "SSH_FX_WRITE_PROTECT", "The file is on read-only media, or the media is write protected." },
{ "SSH_FX_NO_MEDIA",
"The requested operation cannot be completed because there is no media available in the drive." },
{ "SSH_FX_NO_SPACE_ON_FILESYSTEM",
"The requested operation cannot be completed because there is insufficient free space on the filesystem." },
{ "SSH_FX_QUOTA_EXCEEDED",
"The operation cannot be completed because it would exceed the user's storage quota." },
{
"SSH_FX_UNKNOWN_PRINCIPAL",
"A principal referenced by the request (either the 'owner', 'group', or 'who' field of an ACL), was unknown. The error specific data contains the problematic names." },
{ "SSH_FX_LOCK_CONFLICT", "The file could not be opened because it is locked by another process." },
{ "SSH_FX_DIR_NOT_EMPTY", "The directory is not empty." },
{ "SSH_FX_NOT_A_DIRECTORY", "The specified file is not a directory." },
{ "SSH_FX_INVALID_FILENAME", "The filename is not valid." },
{ "SSH_FX_LINK_LOOP",
"Too many symbolic links encountered or, an SSH_FXF_NOFOLLOW open encountered a symbolic link as the final component." },
{ "SSH_FX_CANNOT_DELETE",
"The file cannot be deleted. One possible reason is that the advisory READONLY attribute-bit is set." },
{ "SSH_FX_INVALID_PARAMETER",
"One of the parameters was out of range, or the parameters specified cannot be used together." },
{ "SSH_FX_FILE_IS_A_DIRECTORY",
"The specified file was a directory in a context where a directory cannot be used." },
{ "SSH_FX_BYTE_RANGE_LOCK_CONFLICT",
" A read or write operation failed because another process's mandatory byte-range lock overlaps with the request." },
{ "SSH_FX_BYTE_RANGE_LOCK_REFUSED", "A request for a byte range lock was refused." },
{ "SSH_FX_DELETE_PENDING", "An operation was attempted on a file for which a delete operation is pending." },
{ "SSH_FX_FILE_CORRUPT", "The file is corrupt; an filesystem integrity check should be run." },
{ "SSH_FX_OWNER_INVALID", "The principal specified can not be assigned as an owner of a file." },
{ "SSH_FX_GROUP_INVALID", "The principal specified can not be assigned as the primary group of a file." },
{ "SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK",
"The requested operation could not be completed because the specifed byte range lock has not been granted." },
};
public static final String[] getDescription(int errorCode)
{
if ((errorCode < 0) || (errorCode >= messages.length))
return null;
return messages[errorCode];
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/ErrorCodes.java | Java | asf20 | 5,772 |
package com.trilead.ssh2.sftp;
/**
*
* Values for the 'text-hint' field in the SFTP ATTRS data type.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttrTextHints.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttrTextHints
{
/**
* The server knows the file is a text file, and should be opened
* using the SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_TEXT = 0x00;
/**
* The server has applied a heuristic or other mechanism and
* believes that the file should be opened with the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_TEXT = 0x01;
/**
* The server knows the file has binary content.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_BINARY = 0x02;
/**
* The server has applied a heuristic or other mechanism and
* believes has binary content, and should not be opened with the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_BINARY = 0x03;
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/AttrTextHints.java | Java | asf20 | 1,089 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Attribute Bits for the "attrib-bits" and "attrib-bits-valid" fields
* of the SFTP ATTR data type.
* <p>
* Yes, these are the "attrib-bits", even though they have "_FLAGS_" in
* their name. Don't ask - I did not invent it.
* <p>
* "<i>These fields, taken together, reflect various attributes of the file
* or directory, on the server. Bits not set in 'attrib-bits-valid' MUST be
* ignored in the 'attrib-bits' field. This allows both the server and the
* client to communicate only the bits it knows about without inadvertently
* twiddling bits they don't understand.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribBits.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribBits
{
/**
* Advisory, read-only bit. This bit is not part of the access
* control information on the file, but is rather an advisory field
* indicating that the file should not be written.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_READONLY = 0x00000001;
/**
* The file is part of the operating system.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYSTEM = 0x00000002;
/**
* File SHOULD NOT be shown to user unless specifically requested.
* For example, most UNIX systems SHOULD set this bit if the filename
* begins with a 'period'. This bit may be read-only (see section 5.4 of
* the SFTP standard draft). Most UNIX systems will not allow this to be
* changed.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_HIDDEN = 0x00000004;
/**
* This attribute applies only to directories. This attribute is
* always read-only, and cannot be modified. This attribute means
* that files and directory names in this directory should be compared
* without regard to case.
* <p>
* It is recommended that where possible, the server's filesystem be
* allowed to do comparisons. For example, if a client wished to prompt
* a user before overwriting a file, it should not compare the new name
* with the previously retrieved list of names in the directory. Rather,
* it should first try to create the new file by specifying
* SSH_FXF_CREATE_NEW flag. Then, if this fails and returns
* SSH_FX_FILE_ALREADY_EXISTS, it should prompt the user and then retry
* the create specifying SSH_FXF_CREATE_TRUNCATE.
* <p>
* Unless otherwise specified, filenames are assumed to be case sensitive.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_CASE_INSENSITIVE = 0x00000008;
/**
* The file should be included in backup / archive operations.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ARCHIVE = 0x00000010;
/**
* The file is stored on disk using file-system level transparent
* encryption. This flag does not affect the file data on the wire
* (for either READ or WRITE requests.)
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ENCRYPTED = 0x00000020;
/**
* The file is stored on disk using file-system level transparent
* compression. This flag does not affect the file data on the wire.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_COMPRESSED = 0x00000040;
/**
* The file is a sparse file; this means that file blocks that have
* not been explicitly written are not stored on disk. For example, if
* a client writes a buffer at 10 M from the beginning of the file,
* the blocks between the previous EOF marker and the 10 M offset would
* not consume physical disk space.
* <p>
* Some servers may store all files as sparse files, in which case
* this bit will be unconditionally set. Other servers may not have
* a mechanism for determining if the file is sparse, and so the file
* MAY be stored sparse even if this flag is not set.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SPARSE = 0x00000080;
/**
* Opening the file without either the SSH_FXF_ACCESS_APPEND_DATA or
* the SSH_FXF_ACCESS_APPEND_DATA_ATOMIC flag (see section 8.1.1.3
* of the SFTP standard draft) MUST result in an
* SSH_FX_INVALID_PARAMETER error.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_APPEND_ONLY = 0x00000100;
/**
* The file cannot be deleted or renamed, no hard link can be created
* to this file, and no data can be written to the file.
* <p>
* This bit implies a stronger level of protection than
* SSH_FILEXFER_ATTR_FLAGS_READONLY, the file permission mask or ACLs.
* Typically even the superuser cannot write to immutable files, and
* only the superuser can set or remove the bit.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_IMMUTABLE = 0x00000200;
/**
* When the file is modified, the changes are written synchronously
* to the disk.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYNC = 0x00000400;
/**
* The server MAY include this bit in a directory listing or realpath
* response. It indicates there was a failure in the translation to UTF-8.
* If this flag is included, the server SHOULD also include the
* UNTRANSLATED_NAME attribute.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_TRANSLATION_ERR = 0x00000800;
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/AttribBits.java | Java | asf20 | 5,233 |
package com.trilead.ssh2.sftp;
/**
*
* Types for the 'type' field in the SFTP ATTRS data type.
* <p>
* "<i>On a POSIX system, these values would be derived from the mode field
* of the stat structure. SPECIAL should be used for files that are of
* a known type which cannot be expressed in the protocol. UNKNOWN
* should be used if the type is not known.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribTypes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribTypes
{
public static final int SSH_FILEXFER_TYPE_REGULAR = 1;
public static final int SSH_FILEXFER_TYPE_DIRECTORY = 2;
public static final int SSH_FILEXFER_TYPE_SYMLINK = 3;
public static final int SSH_FILEXFER_TYPE_SPECIAL = 4;
public static final int SSH_FILEXFER_TYPE_UNKNOWN = 5;
public static final int SSH_FILEXFER_TYPE_SOCKET = 6;
public static final int SSH_FILEXFER_TYPE_CHAR_DEVICE = 7;
public static final int SSH_FILEXFER_TYPE_BLOCK_DEVICE = 8;
public static final int SSH_FILEXFER_TYPE_FIFO = 9;
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/AttribTypes.java | Java | asf20 | 1,076 |
package com.trilead.ssh2.sftp;
/**
*
* Attribute Flags. The 'valid-attribute-flags' field in
* the SFTP ATTRS data type specifies which of the fields are actually present.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribFlags
{
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_SIZE = 0x00000001;
/** Protocol version 6:
* 0x00000002 was used in a previous version of this protocol.
* It is now a reserved value and MUST NOT appear in the mask.
* Some future version of this protocol may reuse this value.
*/
public static final int SSH_FILEXFER_ATTR_V3_UIDGID = 0x00000002;
/**
* Indicates that the 'permissions' field is present.
*/
public static final int SSH_FILEXFER_ATTR_PERMISSIONS = 0x00000004;
/**
* Indicates that the 'atime' and 'mtime' field are present
* (protocol v3).
*/
public static final int SSH_FILEXFER_ATTR_V3_ACMODTIME = 0x00000008;
/**
* Indicates that the 'atime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACCESSTIME = 0x00000008;
/**
* Indicates that the 'createtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CREATETIME = 0x00000010;
/**
* Indicates that the 'mtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MODIFYTIME = 0x00000020;
/**
* Indicates that the 'acl' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACL = 0x00000040;
/**
* Indicates that the 'owner' and 'group' fields are present.
*/
public static final int SSH_FILEXFER_ATTR_OWNERGROUP = 0x00000080;
/**
* Indicates that additionally to the 'atime', 'createtime',
* 'mtime' and 'ctime' fields (if present), there is also
* 'atime-nseconds', 'createtime-nseconds', 'mtime-nseconds'
* and 'ctime-nseconds'.
*/
public static final int SSH_FILEXFER_ATTR_SUBSECOND_TIMES = 0x00000100;
/**
* Indicates that the 'attrib-bits' and 'attrib-bits-valid'
* fields are present.
*/
public static final int SSH_FILEXFER_ATTR_BITS = 0x00000200;
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ALLOCATION_SIZE = 0x00000400;
/**
* Indicates that the 'text-hint' field is present.
*/
public static final int SSH_FILEXFER_ATTR_TEXT_HINT = 0x00000800;
/**
* Indicates that the 'mime-type' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MIME_TYPE = 0x00001000;
/**
* Indicates that the 'link-count' field is present.
*/
public static final int SSH_FILEXFER_ATTR_LINK_COUNT = 0x00002000;
/**
* Indicates that the 'untranslated-name' field is present.
*/
public static final int SSH_FILEXFER_ATTR_UNTRANSLATED_NAME = 0x00004000;
/**
* Indicates that the 'ctime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CTIME = 0x00008000;
/**
* Indicates that the 'extended-count' field (and probablby some
* 'extensions') is present.
*/
public static final int SSH_FILEXFER_ATTR_EXTENDED = 0x80000000;
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/AttribFlags.java | Java | asf20 | 3,256 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Open Flags.
*
* The following table is provided to assist in mapping POSIX semantics
* to equivalent SFTP file open parameters:
* <p>
* TODO: This comment should be moved to the open method.
* <p>
* <ul>
* <li>O_RDONLY
* <ul><li>desired-access = READ_DATA | READ_ATTRIBUTES</li></ul>
* </li>
* </ul>
* <ul>
* <li>O_WRONLY
* <ul><li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES</li></ul>
* </li>
* </ul>
* <ul>
* <li>O_RDWR
* <ul><li>desired-access = READ_DATA | READ_ATTRIBUTES | WRITE_DATA | WRITE_ATTRIBUTES</li></ul>
* </li>
* </ul>
* <ul>
* <li>O_APPEND
* <ul>
* <li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES | APPEND_DATA</li>
* <li>flags = SSH_FXF_ACCESS_APPEND_DATA and or SSH_FXF_ACCESS_APPEND_DATA_ATOMIC</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_CREAT
* <ul>
* <li>flags = SSH_FXF_OPEN_OR_CREATE</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC
* <ul>
* <li>flags = SSH_FXF_TRUNCATE_EXISTING</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC|O_CREATE
* <ul>
* <li>flags = SSH_FXF_CREATE_TRUNCATE</li>
* </ul>
* </li>
* </ul>
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: OpenFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class OpenFlags
{
/**
* Disposition is a 3 bit field that controls how the file is opened.
* The server MUST support these bits (possible enumaration values:
* SSH_FXF_CREATE_NEW, SSH_FXF_CREATE_TRUNCATE, SSH_FXF_OPEN_EXISTING,
* SSH_FXF_OPEN_OR_CREATE or SSH_FXF_TRUNCATE_EXISTING).
*/
public static final int SSH_FXF_ACCESS_DISPOSITION = 0x00000007;
/**
* A new file is created; if the file already exists, the server
* MUST return status SSH_FX_FILE_ALREADY_EXISTS.
*/
public static final int SSH_FXF_CREATE_NEW = 0x00000000;
/**
* A new file is created; if the file already exists, it is opened
* and truncated.
*/
public static final int SSH_FXF_CREATE_TRUNCATE = 0x00000001;
/**
* An existing file is opened. If the file does not exist, the
* server MUST return SSH_FX_NO_SUCH_FILE. If a directory in the
* path does not exist, the server SHOULD return
* SSH_FX_NO_SUCH_PATH. It is also acceptable if the server
* returns SSH_FX_NO_SUCH_FILE in this case.
*/
public static final int SSH_FXF_OPEN_EXISTING = 0x00000002;
/**
* If the file exists, it is opened. If the file does not exist,
* it is created.
*/
public static final int SSH_FXF_OPEN_OR_CREATE = 0x00000003;
/**
* An existing file is opened and truncated. If the file does not
* exist, the server MUST return the same error codes as defined
* for SSH_FXF_OPEN_EXISTING.
*/
public static final int SSH_FXF_TRUNCATE_EXISTING = 0x00000004;
/**
* Data is always written at the end of the file. The offset field
* of the SSH_FXP_WRITE requests are ignored.
* <p>
* Data is not required to be appended atomically. This means that
* if multiple writers attempt to append data simultaneously, data
* from the first may be lost. However, data MAY be appended
* atomically.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA = 0x00000008;
/**
* Data is always written at the end of the file. The offset field
* of the SSH_FXP_WRITE requests are ignored.
* <p>
* Data MUST be written atomically so that there is no chance that
* multiple appenders can collide and result in data being lost.
* <p>
* If both append flags are specified, the server SHOULD use atomic
* append if it is available, but SHOULD use non-atomic appends
* otherwise. The server SHOULD NOT fail the request in this case.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA_ATOMIC = 0x00000010;
/**
* Indicates that the server should treat the file as text and
* convert it to the canonical newline convention in use.
* (See Determining Server Newline Convention in section 5.3 in the
* SFTP standard draft).
* <p>
* When a file is opened with this flag, the offset field in the read
* and write functions is ignored.
* <p>
* Servers MUST process multiple, parallel reads and writes correctly
* in this mode. Naturally, it is permissible for them to do this by
* serializing the requests.
* <p>
* Clients SHOULD use the SSH_FXF_ACCESS_APPEND_DATA flag to append
* data to a text file rather then using write with a calculated offset.
*/
public static final int SSH_FXF_ACCESS_TEXT_MODE = 0x00000020;
/**
* The server MUST guarantee that no other handle has been opened
* with ACE4_READ_DATA access, and that no other handle will be
* opened with ACE4_READ_DATA access until the client closes the
* handle. (This MUST apply both to other clients and to other
* processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking
* guarantee, it MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_WRITE_DATA or any other
* combination of accesses, as long as ACE4_READ_DATA is not included
* in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_READ = 0x00000040;
/**
* The server MUST guarantee that no other handle has been opened
* with ACE4_WRITE_DATA or ACE4_APPEND_DATA access, and that no other
* handle will be opened with ACE4_WRITE_DATA or ACE4_APPEND_DATA
* access until the client closes the handle. (This MUST apply both
* to other clients and to other processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking
* guarantee, it MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_READ_DATA or any other
* combination of accesses, as long as neither ACE4_WRITE_DATA nor
* ACE4_APPEND_DATA are included in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_WRITE = 0x00000080;
/**
* The server MUST guarantee that no other handle has been opened
* with ACE4_DELETE access, opened with the
* SSH_FXF_ACCESS_DELETE_ON_CLOSE flag set, and that no other handle
* will be opened with ACE4_DELETE access or with the
* SSH_FXF_ACCESS_DELETE_ON_CLOSE flag set, and that the file itself
* is not deleted in any other way until the client closes the handle.
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking
* guarantee, it MUST return SSH_FX_OP_UNSUPPORTED.
*/
public static final int SSH_FXF_ACCESS_BLOCK_DELETE = 0x00000100;
/**
* If this bit is set, the above BLOCK modes are advisory. In advisory
* mode, only other accesses that specify a BLOCK mode need be
* considered when determining whether the BLOCK can be granted,
* and the server need not prevent I/O operations that violate the
* block mode.
* <p>
* The server MAY perform mandatory locking even if the BLOCK_ADVISORY
* bit is set.
*/
public static final int SSH_FXF_ACCESS_BLOCK_ADVISORY = 0x00000200;
/**
* If the final component of the path is a symlink, then the open
* MUST fail, and the error SSH_FX_LINK_LOOP MUST be returned.
*/
public static final int SSH_FXF_ACCESS_NOFOLLOW = 0x00000400;
/**
* The file should be deleted when the last handle to it is closed.
* (The last handle may not be an sftp-handle.) This MAY be emulated
* by a server if the OS doesn't support it by deleting the file when
* this handle is closed.
* <p>
* It is implementation specific whether the directory entry is
* removed immediately or when the handle is closed.
*/
public static final int SSH_FXF_ACCESS_DELETE_ON_CLOSE = 0x00000800;
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/OpenFlags.java | Java | asf20 | 7,930 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Paket Types
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Packet.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class Packet
{
public static final int SSH_FXP_INIT = 1;
public static final int SSH_FXP_VERSION = 2;
public static final int SSH_FXP_OPEN = 3;
public static final int SSH_FXP_CLOSE = 4;
public static final int SSH_FXP_READ = 5;
public static final int SSH_FXP_WRITE = 6;
public static final int SSH_FXP_LSTAT = 7;
public static final int SSH_FXP_FSTAT = 8;
public static final int SSH_FXP_SETSTAT = 9;
public static final int SSH_FXP_FSETSTAT = 10;
public static final int SSH_FXP_OPENDIR = 11;
public static final int SSH_FXP_READDIR = 12;
public static final int SSH_FXP_REMOVE = 13;
public static final int SSH_FXP_MKDIR = 14;
public static final int SSH_FXP_RMDIR = 15;
public static final int SSH_FXP_REALPATH = 16;
public static final int SSH_FXP_STAT = 17;
public static final int SSH_FXP_RENAME = 18;
public static final int SSH_FXP_READLINK = 19;
public static final int SSH_FXP_SYMLINK = 20;
public static final int SSH_FXP_STATUS = 101;
public static final int SSH_FXP_HANDLE = 102;
public static final int SSH_FXP_DATA = 103;
public static final int SSH_FXP_NAME = 104;
public static final int SSH_FXP_ATTRS = 105;
public static final int SSH_FXP_EXTENDED = 200;
public static final int SSH_FXP_EXTENDED_REPLY = 201;
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/Packet.java | Java | asf20 | 1,505 |
package com.trilead.ssh2.sftp;
/**
*
* Permissions for the 'permissions' field in the SFTP ATTRS data type.
* <p>
* "<i>The 'permissions' field contains a bit mask specifying file permissions.
* These permissions correspond to the st_mode field of the stat structure
* defined by POSIX [IEEE.1003-1.1996].</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribPermissions.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribPermissions
{
/* Octal values! */
public static final int S_IRUSR = 0400;
public static final int S_IWUSR = 0200;
public static final int S_IXUSR = 0100;
public static final int S_IRGRP = 0040;
public static final int S_IWGRP = 0020;
public static final int S_IXGRP = 0010;
public static final int S_IROTH = 0004;
public static final int S_IWOTH = 0002;
public static final int S_IXOTH = 0001;
public static final int S_ISUID = 04000;
public static final int S_ISGID = 02000;
public static final int S_ISVTX = 01000;
}
| 1030365071-xuechao | src/com/trilead/ssh2/sftp/AttribPermissions.java | Java | asf20 | 1,047 |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
import com.jcraft.jzlib.JZlib;
import com.jcraft.jzlib.ZStream;
/**
* @author Kenny Root
*
*/
public class Zlib implements ICompressor {
static private final int DEFAULT_BUF_SIZE = 4096;
static private final int LEVEL = 5;
private ZStream deflate;
private byte[] deflate_tmpbuf;
private ZStream inflate;
private byte[] inflate_tmpbuf;
private byte[] inflated_buf;
public Zlib() {
deflate = new ZStream();
inflate = new ZStream();
deflate.deflateInit(LEVEL);
inflate.inflateInit();
deflate_tmpbuf = new byte[DEFAULT_BUF_SIZE];
inflate_tmpbuf = new byte[DEFAULT_BUF_SIZE];
inflated_buf = new byte[DEFAULT_BUF_SIZE];
}
public boolean canCompressPreauth() {
return true;
}
public int getBufferSize() {
return DEFAULT_BUF_SIZE;
}
public int compress(byte[] buf, int start, int len, byte[] output) {
deflate.next_in = buf;
deflate.next_in_index = start;
deflate.avail_in = len - start;
if ((buf.length + 1024) > deflate_tmpbuf.length) {
deflate_tmpbuf = new byte[buf.length + 1024];
}
deflate.next_out = deflate_tmpbuf;
deflate.next_out_index = 0;
deflate.avail_out = output.length;
if (deflate.deflate(JZlib.Z_PARTIAL_FLUSH) != JZlib.Z_OK) {
System.err.println("compress: compression failure");
}
if (deflate.avail_in > 0) {
System.err.println("compress: deflated data too large");
}
int outputlen = output.length - deflate.avail_out;
System.arraycopy(deflate_tmpbuf, 0, output, 0, outputlen);
return outputlen;
}
public byte[] uncompress(byte[] buffer, int start, int[] length) {
int inflated_end = 0;
inflate.next_in = buffer;
inflate.next_in_index = start;
inflate.avail_in = length[0];
while (true) {
inflate.next_out = inflate_tmpbuf;
inflate.next_out_index = 0;
inflate.avail_out = DEFAULT_BUF_SIZE;
int status = inflate.inflate(JZlib.Z_PARTIAL_FLUSH);
switch (status) {
case JZlib.Z_OK:
if (inflated_buf.length < inflated_end + DEFAULT_BUF_SIZE
- inflate.avail_out) {
byte[] foo = new byte[inflated_end + DEFAULT_BUF_SIZE
- inflate.avail_out];
System.arraycopy(inflated_buf, 0, foo, 0, inflated_end);
inflated_buf = foo;
}
System.arraycopy(inflate_tmpbuf, 0, inflated_buf, inflated_end,
DEFAULT_BUF_SIZE - inflate.avail_out);
inflated_end += (DEFAULT_BUF_SIZE - inflate.avail_out);
length[0] = inflated_end;
break;
case JZlib.Z_BUF_ERROR:
if (inflated_end > buffer.length - start) {
byte[] foo = new byte[inflated_end + start];
System.arraycopy(buffer, 0, foo, 0, start);
System.arraycopy(inflated_buf, 0, foo, start, inflated_end);
buffer = foo;
} else {
System.arraycopy(inflated_buf, 0, buffer, start,
inflated_end);
}
length[0] = inflated_end;
return buffer;
default:
System.err.println("uncompress: inflate returnd " + status);
return null;
}
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/compression/Zlib.java | Java | asf20 | 3,628 |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
/**
* Defines how zlib@openssh.org compression works.
* See
* http://www.openssh.org/txt/draft-miller-secsh-compression-delayed-00.txt
* compression is disabled until userauth has occurred.
*
* @author Matt Johnston
*
*/
public class ZlibOpenSSH extends Zlib {
public boolean canCompressPreauth() {
return false;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/compression/ZlibOpenSSH.java | Java | asf20 | 1,051 |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
import java.util.Vector;
/**
* @author Kenny Root
*
*/
public class CompressionFactory {
static class CompressorEntry
{
String type;
String compressorClass;
public CompressorEntry(String type, String compressorClass)
{
this.type = type;
this.compressorClass = compressorClass;
}
}
static Vector<CompressorEntry> compressors = new Vector<CompressorEntry>();
static
{
/* Higher Priority First */
compressors.addElement(new CompressorEntry("zlib", "com.trilead.ssh2.compression.Zlib"));
compressors.addElement(new CompressorEntry("zlib@openssh.com", "com.trilead.ssh2.compression.ZlibOpenSSH"));
compressors.addElement(new CompressorEntry("none", ""));
}
public static String[] getDefaultCompressorList()
{
String list[] = new String[compressors.size()];
for (int i = 0; i < compressors.size(); i++)
{
CompressorEntry ce = compressors.elementAt(i);
list[i] = new String(ce.type);
}
return list;
}
public static void checkCompressorList(String[] compressorCandidates)
{
for (int i = 0; i < compressorCandidates.length; i++)
getEntry(compressorCandidates[i]);
}
public static ICompressor createCompressor(String type)
{
try
{
CompressorEntry ce = getEntry(type);
if ("".equals(ce.compressorClass))
return null;
Class<?> cc = Class.forName(ce.compressorClass);
ICompressor cmp = (ICompressor) cc.newInstance();
return cmp;
}
catch (Exception e)
{
throw new IllegalArgumentException("Cannot instantiate " + type);
}
}
private static CompressorEntry getEntry(String type)
{
for (int i = 0; i < compressors.size(); i++)
{
CompressorEntry ce = compressors.elementAt(i);
if (ce.type.equals(type))
return ce;
}
throw new IllegalArgumentException("Unkown algorithm " + type);
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/compression/CompressionFactory.java | Java | asf20 | 2,516 |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
/**
* @author Kenny Root
*
*/
public interface ICompressor {
int getBufferSize();
int compress(byte[] buf, int start, int len, byte[] output);
byte[] uncompress(byte[] buf, int start, int[] len);
boolean canCompressPreauth();
}
| 1030365071-xuechao | src/com/trilead/ssh2/compression/ICompressor.java | Java | asf20 | 957 |
package com.trilead.ssh2;
/**
* A <code>SFTPv3FileAttributes</code> object represents detail information
* about a file on the server. Not all fields may/must be present.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3FileAttributes.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class SFTPv3FileAttributes
{
/**
* The SIZE attribute. <code>NULL</code> if not present.
*/
public Long size = null;
/**
* The UID attribute. <code>NULL</code> if not present.
*/
public Integer uid = null;
/**
* The GID attribute. <code>NULL</code> if not present.
*/
public Integer gid = null;
/**
* The POSIX permissions. <code>NULL</code> if not present.
* <p>
* Here is a list:
* <p>
* <pre>Note: these numbers are all OCTAL.
*
* S_IFMT 0170000 bitmask for the file type bitfields
* S_IFSOCK 0140000 socket
* S_IFLNK 0120000 symbolic link
* S_IFREG 0100000 regular file
* S_IFBLK 0060000 block device
* S_IFDIR 0040000 directory
* S_IFCHR 0020000 character device
* S_IFIFO 0010000 fifo
* S_ISUID 0004000 set UID bit
* S_ISGID 0002000 set GID bit
* S_ISVTX 0001000 sticky bit
*
* S_IRWXU 00700 mask for file owner permissions
* S_IRUSR 00400 owner has read permission
* S_IWUSR 00200 owner has write permission
* S_IXUSR 00100 owner has execute permission
* S_IRWXG 00070 mask for group permissions
* S_IRGRP 00040 group has read permission
* S_IWGRP 00020 group has write permission
* S_IXGRP 00010 group has execute permission
* S_IRWXO 00007 mask for permissions for others (not in group)
* S_IROTH 00004 others have read permission
* S_IWOTH 00002 others have write permisson
* S_IXOTH 00001 others have execute permission
* </pre>
*/
public Integer permissions = null;
/**
* The ATIME attribute. Represented as seconds from Jan 1, 1970 in UTC.
* <code>NULL</code> if not present.
*/
public Long atime = null;
/**
* The MTIME attribute. Represented as seconds from Jan 1, 1970 in UTC.
* <code>NULL</code> if not present.
*/
public Long mtime = null;
/**
* Checks if this entry is a directory.
*
* @return Returns true if permissions are available and they indicate
* that this entry represents a directory.
*/
public boolean isDirectory()
{
if (permissions == null)
return false;
return ((permissions.intValue() & 0040000) != 0);
}
/**
* Checks if this entry is a regular file.
*
* @return Returns true if permissions are available and they indicate
* that this entry represents a regular file.
*/
public boolean isRegularFile()
{
if (permissions == null)
return false;
return ((permissions.intValue() & 0100000) != 0);
}
/**
* Checks if this entry is a a symlink.
*
* @return Returns true if permissions are available and they indicate
* that this entry represents a symlink.
*/
public boolean isSymlink()
{
if (permissions == null)
return false;
return ((permissions.intValue() & 0120000) != 0);
}
/**
* Turn the POSIX permissions into a 7 digit octal representation.
* Note: the returned value is first masked with <code>0177777</code>.
*
* @return <code>NULL</code> if permissions are not available.
*/
public String getOctalPermissions()
{
if (permissions == null)
return null;
String res = Integer.toString(permissions.intValue() & 0177777, 8);
StringBuffer sb = new StringBuffer();
int leadingZeros = 7 - res.length();
while (leadingZeros > 0)
{
sb.append('0');
leadingZeros--;
}
sb.append(res);
return sb.toString();
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/SFTPv3FileAttributes.java | Java | asf20 | 3,936 |
package com.trilead.ssh2;
/**
* A <code>SFTPv3FileHandle</code>.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3FileHandle.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPv3FileHandle
{
final SFTPv3Client client;
final byte[] fileHandle;
boolean isClosed = false;
/* The constructor is NOT public */
SFTPv3FileHandle(SFTPv3Client client, byte[] h)
{
this.client = client;
this.fileHandle = h;
}
/**
* Get the SFTPv3Client instance which created this handle.
*
* @return A SFTPv3Client instance.
*/
public SFTPv3Client getClient()
{
return client;
}
/**
* Check if this handle was closed with the {@link SFTPv3Client#closeFile(SFTPv3FileHandle)} method
* of the <code>SFTPv3Client</code> instance which created the handle.
*
* @return if the handle is closed.
*/
public boolean isClosed()
{
return isClosed;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/SFTPv3FileHandle.java | Java | asf20 | 959 |
package com.trilead.ssh2;
import java.util.Map;
/**
* AuthAgentCallback.
*
* @author Kenny Root
* @version $Id$
*/
public interface AuthAgentCallback {
/**
* @return array of blobs containing the OpenSSH-format encoded public keys
*/
Map<String,byte[]> retrieveIdentities();
/**
* @param key A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of
* the user in Trilead object format.
* @param comment comment associated with this key
* @param confirmUse whether to prompt before using this key
* @param lifetime lifetime in seconds for key to be remembered
* @return success or failure
*/
boolean addIdentity(Object key, String comment, boolean confirmUse, int lifetime);
/**
* @param publicKey byte blob containing the OpenSSH-format encoded public key
* @return success or failure
*/
boolean removeIdentity(byte[] publicKey);
/**
* @return success or failure
*/
boolean removeAllIdentities();
/**
* @param publicKey byte blob containing the OpenSSH-format encoded public key
* @return A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of
* the user in Trilead object format.
*/
Object getPrivateKey(byte[] publicKey);
/**
* @return
*/
boolean isAgentLocked();
/**
* @param lockPassphrase
*/
boolean setAgentLock(String lockPassphrase);
/**
* @param unlockPassphrase
* @return
*/
boolean requestAgentUnlock(String unlockPassphrase);
}
| 1030365071-xuechao | src/com/trilead/ssh2/AuthAgentCallback.java | Java | asf20 | 1,551 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDHReply.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDHReply.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDHReply
{
byte[] payload;
byte[] hostKey;
BigInteger f;
byte[] signature;
public PacketKexDHReply(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEXDH_REPLY)
throw new IOException("This is not a SSH_MSG_KEXDH_REPLY! ("
+ packet_type + ")");
hostKey = tr.readByteString();
f = tr.readMPINT();
signature = tr.readByteString();
if (tr.remain() != 0) throw new IOException("PADDING IN SSH_MSG_KEXDH_REPLY!");
}
public BigInteger getF()
{
return f;
}
public byte[] getHostKey()
{
return hostKey;
}
public byte[] getSignature()
{
return signature;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexDHReply.java | Java | asf20 | 1,155 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketServiceRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketServiceRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketServiceRequest
{
byte[] payload;
String serviceName;
public PacketServiceRequest(String serviceName)
{
this.serviceName = serviceName;
}
public PacketServiceRequest(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_SERVICE_REQUEST)
throw new IOException("This is not a SSH_MSG_SERVICE_REQUEST! ("
+ packet_type + ")");
serviceName = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_SERVICE_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_SERVICE_REQUEST);
tw.writeString(serviceName);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketServiceRequest.java | Java | asf20 | 1,239 |
package com.trilead.ssh2.packets;
import com.trilead.ssh2.DHGexParameters;
/**
* PacketKexDhGexRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexRequest
{
byte[] payload;
int min;
int n;
int max;
public PacketKexDhGexRequest(DHGexParameters para)
{
this.min = para.getMin_group_len();
this.n = para.getPref_group_len();
this.max = para.getMax_group_len();
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_REQUEST);
tw.writeUINT32(min);
tw.writeUINT32(n);
tw.writeUINT32(max);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexDhGexRequest.java | Java | asf20 | 822 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthRequestPassword.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestNone.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestNone
{
byte[] payload;
String userName;
String serviceName;
public PacketUserauthRequestNone(String serviceName, String user)
{
this.serviceName = serviceName;
this.userName = user;
}
public PacketUserauthRequestNone(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST! (" + packet_type + ")");
userName = tr.readString();
serviceName = tr.readString();
String method = tr.readString();
if (method.equals("none") == false)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST with type none!");
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("none");
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthRequestNone.java | Java | asf20 | 1,576 |
package com.trilead.ssh2.packets;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
/**
* TypesWriter.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TypesWriter.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class TypesWriter
{
byte arr[];
int pos;
public TypesWriter()
{
arr = new byte[256];
pos = 0;
}
private void resize(int len)
{
byte new_arr[] = new byte[len];
System.arraycopy(arr, 0, new_arr, 0, arr.length);
arr = new_arr;
}
public int length()
{
return pos;
}
public byte[] getBytes()
{
byte[] dst = new byte[pos];
System.arraycopy(arr, 0, dst, 0, pos);
return dst;
}
public void getBytes(byte dst[])
{
System.arraycopy(arr, 0, dst, 0, pos);
}
public void writeUINT32(int val, int off)
{
if ((off + 4) > arr.length)
resize(off + 32);
arr[off++] = (byte) (val >> 24);
arr[off++] = (byte) (val >> 16);
arr[off++] = (byte) (val >> 8);
arr[off++] = (byte) val;
}
public void writeUINT32(int val)
{
writeUINT32(val, pos);
pos += 4;
}
public void writeUINT64(long val)
{
if ((pos + 8) > arr.length)
resize(arr.length + 32);
arr[pos++] = (byte) (val >> 56);
arr[pos++] = (byte) (val >> 48);
arr[pos++] = (byte) (val >> 40);
arr[pos++] = (byte) (val >> 32);
arr[pos++] = (byte) (val >> 24);
arr[pos++] = (byte) (val >> 16);
arr[pos++] = (byte) (val >> 8);
arr[pos++] = (byte) val;
}
public void writeBoolean(boolean v)
{
if ((pos + 1) > arr.length)
resize(arr.length + 32);
arr[pos++] = v ? (byte) 1 : (byte) 0;
}
public void writeByte(int v, int off)
{
if ((off + 1) > arr.length)
resize(off + 32);
arr[off] = (byte) v;
}
public void writeByte(int v)
{
writeByte(v, pos);
pos++;
}
public void writeMPInt(BigInteger b)
{
byte raw[] = b.toByteArray();
if ((raw.length == 1) && (raw[0] == 0))
writeUINT32(0); /* String with zero bytes of data */
else
writeString(raw, 0, raw.length);
}
public void writeBytes(byte[] buff)
{
writeBytes(buff, 0, buff.length);
}
public void writeBytes(byte[] buff, int off, int len)
{
if ((pos + len) > arr.length)
resize(arr.length + len + 32);
System.arraycopy(buff, off, arr, pos, len);
pos += len;
}
public void writeString(byte[] buff, int off, int len)
{
writeUINT32(len);
writeBytes(buff, off, len);
}
public void writeString(String v)
{
byte[] b;
try
{
/* All Java JVMs must support ISO-8859-1 */
b = v.getBytes("ISO-8859-1");
}
catch (UnsupportedEncodingException ignore)
{
b = v.getBytes();
}
writeUINT32(b.length);
writeBytes(b, 0, b.length);
}
public void writeString(String v, String charsetName) throws UnsupportedEncodingException
{
byte[] b = (charsetName == null) ? v.getBytes() : v.getBytes(charsetName);
writeUINT32(b.length);
writeBytes(b, 0, b.length);
}
public void writeNameList(String v[])
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < v.length; i++)
{
if (i > 0)
sb.append(',');
sb.append(v[i]);
}
writeString(sb.toString());
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/TypesWriter.java | Java | asf20 | 3,273 |
package com.trilead.ssh2.packets;
import java.math.BigInteger;
/**
* PacketKexDhGexInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexInit
{
byte[] payload;
BigInteger e;
public PacketKexDhGexInit(BigInteger e)
{
this.e = e;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_INIT);
tw.writeMPInt(e);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexDhGexInit.java | Java | asf20 | 620 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDhGexGroup.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexGroup.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexGroup
{
byte[] payload;
BigInteger p;
BigInteger g;
public PacketKexDhGexGroup(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEX_DH_GEX_GROUP)
throw new IllegalArgumentException(
"This is not a SSH_MSG_KEX_DH_GEX_GROUP! (" + packet_type
+ ")");
p = tr.readMPINT();
g = tr.readMPINT();
if (tr.remain() != 0)
throw new IOException("PADDING IN SSH_MSG_KEX_DH_GEX_GROUP!");
}
public BigInteger getG()
{
return g;
}
public BigInteger getP()
{
return p;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexDhGexGroup.java | Java | asf20 | 1,067 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketChannelWindowAdjust.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelWindowAdjust.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketChannelWindowAdjust
{
byte[] payload;
public int recipientChannelID;
public int windowChange;
public PacketChannelWindowAdjust(int recipientChannelID, int windowChange)
{
this.recipientChannelID = recipientChannelID;
this.windowChange = windowChange;
}
public PacketChannelWindowAdjust(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST)
throw new IOException(
"This is not a SSH_MSG_CHANNEL_WINDOW_ADJUST! ("
+ packet_type + ")");
recipientChannelID = tr.readUINT32();
windowChange = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_WINDOW_ADJUST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST);
tw.writeUINT32(recipientChannelID);
tw.writeUINT32(windowChange);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketChannelWindowAdjust.java | Java | asf20 | 1,493 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDhGexReply.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexReply.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexReply
{
byte[] payload;
byte[] hostKey;
BigInteger f;
byte[] signature;
public PacketKexDhGexReply(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEX_DH_GEX_REPLY)
throw new IOException("This is not a SSH_MSG_KEX_DH_GEX_REPLY! (" + packet_type + ")");
hostKey = tr.readByteString();
f = tr.readMPINT();
signature = tr.readByteString();
if (tr.remain() != 0)
throw new IOException("PADDING IN SSH_MSG_KEX_DH_GEX_REPLY!");
}
public BigInteger getF()
{
return f;
}
public byte[] getHostKey()
{
return hostKey;
}
public byte[] getSignature()
{
return signature;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexDhGexReply.java | Java | asf20 | 1,180 |
package com.trilead.ssh2.packets;
/**
* PacketGlobalCancelForwardRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalCancelForwardRequest.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketGlobalCancelForwardRequest
{
byte[] payload;
public boolean wantReply;
public String bindAddress;
public int bindPort;
public PacketGlobalCancelForwardRequest(boolean wantReply, String bindAddress, int bindPort)
{
this.wantReply = wantReply;
this.bindAddress = bindAddress;
this.bindPort = bindPort;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("cancel-tcpip-forward");
tw.writeBoolean(wantReply);
tw.writeString(bindAddress);
tw.writeUINT32(bindPort);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketGlobalCancelForwardRequest.java | Java | asf20 | 962 |
package com.trilead.ssh2.packets;
/**
* PacketSessionSubsystemRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionSubsystemRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionSubsystemRequest
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String subsystem;
public PacketSessionSubsystemRequest(int recipientChannelID, boolean wantReply, String subsystem)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.subsystem = subsystem;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("subsystem");
tw.writeBoolean(wantReply);
tw.writeString(subsystem);
payload = tw.getBytes();
tw.getBytes(payload);
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketSessionSubsystemRequest.java | Java | asf20 | 990 |
package com.trilead.ssh2.packets;
/**
* PacketSessionExecCommand.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionExecCommand.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionExecCommand
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String command;
public PacketSessionExecCommand(int recipientChannelID, boolean wantReply, String command)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.command = command;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("exec");
tw.writeBoolean(wantReply);
tw.writeString(command);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketSessionExecCommand.java | Java | asf20 | 929 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthBanner.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthFailure.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthFailure
{
byte[] payload;
String[] authThatCanContinue;
boolean partialSuccess;
public PacketUserauthFailure(String[] authThatCanContinue, boolean partialSuccess)
{
this.authThatCanContinue = authThatCanContinue;
this.partialSuccess = partialSuccess;
}
public PacketUserauthFailure(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_FAILURE)
throw new IOException("This is not a SSH_MSG_USERAUTH_FAILURE! (" + packet_type + ")");
authThatCanContinue = tr.readNameList();
partialSuccess = tr.readBoolean();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_FAILURE packet!");
}
public String[] getAuthThatCanContinue()
{
return authThatCanContinue;
}
public boolean isPartialSuccess()
{
return partialSuccess;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthFailure.java | Java | asf20 | 1,328 |
package com.trilead.ssh2.packets;
/**
* PacketSessionStartShell.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionStartShell.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionStartShell
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public PacketSessionStartShell(int recipientChannelID, boolean wantReply)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("shell");
tw.writeBoolean(wantReply);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketSessionStartShell.java | Java | asf20 | 828 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
import com.trilead.ssh2.util.Tokenizer;
/**
* TypesReader.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TypesReader.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class TypesReader
{
byte[] arr;
int pos = 0;
int max = 0;
public TypesReader(byte[] arr)
{
this.arr = arr;
pos = 0;
max = arr.length;
}
public TypesReader(byte[] arr, int off)
{
this.arr = arr;
this.pos = off;
this.max = arr.length;
if ((pos < 0) || (pos > arr.length))
throw new IllegalArgumentException("Illegal offset.");
}
public TypesReader(byte[] arr, int off, int len)
{
this.arr = arr;
this.pos = off;
this.max = off + len;
if ((pos < 0) || (pos > arr.length))
throw new IllegalArgumentException("Illegal offset.");
if ((max < 0) || (max > arr.length))
throw new IllegalArgumentException("Illegal length.");
}
public int readByte() throws IOException
{
if (pos >= max)
throw new IOException("Packet too short.");
return (arr[pos++] & 0xff);
}
public byte[] readBytes(int len) throws IOException
{
if ((pos + len) > max)
throw new IOException("Packet too short.");
byte[] res = new byte[len];
System.arraycopy(arr, pos, res, 0, len);
pos += len;
return res;
}
public void readBytes(byte[] dst, int off, int len) throws IOException
{
if ((pos + len) > max)
throw new IOException("Packet too short.");
System.arraycopy(arr, pos, dst, off, len);
pos += len;
}
public boolean readBoolean() throws IOException
{
if (pos >= max)
throw new IOException("Packet too short.");
return (arr[pos++] != 0);
}
public int readUINT32() throws IOException
{
if ((pos + 4) > max)
throw new IOException("Packet too short.");
return ((arr[pos++] & 0xff) << 24) | ((arr[pos++] & 0xff) << 16) | ((arr[pos++] & 0xff) << 8)
| (arr[pos++] & 0xff);
}
public long readUINT64() throws IOException
{
if ((pos + 8) > max)
throw new IOException("Packet too short.");
long high = ((arr[pos++] & 0xff) << 24) | ((arr[pos++] & 0xff) << 16) | ((arr[pos++] & 0xff) << 8)
| (arr[pos++] & 0xff); /* sign extension may take place - will be shifted away =) */
long low = ((arr[pos++] & 0xff) << 24) | ((arr[pos++] & 0xff) << 16) | ((arr[pos++] & 0xff) << 8)
| (arr[pos++] & 0xff); /* sign extension may take place - handle below */
return (high << 32) | (low & 0xffffffffl); /* see Java language spec (15.22.1, 5.6.2) */
}
public BigInteger readMPINT() throws IOException
{
BigInteger b;
byte raw[] = readByteString();
if (raw.length == 0)
b = BigInteger.ZERO;
else
b = new BigInteger(raw);
return b;
}
public byte[] readByteString() throws IOException
{
int len = readUINT32();
if ((len + pos) > max)
throw new IOException("Malformed SSH byte string.");
byte[] res = new byte[len];
System.arraycopy(arr, pos, res, 0, len);
pos += len;
return res;
}
public String readString(String charsetName) throws IOException
{
int len = readUINT32();
if ((len + pos) > max)
throw new IOException("Malformed SSH string.");
String res = (charsetName == null) ? new String(arr, pos, len) : new String(arr, pos, len, charsetName);
pos += len;
return res;
}
public String readString() throws IOException
{
int len = readUINT32();
if ((len + pos) > max)
throw new IOException("Malformed SSH string.");
String res = new String(arr, pos, len, "ISO-8859-1");
pos += len;
return res;
}
public String[] readNameList() throws IOException
{
return Tokenizer.parseTokens(readString(), ',');
}
public int remain()
{
return max - pos;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/TypesReader.java | Java | asf20 | 3,904 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthRequestPassword.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestPassword.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestPassword
{
byte[] payload;
String userName;
String serviceName;
String password;
public PacketUserauthRequestPassword(String serviceName, String user, String pass)
{
this.serviceName = serviceName;
this.userName = user;
this.password = pass;
}
public PacketUserauthRequestPassword(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST! (" + packet_type + ")");
userName = tr.readString();
serviceName = tr.readString();
String method = tr.readString();
if (method.equals("password") == false)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST with type password!");
/* ... */
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("password");
tw.writeBoolean(false);
tw.writeString(password);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthRequestPassword.java | Java | asf20 | 1,736 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketChannelOpenFailure.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelOpenFailure.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketChannelOpenFailure
{
byte[] payload;
public int recipientChannelID;
public int reasonCode;
public String description;
public String languageTag;
public PacketChannelOpenFailure(int recipientChannelID, int reasonCode, String description,
String languageTag)
{
this.recipientChannelID = recipientChannelID;
this.reasonCode = reasonCode;
this.description = description;
this.languageTag = languageTag;
}
public PacketChannelOpenFailure(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_OPEN_FAILURE)
throw new IOException(
"This is not a SSH_MSG_CHANNEL_OPEN_FAILURE! ("
+ packet_type + ")");
recipientChannelID = tr.readUINT32();
reasonCode = tr.readUINT32();
description = tr.readString();
languageTag = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_OPEN_FAILURE packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN_FAILURE);
tw.writeUINT32(recipientChannelID);
tw.writeUINT32(reasonCode);
tw.writeString(description);
tw.writeString(languageTag);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketChannelOpenFailure.java | Java | asf20 | 1,778 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketNewKeys.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketNewKeys.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketNewKeys
{
byte[] payload;
public PacketNewKeys()
{
}
public PacketNewKeys(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_NEWKEYS)
throw new IOException("This is not a SSH_MSG_NEWKEYS! ("
+ packet_type + ")");
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_NEWKEYS packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_NEWKEYS);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketNewKeys.java | Java | asf20 | 1,027 |
package com.trilead.ssh2.packets;
/**
* PacketGlobalAuthAgent.
*
* @author Kenny Root, kenny@the-b.org
* @version $Id$
*/
public class PacketChannelAuthAgentReq
{
byte[] payload;
public int recipientChannelID;
public PacketChannelAuthAgentReq(int recipientChannelID)
{
this.recipientChannelID = recipientChannelID;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("auth-agent-req@openssh.com");
tw.writeBoolean(true); // want reply
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketChannelAuthAgentReq.java | Java | asf20 | 663 |
package com.trilead.ssh2.packets;
public class PacketSessionPtyResize {
byte[] payload;
public int recipientChannelID;
public int width;
public int height;
public int pixelWidth;
public int pixelHeight;
public PacketSessionPtyResize(int recipientChannelID, int width, int height, int pixelWidth, int pixelHeight) {
this.recipientChannelID = recipientChannelID;
this.width = width;
this.height = height;
this.pixelWidth = pixelWidth;
this.pixelHeight = pixelHeight;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("window-change");
tw.writeBoolean(false);
tw.writeUINT32(width);
tw.writeUINT32(height);
tw.writeUINT32(pixelWidth);
tw.writeUINT32(pixelHeight);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketSessionPtyResize.java | Java | asf20 | 912 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthRequestPublicKey.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestPublicKey.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestPublicKey
{
byte[] payload;
String userName;
String serviceName;
String password;
String pkAlgoName;
byte[] pk;
byte[] sig;
public PacketUserauthRequestPublicKey(String serviceName, String user,
String pkAlgorithmName, byte[] pk, byte[] sig)
{
this.serviceName = serviceName;
this.userName = user;
this.pkAlgoName = pkAlgorithmName;
this.pk = pk;
this.sig = sig;
}
public PacketUserauthRequestPublicKey(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST! ("
+ packet_type + ")");
throw new IOException("Not implemented!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("publickey");
tw.writeBoolean(true);
tw.writeString(pkAlgoName);
tw.writeString(pk, 0, pk.length);
tw.writeString(sig, 0, sig.length);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthRequestPublicKey.java | Java | asf20 | 1,653 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketIgnore.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketIgnore.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketIgnore
{
byte[] payload;
byte[] data;
public void setData(byte[] data)
{
this.data = data;
payload = null;
}
public PacketIgnore()
{
}
public PacketIgnore(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_IGNORE)
throw new IOException("This is not a SSH_MSG_IGNORE packet! (" + packet_type + ")");
/* Could parse String body */
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_IGNORE);
if (data != null)
tw.writeString(data, 0, data.length);
else
tw.writeString("");
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketIgnore.java | Java | asf20 | 1,169 |
package com.trilead.ssh2.packets;
/**
* Packets.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Packets.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class Packets
{
public static final int SSH_MSG_DISCONNECT = 1;
public static final int SSH_MSG_IGNORE = 2;
public static final int SSH_MSG_UNIMPLEMENTED = 3;
public static final int SSH_MSG_DEBUG = 4;
public static final int SSH_MSG_SERVICE_REQUEST = 5;
public static final int SSH_MSG_SERVICE_ACCEPT = 6;
public static final int SSH_MSG_KEXINIT = 20;
public static final int SSH_MSG_NEWKEYS = 21;
public static final int SSH_MSG_KEXDH_INIT = 30;
public static final int SSH_MSG_KEXDH_REPLY = 31;
public static final int SSH_MSG_KEX_DH_GEX_REQUEST_OLD = 30;
public static final int SSH_MSG_KEX_DH_GEX_REQUEST = 34;
public static final int SSH_MSG_KEX_DH_GEX_GROUP = 31;
public static final int SSH_MSG_KEX_DH_GEX_INIT = 32;
public static final int SSH_MSG_KEX_DH_GEX_REPLY = 33;
public static final int SSH_MSG_USERAUTH_REQUEST = 50;
public static final int SSH_MSG_USERAUTH_FAILURE = 51;
public static final int SSH_MSG_USERAUTH_SUCCESS = 52;
public static final int SSH_MSG_USERAUTH_BANNER = 53;
public static final int SSH_MSG_USERAUTH_INFO_REQUEST = 60;
public static final int SSH_MSG_USERAUTH_INFO_RESPONSE = 61;
public static final int SSH_MSG_GLOBAL_REQUEST = 80;
public static final int SSH_MSG_REQUEST_SUCCESS = 81;
public static final int SSH_MSG_REQUEST_FAILURE = 82;
public static final int SSH_MSG_CHANNEL_OPEN = 90;
public static final int SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91;
public static final int SSH_MSG_CHANNEL_OPEN_FAILURE = 92;
public static final int SSH_MSG_CHANNEL_WINDOW_ADJUST = 93;
public static final int SSH_MSG_CHANNEL_DATA = 94;
public static final int SSH_MSG_CHANNEL_EXTENDED_DATA = 95;
public static final int SSH_MSG_CHANNEL_EOF = 96;
public static final int SSH_MSG_CHANNEL_CLOSE = 97;
public static final int SSH_MSG_CHANNEL_REQUEST = 98;
public static final int SSH_MSG_CHANNEL_SUCCESS = 99;
public static final int SSH_MSG_CHANNEL_FAILURE = 100;
public static final int SSH_EXTENDED_DATA_STDERR = 1;
public static final int SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1;
public static final int SSH_DISCONNECT_PROTOCOL_ERROR = 2;
public static final int SSH_DISCONNECT_KEY_EXCHANGE_FAILED = 3;
public static final int SSH_DISCONNECT_RESERVED = 4;
public static final int SSH_DISCONNECT_MAC_ERROR = 5;
public static final int SSH_DISCONNECT_COMPRESSION_ERROR = 6;
public static final int SSH_DISCONNECT_SERVICE_NOT_AVAILABLE = 7;
public static final int SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8;
public static final int SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9;
public static final int SSH_DISCONNECT_CONNECTION_LOST = 10;
public static final int SSH_DISCONNECT_BY_APPLICATION = 11;
public static final int SSH_DISCONNECT_TOO_MANY_CONNECTIONS = 12;
public static final int SSH_DISCONNECT_AUTH_CANCELLED_BY_USER = 13;
public static final int SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14;
public static final int SSH_DISCONNECT_ILLEGAL_USER_NAME = 15;
public static final int SSH_OPEN_ADMINISTRATIVELY_PROHIBITED = 1;
public static final int SSH_OPEN_CONNECT_FAILED = 2;
public static final int SSH_OPEN_UNKNOWN_CHANNEL_TYPE = 3;
public static final int SSH_OPEN_RESOURCE_SHORTAGE = 4;
private static final String[] reverseNames = new String[101];
static
{
reverseNames[1] = "SSH_MSG_DISCONNECT";
reverseNames[2] = "SSH_MSG_IGNORE";
reverseNames[3] = "SSH_MSG_UNIMPLEMENTED";
reverseNames[4] = "SSH_MSG_DEBUG";
reverseNames[5] = "SSH_MSG_SERVICE_REQUEST";
reverseNames[6] = "SSH_MSG_SERVICE_ACCEPT";
reverseNames[20] = "SSH_MSG_KEXINIT";
reverseNames[21] = "SSH_MSG_NEWKEYS";
reverseNames[30] = "SSH_MSG_KEXDH_INIT";
reverseNames[31] = "SSH_MSG_KEXDH_REPLY/SSH_MSG_KEX_DH_GEX_GROUP";
reverseNames[32] = "SSH_MSG_KEX_DH_GEX_INIT";
reverseNames[33] = "SSH_MSG_KEX_DH_GEX_REPLY";
reverseNames[34] = "SSH_MSG_KEX_DH_GEX_REQUEST";
reverseNames[50] = "SSH_MSG_USERAUTH_REQUEST";
reverseNames[51] = "SSH_MSG_USERAUTH_FAILURE";
reverseNames[52] = "SSH_MSG_USERAUTH_SUCCESS";
reverseNames[53] = "SSH_MSG_USERAUTH_BANNER";
reverseNames[60] = "SSH_MSG_USERAUTH_INFO_REQUEST";
reverseNames[61] = "SSH_MSG_USERAUTH_INFO_RESPONSE";
reverseNames[80] = "SSH_MSG_GLOBAL_REQUEST";
reverseNames[81] = "SSH_MSG_REQUEST_SUCCESS";
reverseNames[82] = "SSH_MSG_REQUEST_FAILURE";
reverseNames[90] = "SSH_MSG_CHANNEL_OPEN";
reverseNames[91] = "SSH_MSG_CHANNEL_OPEN_CONFIRMATION";
reverseNames[92] = "SSH_MSG_CHANNEL_OPEN_FAILURE";
reverseNames[93] = "SSH_MSG_CHANNEL_WINDOW_ADJUST";
reverseNames[94] = "SSH_MSG_CHANNEL_DATA";
reverseNames[95] = "SSH_MSG_CHANNEL_EXTENDED_DATA";
reverseNames[96] = "SSH_MSG_CHANNEL_EOF";
reverseNames[97] = "SSH_MSG_CHANNEL_CLOSE";
reverseNames[98] = "SSH_MSG_CHANNEL_REQUEST";
reverseNames[99] = "SSH_MSG_CHANNEL_SUCCESS";
reverseNames[100] = "SSH_MSG_CHANNEL_FAILURE";
}
public static final String getMessageName(int type)
{
String res = null;
if ((type >= 0) && (type < reverseNames.length))
{
res = reverseNames[type];
}
return (res == null) ? ("UNKNOWN MSG " + type) : res;
}
// public static final void debug(String tag, byte[] msg)
// {
// System.err.println(tag + " Type: " + msg[0] + ", LEN: " + msg.length);
//
// for (int i = 0; i < msg.length; i++)
// {
// if (((msg[i] >= 'a') && (msg[i] <= 'z')) || ((msg[i] >= 'A') && (msg[i] <= 'Z'))
// || ((msg[i] >= '0') && (msg[i] <= '9')) || (msg[i] == ' '))
// System.err.print((char) msg[i]);
// else
// System.err.print(".");
// }
// System.err.println();
// System.err.flush();
// }
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/Packets.java | Java | asf20 | 5,945 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthInfoRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthInfoRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthInfoRequest
{
byte[] payload;
String name;
String instruction;
String languageTag;
int numPrompts;
String prompt[];
boolean echo[];
public PacketUserauthInfoRequest(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_INFO_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_INFO_REQUEST! (" + packet_type + ")");
name = tr.readString();
instruction = tr.readString();
languageTag = tr.readString();
numPrompts = tr.readUINT32();
prompt = new String[numPrompts];
echo = new boolean[numPrompts];
for (int i = 0; i < numPrompts; i++)
{
prompt[i] = tr.readString();
echo[i] = tr.readBoolean();
}
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_INFO_REQUEST packet!");
}
public boolean[] getEcho()
{
return echo;
}
public String getInstruction()
{
return instruction;
}
public String getLanguageTag()
{
return languageTag;
}
public String getName()
{
return name;
}
public int getNumPrompts()
{
return numPrompts;
}
public String[] getPrompt()
{
return prompt;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthInfoRequest.java | Java | asf20 | 1,671 |
package com.trilead.ssh2.packets;
/**
* PacketUserauthRequestInteractive.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestInteractive.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestInteractive
{
byte[] payload;
String userName;
String serviceName;
String[] submethods;
public PacketUserauthRequestInteractive(String serviceName, String user, String[] submethods)
{
this.serviceName = serviceName;
this.userName = user;
this.submethods = submethods;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("keyboard-interactive");
tw.writeString(""); // draft-ietf-secsh-newmodes-04.txt says that
// the language tag should be empty.
tw.writeNameList(submethods);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthRequestInteractive.java | Java | asf20 | 1,045 |
package com.trilead.ssh2.packets;
/**
* PacketChannelTrileadPing.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelTrileadPing.java,v 1.1 2008/03/03 07:01:36
* cplattne Exp $
*/
public class PacketChannelTrileadPing
{
byte[] payload;
public int recipientChannelID;
public PacketChannelTrileadPing(int recipientChannelID)
{
this.recipientChannelID = recipientChannelID;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("trilead-ping");
tw.writeBoolean(true);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketChannelTrileadPing.java | Java | asf20 | 769 |
package com.trilead.ssh2.packets;
/**
* PacketOpenDirectTCPIPChannel.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketOpenDirectTCPIPChannel.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketOpenDirectTCPIPChannel
{
byte[] payload;
int channelID;
int initialWindowSize;
int maxPacketSize;
String host_to_connect;
int port_to_connect;
String originator_IP_address;
int originator_port;
public PacketOpenDirectTCPIPChannel(int channelID, int initialWindowSize, int maxPacketSize,
String host_to_connect, int port_to_connect, String originator_IP_address,
int originator_port)
{
this.channelID = channelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
this.originator_IP_address = originator_IP_address;
this.originator_port = originator_port;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN);
tw.writeString("direct-tcpip");
tw.writeUINT32(channelID);
tw.writeUINT32(initialWindowSize);
tw.writeUINT32(maxPacketSize);
tw.writeString(host_to_connect);
tw.writeUINT32(port_to_connect);
tw.writeString(originator_IP_address);
tw.writeUINT32(originator_port);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketOpenDirectTCPIPChannel.java | Java | asf20 | 1,490 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketOpenSessionChannel.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketOpenSessionChannel.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketOpenSessionChannel
{
byte[] payload;
int channelID;
int initialWindowSize;
int maxPacketSize;
public PacketOpenSessionChannel(int channelID, int initialWindowSize,
int maxPacketSize)
{
this.channelID = channelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
}
public PacketOpenSessionChannel(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_OPEN)
throw new IOException("This is not a SSH_MSG_CHANNEL_OPEN! ("
+ packet_type + ")");
channelID = tr.readUINT32();
initialWindowSize = tr.readUINT32();
maxPacketSize = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_OPEN packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN);
tw.writeString("session");
tw.writeUINT32(channelID);
tw.writeUINT32(initialWindowSize);
tw.writeUINT32(maxPacketSize);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketOpenSessionChannel.java | Java | asf20 | 1,578 |
package com.trilead.ssh2.packets;
/**
* PacketSessionX11Request.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionX11Request.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionX11Request
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public boolean singleConnection;
String x11AuthenticationProtocol;
String x11AuthenticationCookie;
int x11ScreenNumber;
public PacketSessionX11Request(int recipientChannelID, boolean wantReply, boolean singleConnection,
String x11AuthenticationProtocol, String x11AuthenticationCookie, int x11ScreenNumber)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.singleConnection = singleConnection;
this.x11AuthenticationProtocol = x11AuthenticationProtocol;
this.x11AuthenticationCookie = x11AuthenticationCookie;
this.x11ScreenNumber = x11ScreenNumber;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("x11-req");
tw.writeBoolean(wantReply);
tw.writeBoolean(singleConnection);
tw.writeString(x11AuthenticationProtocol);
tw.writeString(x11AuthenticationCookie);
tw.writeUINT32(x11ScreenNumber);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketSessionX11Request.java | Java | asf20 | 1,461 |
package com.trilead.ssh2.packets;
import com.trilead.ssh2.DHGexParameters;
/**
* PacketKexDhGexRequestOld.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexRequestOld.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexRequestOld
{
byte[] payload;
int n;
public PacketKexDhGexRequestOld(DHGexParameters para)
{
this.n = para.getPref_group_len();
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_REQUEST_OLD);
tw.writeUINT32(n);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexDhGexRequestOld.java | Java | asf20 | 690 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthBanner.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthBanner.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthBanner
{
byte[] payload;
String message;
String language;
public PacketUserauthBanner(String message, String language)
{
this.message = message;
this.language = language;
}
public String getBanner()
{
return message;
}
public PacketUserauthBanner(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_BANNER)
throw new IOException("This is not a SSH_MSG_USERAUTH_BANNER! (" + packet_type + ")");
message = tr.readString("UTF-8");
language = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_BANNER);
tw.writeString(message);
tw.writeString(language);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthBanner.java | Java | asf20 | 1,401 |
package com.trilead.ssh2.packets;
/**
* PacketUserauthInfoResponse.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthInfoResponse.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthInfoResponse
{
byte[] payload;
String[] responses;
public PacketUserauthInfoResponse(String[] responses)
{
this.responses = responses;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_INFO_RESPONSE);
tw.writeUINT32(responses.length);
for (int i = 0; i < responses.length; i++)
tw.writeString(responses[i]);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketUserauthInfoResponse.java | Java | asf20 | 757 |
package com.trilead.ssh2.packets;
/**
* PacketSessionPtyRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionPtyRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionPtyRequest
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String term;
public int character_width;
public int character_height;
public int pixel_width;
public int pixel_height;
public byte[] terminal_modes;
public PacketSessionPtyRequest(int recipientChannelID, boolean wantReply, String term,
int character_width, int character_height, int pixel_width, int pixel_height,
byte[] terminal_modes)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.term = term;
this.character_width = character_width;
this.character_height = character_height;
this.pixel_width = pixel_width;
this.pixel_height = pixel_height;
this.terminal_modes = terminal_modes;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("pty-req");
tw.writeBoolean(wantReply);
tw.writeString(term);
tw.writeUINT32(character_width);
tw.writeUINT32(character_height);
tw.writeUINT32(pixel_width);
tw.writeUINT32(pixel_height);
tw.writeString(terminal_modes, 0, terminal_modes.length);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketSessionPtyRequest.java | Java | asf20 | 1,574 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketDisconnect.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketDisconnect.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PacketDisconnect
{
byte[] payload;
int reason;
String desc;
String lang;
public PacketDisconnect(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_DISCONNECT)
throw new IOException("This is not a Disconnect Packet! (" + packet_type + ")");
reason = tr.readUINT32();
desc = tr.readString();
lang = tr.readString();
}
public PacketDisconnect(int reason, String desc, String lang)
{
this.reason = reason;
this.desc = desc;
this.lang = lang;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_DISCONNECT);
tw.writeUINT32(reason);
tw.writeString(desc);
tw.writeString(lang);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketDisconnect.java | Java | asf20 | 1,267 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketServiceAccept.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketServiceAccept.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PacketServiceAccept
{
byte[] payload;
String serviceName;
public PacketServiceAccept(String serviceName)
{
this.serviceName = serviceName;
}
public PacketServiceAccept(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_SERVICE_ACCEPT)
throw new IOException("This is not a SSH_MSG_SERVICE_ACCEPT! (" + packet_type + ")");
/* Be clever in case the server is not. Some servers seem to violate RFC4253 */
if (tr.remain() > 0)
{
serviceName = tr.readString();
}
else
{
serviceName = "";
}
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_SERVICE_ACCEPT packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_SERVICE_ACCEPT);
tw.writeString(serviceName);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketServiceAccept.java | Java | asf20 | 1,386 |
package com.trilead.ssh2.packets;
import java.math.BigInteger;
/**
* PacketKexDHInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDHInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDHInit
{
byte[] payload;
BigInteger e;
public PacketKexDHInit(BigInteger e)
{
this.e = e;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEXDH_INIT);
tw.writeMPInt(e);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexDHInit.java | Java | asf20 | 603 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketChannelOpenConfirmation.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelOpenConfirmation.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketChannelOpenConfirmation
{
byte[] payload;
public int recipientChannelID;
public int senderChannelID;
public int initialWindowSize;
public int maxPacketSize;
public PacketChannelOpenConfirmation(int recipientChannelID, int senderChannelID, int initialWindowSize,
int maxPacketSize)
{
this.recipientChannelID = recipientChannelID;
this.senderChannelID = senderChannelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
}
public PacketChannelOpenConfirmation(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION)
throw new IOException(
"This is not a SSH_MSG_CHANNEL_OPEN_CONFIRMATION! ("
+ packet_type + ")");
recipientChannelID = tr.readUINT32();
senderChannelID = tr.readUINT32();
initialWindowSize = tr.readUINT32();
maxPacketSize = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
tw.writeUINT32(recipientChannelID);
tw.writeUINT32(senderChannelID);
tw.writeUINT32(initialWindowSize);
tw.writeUINT32(maxPacketSize);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketChannelOpenConfirmation.java | Java | asf20 | 1,889 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.security.SecureRandom;
import com.trilead.ssh2.compression.CompressionFactory;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.transport.KexParameters;
/**
* PacketKexInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexInit
{
byte[] payload;
KexParameters kp = new KexParameters();
public PacketKexInit(CryptoWishList cwl, SecureRandom rnd)
{
kp.cookie = new byte[16];
rnd.nextBytes(kp.cookie);
kp.kex_algorithms = cwl.kexAlgorithms;
kp.server_host_key_algorithms = cwl.serverHostKeyAlgorithms;
kp.encryption_algorithms_client_to_server = cwl.c2s_enc_algos;
kp.encryption_algorithms_server_to_client = cwl.s2c_enc_algos;
kp.mac_algorithms_client_to_server = cwl.c2s_mac_algos;
kp.mac_algorithms_server_to_client = cwl.s2c_mac_algos;
kp.compression_algorithms_client_to_server = cwl.c2s_comp_algos;
kp.compression_algorithms_server_to_client = cwl.s2c_comp_algos;
kp.languages_client_to_server = new String[] {};
kp.languages_server_to_client = new String[] {};
kp.first_kex_packet_follows = false;
kp.reserved_field1 = 0;
}
public PacketKexInit(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEXINIT)
throw new IOException("This is not a KexInitPacket! (" + packet_type + ")");
kp.cookie = tr.readBytes(16);
kp.kex_algorithms = tr.readNameList();
kp.server_host_key_algorithms = tr.readNameList();
kp.encryption_algorithms_client_to_server = tr.readNameList();
kp.encryption_algorithms_server_to_client = tr.readNameList();
kp.mac_algorithms_client_to_server = tr.readNameList();
kp.mac_algorithms_server_to_client = tr.readNameList();
kp.compression_algorithms_client_to_server = tr.readNameList();
kp.compression_algorithms_server_to_client = tr.readNameList();
kp.languages_client_to_server = tr.readNameList();
kp.languages_server_to_client = tr.readNameList();
kp.first_kex_packet_follows = tr.readBoolean();
kp.reserved_field1 = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in KexInitPacket!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEXINIT);
tw.writeBytes(kp.cookie, 0, 16);
tw.writeNameList(kp.kex_algorithms);
tw.writeNameList(kp.server_host_key_algorithms);
tw.writeNameList(kp.encryption_algorithms_client_to_server);
tw.writeNameList(kp.encryption_algorithms_server_to_client);
tw.writeNameList(kp.mac_algorithms_client_to_server);
tw.writeNameList(kp.mac_algorithms_server_to_client);
tw.writeNameList(kp.compression_algorithms_client_to_server);
tw.writeNameList(kp.compression_algorithms_server_to_client);
tw.writeNameList(kp.languages_client_to_server);
tw.writeNameList(kp.languages_server_to_client);
tw.writeBoolean(kp.first_kex_packet_follows);
tw.writeUINT32(kp.reserved_field1);
payload = tw.getBytes();
}
return payload;
}
public KexParameters getKexParameters()
{
return kp;
}
public String[] getCompression_algorithms_client_to_server()
{
return kp.compression_algorithms_client_to_server;
}
public String[] getCompression_algorithms_server_to_client()
{
return kp.compression_algorithms_server_to_client;
}
public byte[] getCookie()
{
return kp.cookie;
}
public String[] getEncryption_algorithms_client_to_server()
{
return kp.encryption_algorithms_client_to_server;
}
public String[] getEncryption_algorithms_server_to_client()
{
return kp.encryption_algorithms_server_to_client;
}
public boolean isFirst_kex_packet_follows()
{
return kp.first_kex_packet_follows;
}
public String[] getKex_algorithms()
{
return kp.kex_algorithms;
}
public String[] getLanguages_client_to_server()
{
return kp.languages_client_to_server;
}
public String[] getLanguages_server_to_client()
{
return kp.languages_server_to_client;
}
public String[] getMac_algorithms_client_to_server()
{
return kp.mac_algorithms_client_to_server;
}
public String[] getMac_algorithms_server_to_client()
{
return kp.mac_algorithms_server_to_client;
}
public int getReserved_field1()
{
return kp.reserved_field1;
}
public String[] getServer_host_key_algorithms()
{
return kp.server_host_key_algorithms;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketKexInit.java | Java | asf20 | 4,829 |
package com.trilead.ssh2.packets;
/**
* PacketGlobalTrileadPing.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalTrileadPing.java,v 1.1 2008/03/03 07:01:36 cplattne Exp $
*/
public class PacketGlobalTrileadPing
{
byte[] payload;
public PacketGlobalTrileadPing()
{
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("trilead-ping");
tw.writeBoolean(true);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketGlobalTrileadPing.java | Java | asf20 | 612 |
package com.trilead.ssh2.packets;
/**
* PacketGlobalForwardRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalForwardRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketGlobalForwardRequest
{
byte[] payload;
public boolean wantReply;
public String bindAddress;
public int bindPort;
public PacketGlobalForwardRequest(boolean wantReply, String bindAddress, int bindPort)
{
this.wantReply = wantReply;
this.bindAddress = bindAddress;
this.bindPort = bindPort;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("tcpip-forward");
tw.writeBoolean(wantReply);
tw.writeString(bindAddress);
tw.writeUINT32(bindPort);
payload = tw.getBytes();
}
return payload;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/packets/PacketGlobalForwardRequest.java | Java | asf20 | 921 |
package com.trilead.ssh2;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.LocalAcceptThread;
/**
* A <code>LocalPortForwarder</code> forwards TCP/IP connections to a local
* port via the secure tunnel to another host (which may or may not be identical
* to the remote SSH-2 server). Checkout {@link Connection#createLocalPortForwarder(int, String, int)}
* on how to create one.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: LocalPortForwarder.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class LocalPortForwarder
{
ChannelManager cm;
String host_to_connect;
int port_to_connect;
LocalAcceptThread lat;
LocalPortForwarder(ChannelManager cm, int local_port, String host_to_connect, int port_to_connect)
throws IOException
{
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
lat = new LocalAcceptThread(cm, local_port, host_to_connect, port_to_connect);
lat.setDaemon(true);
lat.start();
}
LocalPortForwarder(ChannelManager cm, InetSocketAddress addr, String host_to_connect, int port_to_connect)
throws IOException
{
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
lat = new LocalAcceptThread(cm, addr, host_to_connect, port_to_connect);
lat.setDaemon(true);
lat.start();
}
/**
* Stop TCP/IP forwarding of newly arriving connections.
*
* @throws IOException
*/
public void close() throws IOException
{
lat.stopWorking();
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/LocalPortForwarder.java | Java | asf20 | 1,682 |
package com.trilead.ssh2;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.util.Vector;
import com.trilead.ssh2.auth.AuthenticationManager;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.crypto.cipher.BlockCipherFactory;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketIgnore;
import com.trilead.ssh2.transport.KexManager;
import com.trilead.ssh2.transport.TransportManager;
import com.trilead.ssh2.util.TimeoutService;
import com.trilead.ssh2.util.TimeoutService.TimeoutToken;
/**
* A <code>Connection</code> is used to establish an encrypted TCP/IP
* connection to a SSH-2 server.
* <p>
* Typically, one
* <ol>
* <li>creates a {@link #Connection(String) Connection} object.</li>
* <li>calls the {@link #connect() connect()} method.</li>
* <li>calls some of the authentication methods (e.g.,
* {@link #authenticateWithPublicKey(String, File, String) authenticateWithPublicKey()}).</li>
* <li>calls one or several times the {@link #openSession() openSession()}
* method.</li>
* <li>finally, one must close the connection and release resources with the
* {@link #close() close()} method.</li>
* </ol>
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Connection.java,v 1.3 2008/04/01 12:38:09 cplattne Exp $
*/
public class Connection
{
/**
* The identifier presented to the SSH-2 server.
*/
public final static String identification = "TrileadSSH2Java_213";
/**
* Will be used to generate all random data needed for the current
* connection. Note: SecureRandom.nextBytes() is thread safe.
*/
private SecureRandom generator;
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported cipher algorithms by this implementation.
*/
public static synchronized String[] getAvailableCiphers()
{
return BlockCipherFactory.getDefaultCipherList();
}
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported MAC algorthims by this implementation.
*/
public static synchronized String[] getAvailableMACs()
{
return MAC.getMacList();
}
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported server host key algorthims by this
* implementation.
*/
public static synchronized String[] getAvailableServerHostKeyAlgorithms()
{
return KexManager.getDefaultServerHostkeyAlgorithmList();
}
private AuthenticationManager am;
private boolean authenticated = false;
private boolean compression = false;
private ChannelManager cm;
private CryptoWishList cryptoWishList = new CryptoWishList();
private DHGexParameters dhgexpara = new DHGexParameters();
private final String hostname;
private final int port;
private TransportManager tm;
private boolean tcpNoDelay = false;
private ProxyData proxyData = null;
private Vector<ConnectionMonitor> connectionMonitors = new Vector<ConnectionMonitor>();
/**
* Prepares a fresh <code>Connection</code> object which can then be used
* to establish a connection to the specified SSH-2 server.
* <p>
* Same as {@link #Connection(String, int) Connection(hostname, 22)}.
*
* @param hostname
* the hostname of the SSH-2 server.
*/
public Connection(String hostname)
{
this(hostname, 22);
}
/**
* Prepares a fresh <code>Connection</code> object which can then be used
* to establish a connection to the specified SSH-2 server.
*
* @param hostname
* the host where we later want to connect to.
* @param port
* port on the server, normally 22.
*/
public Connection(String hostname, int port)
{
this.hostname = hostname;
this.port = port;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* is based on DSA (it uses DSA to sign a challenge sent by the server).
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
*
* @param user
* A <code>String</code> holding the username.
* @param pem
* A <code>String</code> containing the DSA private key of the
* user in OpenSSH key format (PEM, you can't miss the
* "-----BEGIN DSA PRIVATE KEY-----" tag). The string may contain
* linefeeds.
* @param password
* If the PEM string is 3DES encrypted ("DES-EDE3-CBC"), then you
* must specify the password. Otherwise, this argument will be
* ignored and can be set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*
* @deprecated You should use one of the
* {@link #authenticateWithPublicKey(String, File, String) authenticateWithPublicKey()}
* methods, this method is just a wrapper for it and will
* disappear in future builds.
*
*/
public synchronized boolean authenticateWithDSA(String user, String pem, String password) throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (pem == null)
throw new IllegalArgumentException("pem argument is null");
authenticated = am.authenticatePublicKey(user, pem.toCharArray(), password, getOrCreateSecureRND());
return authenticated;
}
/**
* A wrapper that calls
* {@link #authenticateWithKeyboardInteractive(String, String[], InteractiveCallback)
* authenticateWithKeyboardInteractivewith} a <code>null</code> submethod
* list.
*
* @param user
* A <code>String</code> holding the username.
* @param cb
* An <code>InteractiveCallback</code> which will be used to
* determine the responses to the questions asked by the server.
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithKeyboardInteractive(String user, InteractiveCallback cb)
throws IOException
{
return authenticateWithKeyboardInteractive(user, null, cb);
}
/**
* After a successful connect, one has to authenticate oneself. This method
* is based on "keyboard-interactive", specified in
* draft-ietf-secsh-auth-kbdinteract-XX. Basically, you have to define a
* callback object which will be feeded with challenges generated by the
* server. Answers are then sent back to the server. It is possible that the
* callback will be called several times during the invocation of this
* method (e.g., if the server replies to the callback's answer(s) with
* another challenge...)
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
* <p>
* Note: some SSH servers advertise "keyboard-interactive", however, any
* interactive request will be denied (without having sent any challenge to
* the client).
*
* @param user
* A <code>String</code> holding the username.
* @param submethods
* An array of submethod names, see
* draft-ietf-secsh-auth-kbdinteract-XX. May be <code>null</code>
* to indicate an empty list.
* @param cb
* An <code>InteractiveCallback</code> which will be used to
* determine the responses to the questions asked by the server.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithKeyboardInteractive(String user, String[] submethods,
InteractiveCallback cb) throws IOException
{
if (cb == null)
throw new IllegalArgumentException("Callback may not ne NULL!");
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
authenticated = am.authenticateInteractive(user, submethods, cb);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* sends username and password to the server.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
* <p>
* Note: if this method fails, then please double-check that it is actually
* offered by the server (use
* {@link #getRemainingAuthMethods(String) getRemainingAuthMethods()}.
* <p>
* Often, password authentication is disabled, but users are not aware of
* it. Many servers only offer "publickey" and "keyboard-interactive".
* However, even though "keyboard-interactive" *feels* like password
* authentication (e.g., when using the putty or openssh clients) it is
* *not* the same mechanism.
*
* @param user
* @param password
* @return if the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPassword(String user, String password) throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (password == null)
throw new IllegalArgumentException("password argument is null");
authenticated = am.authenticatePassword(user, password);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* can be used to explicitly use the special "none" authentication method
* (where only a username has to be specified).
* <p>
* Note 1: The "none" method may always be tried by clients, however as by
* the specs, the server will not explicitly announce it. In other words,
* the "none" token will never show up in the list returned by
* {@link #getRemainingAuthMethods(String)}.
* <p>
* Note 2: no matter which one of the authenticateWithXXX() methods you
* call, the library will always issue exactly one initial "none"
* authentication request to retrieve the initially allowed list of
* authentication methods by the server. Please read RFC 4252 for the
* details.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If further authentication steps are needed, <code>false</code>
* is returned and one can retry by any other authentication method (use the
* <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
*
* @param user
* @return if the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithNone(String user) throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
/* Trigger the sending of the PacketUserauthRequestNone packet */
/* (if not already done) */
authenticated = am.authenticateNone(user);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. The
* authentication method "publickey" works by signing a challenge sent by
* the server. The signature is either DSA or RSA based - it just depends on
* the type of private key you specify, either a DSA or RSA private key in
* PEM format. And yes, this is may seem to be a little confusing, the
* method is called "publickey" in the SSH-2 protocol specification, however
* since we need to generate a signature, you actually have to supply a
* private key =).
* <p>
* The private key contained in the PEM file may also be encrypted
* ("Proc-Type: 4,ENCRYPTED"). The library supports DES-CBC and DES-EDE3-CBC
* encryption, as well as the more exotic PEM encrpytions AES-128-CBC,
* AES-192-CBC and AES-256-CBC.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
* <p>
* NOTE PUTTY USERS: Event though your key file may start with
* "-----BEGIN..." it is not in the expected format. You have to convert it
* to the OpenSSH key format by using the "puttygen" tool (can be downloaded
* from the Putty website). Simply load your key and then use the
* "Conversions/Export OpenSSH key" functionality to get a proper PEM file.
*
* @param user
* A <code>String</code> holding the username.
* @param pemPrivateKey
* A <code>char[]</code> containing a DSA or RSA private key of
* the user in OpenSSH key format (PEM, you can't miss the
* "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE
* KEY-----" tag). The char array may contain
* linebreaks/linefeeds.
* @param password
* If the PEM structure is encrypted ("Proc-Type: 4,ENCRYPTED")
* then you must specify a password. Otherwise, this argument
* will be ignored and can be set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user, char[] pemPrivateKey, String password)
throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (pemPrivateKey == null)
throw new IllegalArgumentException("pemPrivateKey argument is null");
authenticated = am.authenticatePublicKey(user, pemPrivateKey, password, getOrCreateSecureRND());
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. The
* authentication method "publickey" works by signing a challenge sent by
* the server. The signature is either DSA or RSA based - it just depends on
* the type of private key you specify, either a DSA or RSA private key in
* PEM format. And yes, this is may seem to be a little confusing, the
* method is called "publickey" in the SSH-2 protocol specification, however
* since we need to generate a signature, you actually have to supply a
* private key =).
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
*
* @param user
* A <code>String</code> holding the username.
* @param key
* A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of
* the user in Trilead object format.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user, Object key)
throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (key == null)
throw new IllegalArgumentException("Key argument is null");
authenticated = am.authenticatePublicKey(user, key, getOrCreateSecureRND());
return authenticated;
}
/**
* A convenience wrapper function which reads in a private key (PEM format,
* either DSA or RSA) and then calls
* <code>authenticateWithPublicKey(String, char[], String)</code>.
* <p>
* NOTE PUTTY USERS: Event though your key file may start with
* "-----BEGIN..." it is not in the expected format. You have to convert it
* to the OpenSSH key format by using the "puttygen" tool (can be downloaded
* from the Putty website). Simply load your key and then use the
* "Conversions/Export OpenSSH key" functionality to get a proper PEM file.
*
* @param user
* A <code>String</code> holding the username.
* @param pemFile
* A <code>File</code> object pointing to a file containing a
* DSA or RSA private key of the user in OpenSSH key format (PEM,
* you can't miss the "-----BEGIN DSA PRIVATE KEY-----" or
* "-----BEGIN RSA PRIVATE KEY-----" tag).
* @param password
* If the PEM file is encrypted then you must specify the
* password. Otherwise, this argument will be ignored and can be
* set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user, File pemFile, String password)
throws IOException
{
if (pemFile == null)
throw new IllegalArgumentException("pemFile argument is null");
char[] buff = new char[256];
CharArrayWriter cw = new CharArrayWriter();
FileReader fr = new FileReader(pemFile);
while (true)
{
int len = fr.read(buff);
if (len < 0)
break;
cw.write(buff, 0, len);
}
fr.close();
return authenticateWithPublicKey(user, cw.toCharArray(), password);
}
/**
* Add a {@link ConnectionMonitor} to this connection. Can be invoked at any
* time, but it is best to add connection monitors before invoking
* <code>connect()</code> to avoid glitches (e.g., you add a connection
* monitor after a successful connect(), but the connection has died in the
* mean time. Then, your connection monitor won't be notified.)
* <p>
* You can add as many monitors as you like.
*
* @see ConnectionMonitor
*
* @param cmon
* An object implementing the <code>ConnectionMonitor</code>
* interface.
*/
public synchronized void addConnectionMonitor(ConnectionMonitor cmon)
{
if (cmon == null)
throw new IllegalArgumentException("cmon argument is null");
connectionMonitors.addElement(cmon);
if (tm != null)
tm.setConnectionMonitors(connectionMonitors);
}
/**
* Controls whether compression is used on the link or not.
* <p>
* Note: This can only be called before connect()
* @param enabled whether to enable compression
* @throws IOException
*/
public synchronized void setCompression(boolean enabled) throws IOException {
if (tm != null)
throw new IOException("Connection to " + hostname + " is already in connected state!");
compression = enabled;
}
/**
* Close the connection to the SSH-2 server. All assigned sessions will be
* closed, too. Can be called at any time. Don't forget to call this once
* you don't need a connection anymore - otherwise the receiver thread may
* run forever.
*/
public synchronized void close()
{
Throwable t = new Throwable("Closed due to user request.");
close(t, false);
}
private void close(Throwable t, boolean hard)
{
if (cm != null)
cm.closeAllChannels();
if (tm != null)
{
tm.close(t, hard == false);
tm = null;
}
am = null;
cm = null;
authenticated = false;
}
/**
* Same as
* {@link #connect(ServerHostKeyVerifier, int, int) connect(null, 0, 0)}.
*
* @return see comments for the
* {@link #connect(ServerHostKeyVerifier, int, int) connect(ServerHostKeyVerifier, int, int)}
* method.
* @throws IOException
*/
public synchronized ConnectionInfo connect() throws IOException
{
return connect(null, 0, 0);
}
/**
* Same as
* {@link #connect(ServerHostKeyVerifier, int, int) connect(verifier, 0, 0)}.
*
* @return see comments for the
* {@link #connect(ServerHostKeyVerifier, int, int) connect(ServerHostKeyVerifier, int, int)}
* method.
* @throws IOException
*/
public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier) throws IOException
{
return connect(verifier, 0, 0);
}
/**
* Connect to the SSH-2 server and, as soon as the server has presented its
* host key, use the
* {@link ServerHostKeyVerifier#verifyServerHostKey(String, int, String,
* byte[]) ServerHostKeyVerifier.verifyServerHostKey()} method of the
* <code>verifier</code> to ask for permission to proceed. If
* <code>verifier</code> is <code>null</code>, then any host key will
* be accepted - this is NOT recommended, since it makes man-in-the-middle
* attackes VERY easy (somebody could put a proxy SSH server between you and
* the real server).
* <p>
* Note: The verifier will be called before doing any crypto calculations
* (i.e., diffie-hellman). Therefore, if you don't like the presented host
* key then no CPU cycles are wasted (and the evil server has less
* information about us).
* <p>
* However, it is still possible that the server presented a fake host key:
* the server cheated (typically a sign for a man-in-the-middle attack) and
* is not able to generate a signature that matches its host key. Don't
* worry, the library will detect such a scenario later when checking the
* signature (the signature cannot be checked before having completed the
* diffie-hellman exchange).
* <p>
* Note 2: The {@link ServerHostKeyVerifier#verifyServerHostKey(String, int,
* String, byte[]) ServerHostKeyVerifier.verifyServerHostKey()} method will
* *NOT* be called from the current thread, the call is being made from a
* background thread (there is a background dispatcher thread for every
* established connection).
* <p>
* Note 3: This method will block as long as the key exchange of the
* underlying connection has not been completed (and you have not specified
* any timeouts).
* <p>
* Note 4: If you want to re-use a connection object that was successfully
* connected, then you must call the {@link #close()} method before invoking
* <code>connect()</code> again.
*
* @param verifier
* An object that implements the {@link ServerHostKeyVerifier}
* interface. Pass <code>null</code> to accept any server host
* key - NOT recommended.
*
* @param connectTimeout
* Connect the underlying TCP socket to the server with the given
* timeout value (non-negative, in milliseconds). Zero means no
* timeout. If a proxy is being used (see
* {@link #setProxyData(ProxyData)}), then this timeout is used
* for the connection establishment to the proxy.
*
* @param kexTimeout
* Timeout for complete connection establishment (non-negative,
* in milliseconds). Zero means no timeout. The timeout counts
* from the moment you invoke the connect() method and is
* cancelled as soon as the first key-exchange round has
* finished. It is possible that the timeout event will be fired
* during the invocation of the <code>verifier</code> callback,
* but it will only have an effect after the
* <code>verifier</code> returns.
*
* @return A {@link ConnectionInfo} object containing the details of the
* established connection.
*
* @throws IOException
* If any problem occurs, e.g., the server's host key is not
* accepted by the <code>verifier</code> or there is problem
* during the initial crypto setup (e.g., the signature sent by
* the server is wrong).
* <p>
* In case of a timeout (either connectTimeout or kexTimeout) a
* SocketTimeoutException is thrown.
* <p>
* An exception may also be thrown if the connection was already
* successfully connected (no matter if the connection broke in
* the mean time) and you invoke <code>connect()</code> again
* without having called {@link #close()} first.
* <p>
* If a HTTP proxy is being used and the proxy refuses the
* connection, then a {@link HTTPProxyException} may be thrown,
* which contains the details returned by the proxy. If the
* proxy is buggy and does not return a proper HTTP response,
* then a normal IOException is thrown instead.
*/
public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier, int connectTimeout, int kexTimeout)
throws IOException
{
final class TimeoutState
{
boolean isCancelled = false;
boolean timeoutSocketClosed = false;
}
if (tm != null)
throw new IOException("Connection to " + hostname + " is already in connected state!");
if (connectTimeout < 0)
throw new IllegalArgumentException("connectTimeout must be non-negative!");
if (kexTimeout < 0)
throw new IllegalArgumentException("kexTimeout must be non-negative!");
final TimeoutState state = new TimeoutState();
tm = new TransportManager(hostname, port);
tm.setConnectionMonitors(connectionMonitors);
// Don't offer compression if not requested
if (!compression) {
cryptoWishList.c2s_comp_algos = new String[] { "none" };
cryptoWishList.s2c_comp_algos = new String[] { "none" };
}
/*
* Make sure that the runnable below will observe the new value of "tm"
* and "state" (the runnable will be executed in a different thread,
* which may be already running, that is why we need a memory barrier
* here). See also the comment in Channel.java if you are interested in
* the details.
*
* OKOK, this is paranoid since adding the runnable to the todo list of
* the TimeoutService will ensure that all writes have been flushed
* before the Runnable reads anything (there is a synchronized block in
* TimeoutService.addTimeoutHandler).
*/
synchronized (tm)
{
/* We could actually synchronize on anything. */
}
try
{
TimeoutToken token = null;
if (kexTimeout > 0)
{
final Runnable timeoutHandler = new Runnable()
{
public void run()
{
synchronized (state)
{
if (state.isCancelled)
return;
state.timeoutSocketClosed = true;
tm.close(new SocketTimeoutException("The connect timeout expired"), false);
}
}
};
long timeoutHorizont = System.currentTimeMillis() + kexTimeout;
token = TimeoutService.addTimeoutHandler(timeoutHorizont, timeoutHandler);
}
try
{
tm.initialize(cryptoWishList, verifier, dhgexpara, connectTimeout, getOrCreateSecureRND(), proxyData);
}
catch (SocketTimeoutException se)
{
throw (SocketTimeoutException) new SocketTimeoutException(
"The connect() operation on the socket timed out.").initCause(se);
}
tm.setTcpNoDelay(tcpNoDelay);
/* Wait until first KEX has finished */
ConnectionInfo ci = tm.getConnectionInfo(1);
/* Now try to cancel the timeout, if needed */
if (token != null)
{
TimeoutService.cancelTimeoutHandler(token);
/* Were we too late? */
synchronized (state)
{
if (state.timeoutSocketClosed)
throw new IOException("This exception will be replaced by the one below =)");
/*
* Just in case the "cancelTimeoutHandler" invocation came
* just a little bit too late but the handler did not enter
* the semaphore yet - we can still stop it.
*/
state.isCancelled = true;
}
}
return ci;
}
catch (SocketTimeoutException ste)
{
throw ste;
}
catch (IOException e1)
{
/* This will also invoke any registered connection monitors */
close(new Throwable("There was a problem during connect."), false);
synchronized (state)
{
/*
* Show a clean exception, not something like "the socket is
* closed!?!"
*/
if (state.timeoutSocketClosed)
throw new SocketTimeoutException("The kexTimeout (" + kexTimeout + " ms) expired.");
}
/* Do not wrap a HTTPProxyException */
if (e1 instanceof HTTPProxyException)
throw e1;
throw (IOException) new IOException("There was a problem while connecting to " + hostname + ":" + port)
.initCause(e1);
}
}
/**
* Creates a new {@link LocalPortForwarder}. A
* <code>LocalPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host (which may or may
* not be identical to the remote SSH-2 server).
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param local_port
* the local port the LocalPortForwarder shall bind to.
* @param host_to_connect
* target address (IP or hostname)
* @param port_to_connect
* target port
* @return A {@link LocalPortForwarder} object.
* @throws IOException
*/
public synchronized LocalPortForwarder createLocalPortForwarder(int local_port, String host_to_connect,
int port_to_connect) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new LocalPortForwarder(cm, local_port, host_to_connect, port_to_connect);
}
/**
* Creates a new {@link LocalPortForwarder}. A
* <code>LocalPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host (which may or may
* not be identical to the remote SSH-2 server).
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param addr
* specifies the InetSocketAddress where the local socket shall
* be bound to.
* @param host_to_connect
* target address (IP or hostname)
* @param port_to_connect
* target port
* @return A {@link LocalPortForwarder} object.
* @throws IOException
*/
public synchronized LocalPortForwarder createLocalPortForwarder(InetSocketAddress addr, String host_to_connect,
int port_to_connect) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new LocalPortForwarder(cm, addr, host_to_connect, port_to_connect);
}
/**
* Creates a new {@link LocalStreamForwarder}. A
* <code>LocalStreamForwarder</code> manages an Input/Outputstream pair
* that is being forwarded via the secure tunnel into a TCP/IP connection to
* another host (which may or may not be identical to the remote SSH-2
* server).
*
* @param host_to_connect
* @param port_to_connect
* @return A {@link LocalStreamForwarder} object.
* @throws IOException
*/
public synchronized LocalStreamForwarder createLocalStreamForwarder(String host_to_connect, int port_to_connect)
throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward, connection is not authenticated.");
return new LocalStreamForwarder(cm, host_to_connect, port_to_connect);
}
/**
* Creates a new {@link DynamicPortForwarder}. A
* <code>DynamicPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host that is chosen via
* the SOCKS protocol.
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param local_port
* @return A {@link DynamicPortForwarder} object.
* @throws IOException
*/
public synchronized DynamicPortForwarder createDynamicPortForwarder(int local_port) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new DynamicPortForwarder(cm, local_port);
}
/**
* Creates a new {@link DynamicPortForwarder}. A
* <code>DynamicPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host that is chosen via
* the SOCKS protocol.
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param addr
* specifies the InetSocketAddress where the local socket shall
* be bound to.
* @return A {@link DynamicPortForwarder} object.
* @throws IOException
*/
public synchronized DynamicPortForwarder createDynamicPortForwarder(InetSocketAddress addr) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new DynamicPortForwarder(cm, addr);
}
/**
* Create a very basic {@link SCPClient} that can be used to copy files
* from/to the SSH-2 server.
* <p>
* Works only after one has passed successfully the authentication step.
* There is no limit on the number of concurrent SCP clients.
* <p>
* Note: This factory method will probably disappear in the future.
*
* @return A {@link SCPClient} object.
* @throws IOException
*/
public synchronized SCPClient createSCPClient() throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot create SCP client, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot create SCP client, connection is not authenticated.");
return new SCPClient(this);
}
/**
* Force an asynchronous key re-exchange (the call does not block). The
* latest values set for MAC, Cipher and DH group exchange parameters will
* be used. If a key exchange is currently in progress, then this method has
* the only effect that the so far specified parameters will be used for the
* next (server driven) key exchange.
* <p>
* Note: This implementation will never start a key exchange (other than the
* initial one) unless you or the SSH-2 server ask for it.
*
* @throws IOException
* In case of any failure behind the scenes.
*/
public synchronized void forceKeyExchange() throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
tm.forceKeyExchange(cryptoWishList, dhgexpara);
}
/**
* Returns the hostname that was passed to the constructor.
*
* @return the hostname
*/
public synchronized String getHostname()
{
return hostname;
}
/**
* Returns the port that was passed to the constructor.
*
* @return the TCP port
*/
public synchronized int getPort()
{
return port;
}
/**
* Returns a {@link ConnectionInfo} object containing the details of the
* connection. Can be called as soon as the connection has been established
* (successfully connected).
*
* @return A {@link ConnectionInfo} object.
* @throws IOException
* In case of any failure behind the scenes.
*/
public synchronized ConnectionInfo getConnectionInfo() throws IOException
{
if (tm == null)
throw new IllegalStateException(
"Cannot get details of connection, you need to establish a connection first.");
return tm.getConnectionInfo(1);
}
/**
* After a successful connect, one has to authenticate oneself. This method
* can be used to tell which authentication methods are supported by the
* server at a certain stage of the authentication process (for the given
* username).
* <p>
* Note 1: the username will only be used if no authentication step was done
* so far (it will be used to ask the server for a list of possible
* authentication methods by sending the initial "none" request). Otherwise,
* this method ignores the user name and returns a cached method list (which
* is based on the information contained in the last negative server
* response).
* <p>
* Note 2: the server may return method names that are not supported by this
* implementation.
* <p>
* After a successful authentication, this method must not be called
* anymore.
*
* @param user
* A <code>String</code> holding the username.
*
* @return a (possibly emtpy) array holding authentication method names.
* @throws IOException
*/
public synchronized String[] getRemainingAuthMethods(String user) throws IOException
{
if (user == null)
throw new IllegalArgumentException("user argument may not be NULL!");
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
return am.getRemainingMethods(user);
}
/**
* Determines if the authentication phase is complete. Can be called at any
* time.
*
* @return <code>true</code> if no further authentication steps are
* needed.
*/
public synchronized boolean isAuthenticationComplete()
{
return authenticated;
}
/**
* Returns true if there was at least one failed authentication request and
* the last failed authentication request was marked with "partial success"
* by the server. This is only needed in the rare case of SSH-2 server
* setups that cannot be satisfied with a single successful authentication
* request (i.e., multiple authentication steps are needed.)
* <p>
* If you are interested in the details, then have a look at RFC4252.
*
* @return if the there was a failed authentication step and the last one
* was marked as a "partial success".
*/
public synchronized boolean isAuthenticationPartialSuccess()
{
if (am == null)
return false;
return am.getPartialSuccess();
}
/**
* Checks if a specified authentication method is available. This method is
* actually just a wrapper for {@link #getRemainingAuthMethods(String)
* getRemainingAuthMethods()}.
*
* @param user
* A <code>String</code> holding the username.
* @param method
* An authentication method name (e.g., "publickey", "password",
* "keyboard-interactive") as specified by the SSH-2 standard.
* @return if the specified authentication method is currently available.
* @throws IOException
*/
public synchronized boolean isAuthMethodAvailable(String user, String method) throws IOException
{
if (method == null)
throw new IllegalArgumentException("method argument may not be NULL!");
String methods[] = getRemainingAuthMethods(user);
for (int i = 0; i < methods.length; i++)
{
if (methods[i].compareTo(method) == 0)
return true;
}
return false;
}
private final SecureRandom getOrCreateSecureRND()
{
if (generator == null)
generator = new SecureRandom();
return generator;
}
/**
* Open a new {@link Session} on this connection. Works only after one has
* passed successfully the authentication step. There is no limit on the
* number of concurrent sessions.
*
* @return A {@link Session} object.
* @throws IOException
*/
public synchronized Session openSession() throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot open session, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot open session, connection is not authenticated.");
return new Session(cm, getOrCreateSecureRND());
}
/**
* Send an SSH_MSG_IGNORE packet. This method will generate a random data
* attribute (length between 0 (invlusive) and 16 (exclusive) bytes,
* contents are random bytes).
* <p>
* This method must only be called once the connection is established.
*
* @throws IOException
*/
public synchronized void sendIgnorePacket() throws IOException
{
SecureRandom rnd = getOrCreateSecureRND();
byte[] data = new byte[rnd.nextInt(16)];
rnd.nextBytes(data);
sendIgnorePacket(data);
}
/**
* Send an SSH_MSG_IGNORE packet with the given data attribute.
* <p>
* This method must only be called once the connection is established.
*
* @throws IOException
*/
public synchronized void sendIgnorePacket(byte[] data) throws IOException
{
if (data == null)
throw new IllegalArgumentException("data argument must not be null.");
if (tm == null)
throw new IllegalStateException(
"Cannot send SSH_MSG_IGNORE packet, you need to establish a connection first.");
PacketIgnore pi = new PacketIgnore();
pi.setData(data);
tm.sendMessage(pi.getPayload());
}
/**
* Removes duplicates from a String array, keeps only first occurence of
* each element. Does not destroy order of elements; can handle nulls. Uses
* a very efficient O(N^2) algorithm =)
*
* @param list
* a String array.
* @return a cleaned String array.
*/
private String[] removeDuplicates(String[] list)
{
if ((list == null) || (list.length < 2))
return list;
String[] list2 = new String[list.length];
int count = 0;
for (int i = 0; i < list.length; i++)
{
boolean duplicate = false;
String element = list[i];
for (int j = 0; j < count; j++)
{
if (((element == null) && (list2[j] == null)) || ((element != null) && (element.equals(list2[j]))))
{
duplicate = true;
break;
}
}
if (duplicate)
continue;
list2[count++] = list[i];
}
if (count == list2.length)
return list2;
String[] tmp = new String[count];
System.arraycopy(list2, 0, tmp, 0, count);
return tmp;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param ciphers
*/
public synchronized void setClient2ServerCiphers(String[] ciphers)
{
if ((ciphers == null) || (ciphers.length == 0))
throw new IllegalArgumentException();
ciphers = removeDuplicates(ciphers);
BlockCipherFactory.checkCipherList(ciphers);
cryptoWishList.c2s_enc_algos = ciphers;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param macs
*/
public synchronized void setClient2ServerMACs(String[] macs)
{
if ((macs == null) || (macs.length == 0))
throw new IllegalArgumentException();
macs = removeDuplicates(macs);
MAC.checkMacList(macs);
cryptoWishList.c2s_mac_algos = macs;
}
/**
* Sets the parameters for the diffie-hellman group exchange. Unless you
* know what you are doing, you will never need this. Default values are
* defined in the {@link DHGexParameters} class.
*
* @param dgp
* {@link DHGexParameters}, non null.
*
*/
public synchronized void setDHGexParameters(DHGexParameters dgp)
{
if (dgp == null)
throw new IllegalArgumentException();
dhgexpara = dgp;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param ciphers
*/
public synchronized void setServer2ClientCiphers(String[] ciphers)
{
if ((ciphers == null) || (ciphers.length == 0))
throw new IllegalArgumentException();
ciphers = removeDuplicates(ciphers);
BlockCipherFactory.checkCipherList(ciphers);
cryptoWishList.s2c_enc_algos = ciphers;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param macs
*/
public synchronized void setServer2ClientMACs(String[] macs)
{
if ((macs == null) || (macs.length == 0))
throw new IllegalArgumentException();
macs = removeDuplicates(macs);
MAC.checkMacList(macs);
cryptoWishList.s2c_mac_algos = macs;
}
/**
* Define the set of allowed server host key algorithms to be used for the
* following key exchange operations.
* <p>
* Unless you know what you are doing, you will never need this.
*
* @param algos
* An array of allowed server host key algorithms. SSH-2 defines
* <code>ssh-dss</code> and <code>ssh-rsa</code>. The
* entries of the array must be ordered after preference, i.e.,
* the entry at index 0 is the most preferred one. You must
* specify at least one entry.
*/
public synchronized void setServerHostKeyAlgorithms(String[] algos)
{
if ((algos == null) || (algos.length == 0))
throw new IllegalArgumentException();
algos = removeDuplicates(algos);
KexManager.checkServerHostkeyAlgorithmsList(algos);
cryptoWishList.serverHostKeyAlgorithms = algos;
}
/**
* Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm) on the
* underlying socket.
* <p>
* Can be called at any time. If the connection has not yet been established
* then the passed value will be stored and set after the socket has been
* set up. The default value that will be used is <code>false</code>.
*
* @param enable
* the argument passed to the <code>Socket.setTCPNoDelay()</code>
* method.
* @throws IOException
*/
public synchronized void setTCPNoDelay(boolean enable) throws IOException
{
tcpNoDelay = enable;
if (tm != null)
tm.setTcpNoDelay(enable);
}
/**
* Used to tell the library that the connection shall be established through
* a proxy server. It only makes sense to call this method before calling
* the {@link #connect() connect()} method.
* <p>
* At the moment, only HTTP proxies are supported.
* <p>
* Note: This method can be called any number of times. The
* {@link #connect() connect()} method will use the value set in the last
* preceding invocation of this method.
*
* @see HTTPProxyData
*
* @param proxyData
* Connection information about the proxy. If <code>null</code>,
* then no proxy will be used (non surprisingly, this is also the
* default).
*/
public synchronized void setProxyData(ProxyData proxyData)
{
this.proxyData = proxyData;
}
/**
* Request a remote port forwarding. If successful, then forwarded
* connections will be redirected to the given target address. You can
* cancle a requested remote port forwarding by calling
* {@link #cancelRemotePortForwarding(int) cancelRemotePortForwarding()}.
* <p>
* A call of this method will block until the peer either agreed or
* disagreed to your request-
* <p>
* Note 1: this method typically fails if you
* <ul>
* <li>pass a port number for which the used remote user has not enough
* permissions (i.e., port < 1024)</li>
* <li>or pass a port number that is already in use on the remote server</li>
* <li>or if remote port forwarding is disabled on the server.</li>
* </ul>
* <p>
* Note 2: (from the openssh man page): By default, the listening socket on
* the server will be bound to the loopback interface only. This may be
* overriden by specifying a bind address. Specifying a remote bind address
* will only succeed if the server's <b>GatewayPorts</b> option is enabled
* (see sshd_config(5)).
*
* @param bindAddress
* address to bind to on the server:
* <ul>
* <li>"" means that connections are to be accepted on all
* protocol families supported by the SSH implementation</li>
* <li>"0.0.0.0" means to listen on all IPv4 addresses</li>
* <li>"::" means to listen on all IPv6 addresses</li>
* <li>"localhost" means to listen on all protocol families
* supported by the SSH implementation on loopback addresses
* only, [RFC3330] and RFC3513]</li>
* <li>"127.0.0.1" and "::1" indicate listening on the loopback
* interfaces for IPv4 and IPv6 respectively</li>
* </ul>
* @param bindPort
* port number to bind on the server (must be > 0)
* @param targetAddress
* the target address (IP or hostname)
* @param targetPort
* the target port
* @throws IOException
*/
public synchronized void requestRemotePortForwarding(String bindAddress, int bindPort, String targetAddress,
int targetPort) throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("The connection is not authenticated.");
if ((bindAddress == null) || (targetAddress == null) || (bindPort <= 0) || (targetPort <= 0))
throw new IllegalArgumentException();
cm.requestGlobalForward(bindAddress, bindPort, targetAddress, targetPort);
}
/**
* Cancel an earlier requested remote port forwarding. Currently active
* forwardings will not be affected (e.g., disrupted). Note that further
* connection forwarding requests may be received until this method has
* returned.
*
* @param bindPort
* the allocated port number on the server
* @throws IOException
* if the remote side refuses the cancel request or another low
* level error occurs (e.g., the underlying connection is
* closed)
*/
public synchronized void cancelRemotePortForwarding(int bindPort) throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("The connection is not authenticated.");
cm.requestCancelGlobalForward(bindPort);
}
/**
* Provide your own instance of SecureRandom. Can be used, e.g., if you want
* to seed the used SecureRandom generator manually.
* <p>
* The SecureRandom instance is used during key exchanges, public key
* authentication, x11 cookie generation and the like.
*
* @param rnd
* a SecureRandom instance
*/
public synchronized void setSecureRandom(SecureRandom rnd)
{
if (rnd == null)
throw new IllegalArgumentException();
this.generator = rnd;
}
/**
* Enable/disable debug logging. <b>Only do this when requested by Trilead
* support.</b>
* <p>
* For speed reasons, some static variables used to check whether debugging
* is enabled are not protected with locks. In other words, if you
* dynamicaly enable/disable debug logging, then some threads may still use
* the old setting. To be on the safe side, enable debugging before doing
* the <code>connect()</code> call.
*
* @param enable
* on/off
* @param logger
* a {@link DebugLogger DebugLogger} instance, <code>null</code>
* means logging using the simple logger which logs all messages
* to to stderr. Ignored if enabled is <code>false</code>
*/
public synchronized void enableDebugging(boolean enable, DebugLogger logger)
{
Logger.enabled = enable;
if (enable == false)
{
Logger.logger = null;
}
else
{
if (logger == null)
{
logger = new DebugLogger()
{
public void log(int level, String className, String message)
{
long now = System.currentTimeMillis();
System.err.println(now + " : " + className + ": " + message);
}
};
}
Logger.logger = logger;
}
}
/**
* This method can be used to perform end-to-end connection testing. It
* sends a 'ping' message to the server and waits for the 'pong' from the
* server.
* <p>
* When this method throws an exception, then you can assume that the
* connection should be abandoned.
* <p>
* Note: Works only after one has passed successfully the authentication
* step.
* <p>
* Implementation details: this method sends a SSH_MSG_GLOBAL_REQUEST
* request ('trilead-ping') to the server and waits for the
* SSH_MSG_REQUEST_FAILURE reply packet from the server.
*
* @throws IOException
* in case of any problem
*/
public synchronized void ping() throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("The connection is not authenticated.");
cm.requestGlobalTrileadPing();
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/Connection.java | Java | asf20 | 56,638 |
package com.trilead.ssh2;
/**
* A callback interface used to implement a client specific method of checking
* server host keys.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ServerHostKeyVerifier.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public interface ServerHostKeyVerifier
{
/**
* The actual verifier method, it will be called by the key exchange code
* on EVERY key exchange - this can happen several times during the lifetime
* of a connection.
* <p>
* Note: SSH-2 servers are allowed to change their hostkey at ANY time.
*
* @param hostname the hostname used to create the {@link Connection} object
* @param port the remote TCP port
* @param serverHostKeyAlgorithm the public key algorithm (<code>ssh-rsa</code> or <code>ssh-dss</code>)
* @param serverHostKey the server's public key blob
* @return if the client wants to accept the server's host key - if not, the
* connection will be closed.
* @throws Exception Will be wrapped with an IOException, extended version of returning false =)
*/
public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey)
throws Exception;
}
| 1030365071-xuechao | src/com/trilead/ssh2/ServerHostKeyVerifier.java | Java | asf20 | 1,248 |
package com.trilead.ssh2.auth;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Vector;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.packets.PacketServiceAccept;
import com.trilead.ssh2.packets.PacketServiceRequest;
import com.trilead.ssh2.packets.PacketUserauthBanner;
import com.trilead.ssh2.packets.PacketUserauthFailure;
import com.trilead.ssh2.packets.PacketUserauthInfoRequest;
import com.trilead.ssh2.packets.PacketUserauthInfoResponse;
import com.trilead.ssh2.packets.PacketUserauthRequestInteractive;
import com.trilead.ssh2.packets.PacketUserauthRequestNone;
import com.trilead.ssh2.packets.PacketUserauthRequestPassword;
import com.trilead.ssh2.packets.PacketUserauthRequestPublicKey;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.packets.TypesWriter;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.DSASignature;
import com.trilead.ssh2.signature.RSAPrivateKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
import com.trilead.ssh2.signature.RSASignature;
import com.trilead.ssh2.transport.MessageHandler;
import com.trilead.ssh2.transport.TransportManager;
/**
* AuthenticationManager.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AuthenticationManager.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class AuthenticationManager implements MessageHandler
{
TransportManager tm;
Vector packets = new Vector();
boolean connectionClosed = false;
String banner;
String[] remainingMethods = new String[0];
boolean isPartialSuccess = false;
boolean authenticated = false;
boolean initDone = false;
public AuthenticationManager(TransportManager tm)
{
this.tm = tm;
}
boolean methodPossible(String methName)
{
if (remainingMethods == null)
return false;
for (int i = 0; i < remainingMethods.length; i++)
{
if (remainingMethods[i].compareTo(methName) == 0)
return true;
}
return false;
}
byte[] deQueue() throws IOException
{
synchronized (packets)
{
while (packets.size() == 0)
{
if (connectionClosed)
throw (IOException) new IOException("The connection is closed.").initCause(tm
.getReasonClosedCause());
try
{
packets.wait();
}
catch (InterruptedException ign)
{
}
}
/* This sequence works with J2ME */
byte[] res = (byte[]) packets.firstElement();
packets.removeElementAt(0);
return res;
}
}
byte[] getNextMessage() throws IOException
{
while (true)
{
byte[] msg = deQueue();
if (msg[0] != Packets.SSH_MSG_USERAUTH_BANNER)
return msg;
PacketUserauthBanner sb = new PacketUserauthBanner(msg, 0, msg.length);
banner = sb.getBanner();
}
}
public String[] getRemainingMethods(String user) throws IOException
{
initialize(user);
return remainingMethods;
}
public boolean getPartialSuccess()
{
return isPartialSuccess;
}
private boolean initialize(String user) throws IOException
{
if (initDone == false)
{
tm.registerMessageHandler(this, 0, 255);
PacketServiceRequest sr = new PacketServiceRequest("ssh-userauth");
tm.sendMessage(sr.getPayload());
PacketUserauthRequestNone urn = new PacketUserauthRequestNone("ssh-connection", user);
tm.sendMessage(urn.getPayload());
byte[] msg = getNextMessage();
new PacketServiceAccept(msg, 0, msg.length);
msg = getNextMessage();
initDone = true;
if (msg[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (msg[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(msg, 0, msg.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
throw new IOException("Unexpected SSH message (type " + msg[0] + ")");
}
return authenticated;
}
public boolean authenticatePublicKey(String user, char[] PEMPrivateKey, String password, SecureRandom rnd)
throws IOException
{
Object key = PEMDecoder.decode(PEMPrivateKey, password);
return authenticatePublicKey(user, key, rnd);
}
public boolean authenticatePublicKey(String user, Object key, SecureRandom rnd)
throws IOException
{
try
{
initialize(user);
if (methodPossible("publickey") == false)
throw new IOException("Authentication method publickey not supported by the server at this stage.");
if (key instanceof DSAPrivateKey)
{
DSAPrivateKey pk = (DSAPrivateKey) key;
byte[] pk_enc = DSASHA1Verify.encodeSSHDSAPublicKey(pk.getPublicKey());
TypesWriter tw = new TypesWriter();
byte[] H = tm.getSessionIdentifier();
tw.writeString(H, 0, H.length);
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(user);
tw.writeString("ssh-connection");
tw.writeString("publickey");
tw.writeBoolean(true);
tw.writeString("ssh-dss");
tw.writeString(pk_enc, 0, pk_enc.length);
byte[] msg = tw.getBytes();
DSASignature ds = DSASHA1Verify.generateSignature(msg, pk, rnd);
byte[] ds_enc = DSASHA1Verify.encodeSSHDSASignature(ds);
PacketUserauthRequestPublicKey ua = new PacketUserauthRequestPublicKey("ssh-connection", user,
"ssh-dss", pk_enc, ds_enc);
tm.sendMessage(ua.getPayload());
}
else if (key instanceof RSAPrivateKey)
{
RSAPrivateKey pk = (RSAPrivateKey) key;
byte[] pk_enc = RSASHA1Verify.encodeSSHRSAPublicKey(pk.getPublicKey());
TypesWriter tw = new TypesWriter();
{
byte[] H = tm.getSessionIdentifier();
tw.writeString(H, 0, H.length);
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(user);
tw.writeString("ssh-connection");
tw.writeString("publickey");
tw.writeBoolean(true);
tw.writeString("ssh-rsa");
tw.writeString(pk_enc, 0, pk_enc.length);
}
byte[] msg = tw.getBytes();
RSASignature ds = RSASHA1Verify.generateSignature(msg, pk);
byte[] rsa_sig_enc = RSASHA1Verify.encodeSSHRSASignature(ds);
PacketUserauthRequestPublicKey ua = new PacketUserauthRequestPublicKey("ssh-connection", user,
"ssh-rsa", pk_enc, rsa_sig_enc);
tm.sendMessage(ua.getPayload());
}
else
{
throw new IOException("Unknown private key type returned by the PEM decoder.");
}
byte[] ar = getNextMessage();
if (ar[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(ar, 0, ar.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
throw new IOException("Unexpected SSH message (type " + ar[0] + ")");
}
catch (IOException e)
{
e.printStackTrace();
tm.close(e, false);
throw (IOException) new IOException("Publickey authentication failed.").initCause(e);
}
}
public boolean authenticateNone(String user) throws IOException
{
try
{
initialize(user);
return authenticated;
}
catch (IOException e)
{
tm.close(e, false);
throw (IOException) new IOException("None authentication failed.").initCause(e);
}
}
public boolean authenticatePassword(String user, String pass) throws IOException
{
try
{
initialize(user);
if (methodPossible("password") == false)
throw new IOException("Authentication method password not supported by the server at this stage.");
PacketUserauthRequestPassword ua = new PacketUserauthRequestPassword("ssh-connection", user, pass);
tm.sendMessage(ua.getPayload());
byte[] ar = getNextMessage();
if (ar[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(ar, 0, ar.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
throw new IOException("Unexpected SSH message (type " + ar[0] + ")");
}
catch (IOException e)
{
tm.close(e, false);
throw (IOException) new IOException("Password authentication failed.").initCause(e);
}
}
public boolean authenticateInteractive(String user, String[] submethods, InteractiveCallback cb) throws IOException
{
try
{
initialize(user);
if (methodPossible("keyboard-interactive") == false)
throw new IOException(
"Authentication method keyboard-interactive not supported by the server at this stage.");
if (submethods == null)
submethods = new String[0];
PacketUserauthRequestInteractive ua = new PacketUserauthRequestInteractive("ssh-connection", user,
submethods);
tm.sendMessage(ua.getPayload());
while (true)
{
byte[] ar = getNextMessage();
if (ar[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(ar, 0, ar.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_INFO_REQUEST)
{
PacketUserauthInfoRequest pui = new PacketUserauthInfoRequest(ar, 0, ar.length);
String[] responses;
try
{
responses = cb.replyToChallenge(pui.getName(), pui.getInstruction(), pui.getNumPrompts(), pui
.getPrompt(), pui.getEcho());
}
catch (Exception e)
{
throw (IOException) new IOException("Exception in callback.").initCause(e);
}
if (responses == null)
throw new IOException("Your callback may not return NULL!");
PacketUserauthInfoResponse puir = new PacketUserauthInfoResponse(responses);
tm.sendMessage(puir.getPayload());
continue;
}
throw new IOException("Unexpected SSH message (type " + ar[0] + ")");
}
}
catch (IOException e)
{
tm.close(e, false);
throw (IOException) new IOException("Keyboard-interactive authentication failed.").initCause(e);
}
}
public void handleMessage(byte[] msg, int msglen) throws IOException
{
synchronized (packets)
{
if (msg == null)
{
connectionClosed = true;
}
else
{
byte[] tmp = new byte[msglen];
System.arraycopy(msg, 0, tmp, 0, msglen);
packets.addElement(tmp);
}
packets.notifyAll();
if (packets.size() > 5)
{
connectionClosed = true;
throw new IOException("Error, peer is flooding us with authentication packets.");
}
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/auth/AuthenticationManager.java | Java | asf20 | 11,374 |
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
/**
* A <code>StreamGobbler</code> is an InputStream that uses an internal worker
* thread to constantly consume input from another InputStream. It uses a buffer
* to store the consumed data. The buffer size is automatically adjusted, if needed.
* <p>
* This class is sometimes very convenient - if you wrap a session's STDOUT and STDERR
* InputStreams with instances of this class, then you don't have to bother about
* the shared window of STDOUT and STDERR in the low level SSH-2 protocol,
* since all arriving data will be immediatelly consumed by the worker threads.
* Also, as a side effect, the streams will be buffered (e.g., single byte
* read() operations are faster).
* <p>
* Other SSH for Java libraries include this functionality by default in
* their STDOUT and STDERR InputStream implementations, however, please be aware
* that this approach has also a downside:
* <p>
* If you do not call the StreamGobbler's <code>read()</code> method often enough
* and the peer is constantly sending huge amounts of data, then you will sooner or later
* encounter a low memory situation due to the aggregated data (well, it also depends on the Java heap size).
* Joe Average will like this class anyway - a paranoid programmer would never use such an approach.
* <p>
* The term "StreamGobbler" was taken from an article called "When Runtime.exec() won't",
* see http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: StreamGobbler.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class StreamGobbler extends InputStream
{
class GobblerThread extends Thread
{
public void run()
{
byte[] buff = new byte[8192];
while (true)
{
try
{
int avail = is.read(buff);
synchronized (synchronizer)
{
if (avail <= 0)
{
isEOF = true;
synchronizer.notifyAll();
break;
}
int space_available = buffer.length - write_pos;
if (space_available < avail)
{
/* compact/resize buffer */
int unread_size = write_pos - read_pos;
int need_space = unread_size + avail;
byte[] new_buffer = buffer;
if (need_space > buffer.length)
{
int inc = need_space / 3;
inc = (inc < 256) ? 256 : inc;
inc = (inc > 8192) ? 8192 : inc;
new_buffer = new byte[need_space + inc];
}
if (unread_size > 0)
System.arraycopy(buffer, read_pos, new_buffer, 0, unread_size);
buffer = new_buffer;
read_pos = 0;
write_pos = unread_size;
}
System.arraycopy(buff, 0, buffer, write_pos, avail);
write_pos += avail;
synchronizer.notifyAll();
}
}
catch (IOException e)
{
synchronized (synchronizer)
{
exception = e;
synchronizer.notifyAll();
break;
}
}
}
}
}
private InputStream is;
private GobblerThread t;
private Object synchronizer = new Object();
private boolean isEOF = false;
private boolean isClosed = false;
private IOException exception = null;
private byte[] buffer = new byte[2048];
private int read_pos = 0;
private int write_pos = 0;
public StreamGobbler(InputStream is)
{
this.is = is;
t = new GobblerThread();
t.setDaemon(true);
t.start();
}
public int read() throws IOException
{
synchronized (synchronizer)
{
if (isClosed)
throw new IOException("This StreamGobbler is closed.");
while (read_pos == write_pos)
{
if (exception != null)
throw exception;
if (isEOF)
return -1;
try
{
synchronizer.wait();
}
catch (InterruptedException e)
{
}
}
int b = buffer[read_pos++] & 0xff;
return b;
}
}
public int available() throws IOException
{
synchronized (synchronizer)
{
if (isClosed)
throw new IOException("This StreamGobbler is closed.");
return write_pos - read_pos;
}
}
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
public void close() throws IOException
{
synchronized (synchronizer)
{
if (isClosed)
return;
isClosed = true;
isEOF = true;
synchronizer.notifyAll();
is.close();
}
}
public int read(byte[] b, int off, int len) throws IOException
{
if (b == null)
throw new NullPointerException();
if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
throw new IndexOutOfBoundsException();
if (len == 0)
return 0;
synchronized (synchronizer)
{
if (isClosed)
throw new IOException("This StreamGobbler is closed.");
while (read_pos == write_pos)
{
if (exception != null)
throw exception;
if (isEOF)
return -1;
try
{
synchronizer.wait();
}
catch (InterruptedException e)
{
}
}
int avail = write_pos - read_pos;
avail = (avail > len) ? len : avail;
System.arraycopy(buffer, read_pos, b, off, avail);
read_pos += avail;
return avail;
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/StreamGobbler.java | Java | asf20 | 5,412 |
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import com.trilead.ssh2.channel.Channel;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.X11ServerData;
/**
* A <code>Session</code> is a remote execution of a program. "Program" means
* in this context either a shell, an application or a system command. The
* program may or may not have a tty. Only one single program can be started on
* a session. However, multiple sessions can be active simultaneously.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Session.java,v 1.2 2008/03/03 07:01:36 cplattne Exp $
*/
public class Session
{
ChannelManager cm;
Channel cn;
boolean flag_pty_requested = false;
boolean flag_x11_requested = false;
boolean flag_execution_started = false;
boolean flag_closed = false;
String x11FakeCookie = null;
final SecureRandom rnd;
Session(ChannelManager cm, SecureRandom rnd) throws IOException
{
this.cm = cm;
this.cn = cm.openSessionChannel();
this.rnd = rnd;
}
/**
* Basically just a wrapper for lazy people - identical to calling
* <code>requestPTY("dumb", 0, 0, 0, 0, null)</code>.
*
* @throws IOException
*/
public void requestDumbPTY() throws IOException
{
requestPTY("dumb", 0, 0, 0, 0, null);
}
/**
* Basically just another wrapper for lazy people - identical to calling
* <code>requestPTY(term, 0, 0, 0, 0, null)</code>.
*
* @throws IOException
*/
public void requestPTY(String term) throws IOException
{
requestPTY(term, 0, 0, 0, 0, null);
}
/**
* Allocate a pseudo-terminal for this session.
* <p>
* This method may only be called before a program or shell is started in
* this session.
* <p>
* Different aspects can be specified:
* <p>
* <ul>
* <li>The TERM environment variable value (e.g., vt100)</li>
* <li>The terminal's dimensions.</li>
* <li>The encoded terminal modes.</li>
* </ul>
* Zero dimension parameters are ignored. The character/row dimensions
* override the pixel dimensions (when nonzero). Pixel dimensions refer to
* the drawable area of the window. The dimension parameters are only
* informational. The encoding of terminal modes (parameter
* <code>terminal_modes</code>) is described in RFC4254.
*
* @param term
* The TERM environment variable value (e.g., vt100)
* @param term_width_characters
* terminal width, characters (e.g., 80)
* @param term_height_characters
* terminal height, rows (e.g., 24)
* @param term_width_pixels
* terminal width, pixels (e.g., 640)
* @param term_height_pixels
* terminal height, pixels (e.g., 480)
* @param terminal_modes
* encoded terminal modes (may be <code>null</code>)
* @throws IOException
*/
public void requestPTY(String term, int term_width_characters, int term_height_characters, int term_width_pixels,
int term_height_pixels, byte[] terminal_modes) throws IOException
{
if (term == null)
throw new IllegalArgumentException("TERM cannot be null.");
if ((terminal_modes != null) && (terminal_modes.length > 0))
{
if (terminal_modes[terminal_modes.length - 1] != 0)
throw new IOException("Illegal terminal modes description, does not end in zero byte");
}
else
terminal_modes = new byte[] { 0 };
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_pty_requested)
throw new IOException("A PTY was already requested.");
if (flag_execution_started)
throw new IOException(
"Cannot request PTY at this stage anymore, a remote execution has already started.");
flag_pty_requested = true;
}
cm.requestPTY(cn, term, term_width_characters, term_height_characters, term_width_pixels, term_height_pixels,
terminal_modes);
}
/**
* Inform other side of connection that our PTY has resized.
* <p>
* Zero dimension parameters are ignored. The character/row dimensions
* override the pixel dimensions (when nonzero). Pixel dimensions refer to
* the drawable area of the window. The dimension parameters are only
* informational.
*
* @param term_width_characters
* terminal width, characters (e.g., 80)
* @param term_height_characters
* terminal height, rows (e.g., 24)
* @param term_width_pixels
* terminal width, pixels (e.g., 640)
* @param term_height_pixels
* terminal height, pixels (e.g., 480)
* @throws IOException
*/
public void resizePTY(int term_width_characters, int term_height_characters, int term_width_pixels,
int term_height_pixels) throws IOException {
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
}
cm.resizePTY(cn, term_width_characters, term_height_characters, term_width_pixels, term_height_pixels);
}
/**
* Request X11 forwarding for the current session.
* <p>
* You have to supply the name and port of your X-server.
* <p>
* This method may only be called before a program or shell is started in
* this session.
*
* @param hostname the hostname of the real (target) X11 server (e.g., 127.0.0.1)
* @param port the port of the real (target) X11 server (e.g., 6010)
* @param cookie if non-null, then present this cookie to the real X11 server
* @param singleConnection if true, then the server is instructed to only forward one single
* connection, no more connections shall be forwarded after first, or after the session
* channel has been closed
* @throws IOException
*/
public void requestX11Forwarding(String hostname, int port, byte[] cookie, boolean singleConnection)
throws IOException
{
if (hostname == null)
throw new IllegalArgumentException("hostname argument may not be null");
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_x11_requested)
throw new IOException("X11 forwarding was already requested.");
if (flag_execution_started)
throw new IOException(
"Cannot request X11 forwarding at this stage anymore, a remote execution has already started.");
flag_x11_requested = true;
}
/* X11ServerData - used to store data about the target X11 server */
X11ServerData x11data = new X11ServerData();
x11data.hostname = hostname;
x11data.port = port;
x11data.x11_magic_cookie = cookie; /* if non-null, then present this cookie to the real X11 server */
/* Generate fake cookie - this one is used between remote clients and our proxy */
byte[] fakeCookie = new byte[16];
String hexEncodedFakeCookie;
/* Make sure that this fake cookie is unique for this connection */
while (true)
{
rnd.nextBytes(fakeCookie);
/* Generate also hex representation of fake cookie */
StringBuffer tmp = new StringBuffer(32);
for (int i = 0; i < fakeCookie.length; i++)
{
String digit2 = Integer.toHexString(fakeCookie[i] & 0xff);
tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
}
hexEncodedFakeCookie = tmp.toString();
/* Well, yes, chances are low, but we want to be on the safe side */
if (cm.checkX11Cookie(hexEncodedFakeCookie) == null)
break;
}
/* Ask for X11 forwarding */
cm.requestX11(cn, singleConnection, "MIT-MAGIC-COOKIE-1", hexEncodedFakeCookie, 0);
/* OK, that went fine, get ready to accept X11 connections... */
/* ... but only if the user has not called close() in the meantime =) */
synchronized (this)
{
if (flag_closed == false)
{
this.x11FakeCookie = hexEncodedFakeCookie;
cm.registerX11Cookie(hexEncodedFakeCookie, x11data);
}
}
/* Now it is safe to start remote X11 programs */
}
/**
* Execute a command on the remote machine.
*
* @param cmd
* The command to execute on the remote host.
* @throws IOException
*/
public void execCommand(String cmd) throws IOException
{
if (cmd == null)
throw new IllegalArgumentException("cmd argument may not be null");
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_execution_started)
throw new IOException("A remote execution has already started.");
flag_execution_started = true;
}
cm.requestExecCommand(cn, cmd);
}
/**
* Start a shell on the remote machine.
*
* @throws IOException
*/
public void startShell() throws IOException
{
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_execution_started)
throw new IOException("A remote execution has already started.");
flag_execution_started = true;
}
cm.requestShell(cn);
}
/**
* Start a subsystem on the remote machine.
* Unless you know what you are doing, you will never need this.
*
* @param name the name of the subsystem.
* @throws IOException
*/
public void startSubSystem(String name) throws IOException
{
if (name == null)
throw new IllegalArgumentException("name argument may not be null");
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_execution_started)
throw new IOException("A remote execution has already started.");
flag_execution_started = true;
}
cm.requestSubSystem(cn, name);
}
/**
* This method can be used to perform end-to-end session (i.e., SSH channel)
* testing. It sends a 'ping' message to the server and waits for the 'pong'
* from the server.
* <p>
* Implementation details: this method sends a SSH_MSG_CHANNEL_REQUEST request
* ('trilead-ping') to the server and waits for the SSH_MSG_CHANNEL_FAILURE reply
* packet.
*
* @throws IOException in case of any problem or when the session is closed
*/
public void ping() throws IOException
{
synchronized (this)
{
/*
* The following is just a nicer error, we would catch it anyway
* later in the channel code
*/
if (flag_closed)
throw new IOException("This session is closed.");
}
cm.requestChannelTrileadPing(cn);
}
/**
* Request authentication agent forwarding.
* @param agent object that implements the callbacks
*
* @throws IOException in case of any problem or when the session is closed
*/
public synchronized boolean requestAuthAgentForwarding(AuthAgentCallback agent) throws IOException
{
synchronized (this)
{
/*
* The following is just a nicer error, we would catch it anyway
* later in the channel code
*/
if (flag_closed)
throw new IOException("This session is closed.");
}
return cm.requestChannelAgentForwarding(cn, agent);
}
public InputStream getStdout()
{
return cn.getStdoutStream();
}
public InputStream getStderr()
{
return cn.getStderrStream();
}
public OutputStream getStdin()
{
return cn.getStdinStream();
}
/**
* This method blocks until there is more data available on either the
* stdout or stderr InputStream of this <code>Session</code>. Very useful
* if you do not want to use two parallel threads for reading from the two
* InputStreams. One can also specify a timeout. NOTE: do NOT call this
* method if you use concurrent threads that operate on either of the two
* InputStreams of this <code>Session</code> (otherwise this method may
* block, even though more data is available).
*
* @param timeout
* The (non-negative) timeout in <code>ms</code>. <code>0</code> means no
* timeout, the call may block forever.
* @return
* <ul>
* <li><code>0</code> if no more data will arrive.</li>
* <li><code>1</code> if more data is available.</li>
* <li><code>-1</code> if a timeout occurred.</li>
* </ul>
*
* @throws IOException
* @deprecated This method has been replaced with a much more powerful wait-for-condition
* interface and therefore acts only as a wrapper.
*
*/
public int waitUntilDataAvailable(long timeout) throws IOException
{
if (timeout < 0)
throw new IllegalArgumentException("timeout must not be negative!");
int conditions = cm.waitForCondition(cn, timeout, ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA
| ChannelCondition.EOF);
if ((conditions & ChannelCondition.TIMEOUT) != 0)
return -1;
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) != 0)
return 1;
/* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
if ((conditions & ChannelCondition.EOF) != 0)
return 0;
throw new IllegalStateException("Unexpected condition result (" + conditions + ")");
}
/**
* This method blocks until certain conditions hold true on the underlying SSH-2 channel.
* <p>
* This method returns as soon as one of the following happens:
* <ul>
* <li>at least of the specified conditions (see {@link ChannelCondition}) holds true</li>
* <li>timeout > 0 and a timeout occured (TIMEOUT will be set in result conditions)</a>
* <li>the underlying channel was closed (CLOSED will be set in result conditions)</a>
* </ul>
* <p>
* In any case, the result value contains ALL current conditions, which may be more
* than the specified condition set (i.e., never use the "==" operator to test for conditions
* in the bitmask, see also comments in {@link ChannelCondition}).
* <p>
* Note: do NOT call this method if you want to wait for STDOUT_DATA or STDERR_DATA and
* there are concurrent threads (e.g., StreamGobblers) that operate on either of the two
* InputStreams of this <code>Session</code> (otherwise this method may
* block, even though more data is available in the StreamGobblers).
*
* @param condition_set a bitmask based on {@link ChannelCondition} values
* @param timeout non-negative timeout in ms, <code>0</code> means no timeout
* @return all bitmask specifying all current conditions that are true
*/
public int waitForCondition(int condition_set, long timeout)
{
if (timeout < 0)
throw new IllegalArgumentException("timeout must be non-negative!");
return cm.waitForCondition(cn, timeout, condition_set);
}
/**
* Get the exit code/status from the remote command - if available. Be
* careful - not all server implementations return this value. It is
* generally a good idea to call this method only when all data from the
* remote side has been consumed (see also the <code<WaitForCondition</code> method).
*
* @return An <code>Integer</code> holding the exit code, or
* <code>null</code> if no exit code is (yet) available.
*/
public Integer getExitStatus()
{
return cn.getExitStatus();
}
/**
* Get the name of the signal by which the process on the remote side was
* stopped - if available and applicable. Be careful - not all server
* implementations return this value.
*
* @return An <code>String</code> holding the name of the signal, or
* <code>null</code> if the process exited normally or is still
* running (or if the server forgot to send this information).
*/
public String getExitSignal()
{
return cn.getExitSignal();
}
/**
* Close this session. NEVER forget to call this method to free up resources -
* even if you got an exception from one of the other methods (or when
* getting an Exception on the Input- or OutputStreams). Sometimes these other
* methods may throw an exception, saying that the underlying channel is
* closed (this can happen, e.g., if the other server sent a close message.)
* However, as long as you have not called the <code>close()</code>
* method, you may be wasting (local) resources.
*
*/
public void close()
{
synchronized (this)
{
if (flag_closed)
return;
flag_closed = true;
if (x11FakeCookie != null)
cm.unRegisterX11Cookie(x11FakeCookie, true);
try
{
cm.closeChannel(cn, "Closed due to user request", true);
}
catch (IOException ignored)
{
}
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/Session.java | Java | asf20 | 17,299 |
package com.trilead.ssh2;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.digest.Digest;
import com.trilead.ssh2.crypto.digest.HMAC;
import com.trilead.ssh2.crypto.digest.MD5;
import com.trilead.ssh2.crypto.digest.SHA1;
import com.trilead.ssh2.signature.DSAPublicKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.RSAPublicKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
/**
* The <code>KnownHosts</code> class is a handy tool to verify received server hostkeys
* based on the information in <code>known_hosts</code> files (the ones used by OpenSSH).
* <p>
* It offers basically an in-memory database for known_hosts entries, as well as some
* helper functions. Entries from a <code>known_hosts</code> file can be loaded at construction time.
* It is also possible to add more keys later (e.g., one can parse different
* <code>known_hosts<code> files).
* <p>
* It is a thread safe implementation, therefore, you need only to instantiate one
* <code>KnownHosts</code> for your whole application.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KnownHosts.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class KnownHosts
{
public static final int HOSTKEY_IS_OK = 0;
public static final int HOSTKEY_IS_NEW = 1;
public static final int HOSTKEY_HAS_CHANGED = 2;
private class KnownHostsEntry
{
String[] patterns;
Object key;
KnownHostsEntry(String[] patterns, Object key)
{
this.patterns = patterns;
this.key = key;
}
}
private LinkedList publicKeys = new LinkedList();
public KnownHosts()
{
}
public KnownHosts(char[] knownHostsData) throws IOException
{
initialize(knownHostsData);
}
public KnownHosts(File knownHosts) throws IOException
{
initialize(knownHosts);
}
/**
* Adds a single public key entry to the database. Note: this will NOT add the public key
* to any physical file (e.g., "~/.ssh/known_hosts") - use <code>addHostkeyToFile()</code> for that purpose.
* This method is designed to be used in a {@link ServerHostKeyVerifier}.
*
* @param hostnames a list of hostname patterns - at least one most be specified. Check out the
* OpenSSH sshd man page for a description of the pattern matching algorithm.
* @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
* @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
* @throws IOException
*/
public void addHostkey(String hostnames[], String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException
{
if (hostnames == null)
throw new IllegalArgumentException("hostnames may not be null");
if ("ssh-rsa".equals(serverHostKeyAlgorithm))
{
RSAPublicKey rpk = RSASHA1Verify.decodeSSHRSAPublicKey(serverHostKey);
synchronized (publicKeys)
{
publicKeys.add(new KnownHostsEntry(hostnames, rpk));
}
}
else if ("ssh-dss".equals(serverHostKeyAlgorithm))
{
DSAPublicKey dpk = DSASHA1Verify.decodeSSHDSAPublicKey(serverHostKey);
synchronized (publicKeys)
{
publicKeys.add(new KnownHostsEntry(hostnames, dpk));
}
}
else
throw new IOException("Unknwon host key type (" + serverHostKeyAlgorithm + ")");
}
/**
* Parses the given known_hosts data and adds entries to the database.
*
* @param knownHostsData
* @throws IOException
*/
public void addHostkeys(char[] knownHostsData) throws IOException
{
initialize(knownHostsData);
}
/**
* Parses the given known_hosts file and adds entries to the database.
*
* @param knownHosts
* @throws IOException
*/
public void addHostkeys(File knownHosts) throws IOException
{
initialize(knownHosts);
}
/**
* Generate the hashed representation of the given hostname. Useful for adding entries
* with hashed hostnames to a known_hosts file. (see -H option of OpenSSH key-gen).
*
* @param hostname
* @return the hashed representation, e.g., "|1|cDhrv7zwEUV3k71CEPHnhHZezhA=|Xo+2y6rUXo2OIWRAYhBOIijbJMA="
*/
public static final String createHashedHostname(String hostname)
{
SHA1 sha1 = new SHA1();
byte[] salt = new byte[sha1.getDigestLength()];
new SecureRandom().nextBytes(salt);
byte[] hash = hmacSha1Hash(salt, hostname);
String base64_salt = new String(Base64.encode(salt));
String base64_hash = new String(Base64.encode(hash));
return new String("|1|" + base64_salt + "|" + base64_hash);
}
private static final byte[] hmacSha1Hash(byte[] salt, String hostname)
{
SHA1 sha1 = new SHA1();
if (salt.length != sha1.getDigestLength())
throw new IllegalArgumentException("Salt has wrong length (" + salt.length + ")");
HMAC hmac = new HMAC(sha1, salt, salt.length);
try
{
hmac.update(hostname.getBytes("ISO-8859-1"));
}catch(UnsupportedEncodingException ignore)
{
/* Actually, ISO-8859-1 is supported by all correct
* Java implementations. But... you never know. */
hmac.update(hostname.getBytes());
}
byte[] dig = new byte[hmac.getDigestLength()];
hmac.digest(dig);
return dig;
}
private final boolean checkHashed(String entry, String hostname)
{
if (entry.startsWith("|1|") == false)
return false;
int delim_idx = entry.indexOf('|', 3);
if (delim_idx == -1)
return false;
String salt_base64 = entry.substring(3, delim_idx);
String hash_base64 = entry.substring(delim_idx + 1);
byte[] salt = null;
byte[] hash = null;
try
{
salt = Base64.decode(salt_base64.toCharArray());
hash = Base64.decode(hash_base64.toCharArray());
}
catch (IOException e)
{
return false;
}
SHA1 sha1 = new SHA1();
if (salt.length != sha1.getDigestLength())
return false;
byte[] dig = hmacSha1Hash(salt, hostname);
for (int i = 0; i < dig.length; i++)
if (dig[i] != hash[i])
return false;
return true;
}
private int checkKey(String remoteHostname, Object remoteKey)
{
int result = HOSTKEY_IS_NEW;
synchronized (publicKeys)
{
Iterator i = publicKeys.iterator();
while (i.hasNext())
{
KnownHostsEntry ke = (KnownHostsEntry) i.next();
if (hostnameMatches(ke.patterns, remoteHostname) == false)
continue;
boolean res = matchKeys(ke.key, remoteKey);
if (res == true)
return HOSTKEY_IS_OK;
result = HOSTKEY_HAS_CHANGED;
}
}
return result;
}
private Vector getAllKeys(String hostname)
{
Vector keys = new Vector();
synchronized (publicKeys)
{
Iterator i = publicKeys.iterator();
while (i.hasNext())
{
KnownHostsEntry ke = (KnownHostsEntry) i.next();
if (hostnameMatches(ke.patterns, hostname) == false)
continue;
keys.addElement(ke.key);
}
}
return keys;
}
/**
* Try to find the preferred order of hostkey algorithms for the given hostname.
* Based on the type of hostkey that is present in the internal database
* (i.e., either <code>ssh-rsa</code> or <code>ssh-dss</code>)
* an ordered list of hostkey algorithms is returned which can be passed
* to <code>Connection.setServerHostKeyAlgorithms</code>.
*
* @param hostname
* @return <code>null</code> if no key for the given hostname is present or
* there are keys of multiple types present for the given hostname. Otherwise,
* an array with hostkey algorithms is returned (i.e., an array of length 2).
*/
public String[] getPreferredServerHostkeyAlgorithmOrder(String hostname)
{
String[] algos = recommendHostkeyAlgorithms(hostname);
if (algos != null)
return algos;
InetAddress[] ipAdresses = null;
try
{
ipAdresses = InetAddress.getAllByName(hostname);
}
catch (UnknownHostException e)
{
return null;
}
for (int i = 0; i < ipAdresses.length; i++)
{
algos = recommendHostkeyAlgorithms(ipAdresses[i].getHostAddress());
if (algos != null)
return algos;
}
return null;
}
private final boolean hostnameMatches(String[] hostpatterns, String hostname)
{
boolean isMatch = false;
boolean negate = false;
hostname = hostname.toLowerCase();
for (int k = 0; k < hostpatterns.length; k++)
{
if (hostpatterns[k] == null)
continue;
String pattern = null;
/* In contrast to OpenSSH we also allow negated hash entries (as well as hashed
* entries in lines with multiple entries).
*/
if ((hostpatterns[k].length() > 0) && (hostpatterns[k].charAt(0) == '!'))
{
pattern = hostpatterns[k].substring(1);
negate = true;
}
else
{
pattern = hostpatterns[k];
negate = false;
}
/* Optimize, no need to check this entry */
if ((isMatch) && (negate == false))
continue;
/* Now compare */
if (pattern.charAt(0) == '|')
{
if (checkHashed(pattern, hostname))
{
if (negate)
return false;
isMatch = true;
}
}
else
{
pattern = pattern.toLowerCase();
if ((pattern.indexOf('?') != -1) || (pattern.indexOf('*') != -1))
{
if (pseudoRegex(pattern.toCharArray(), 0, hostname.toCharArray(), 0))
{
if (negate)
return false;
isMatch = true;
}
}
else if (pattern.compareTo(hostname) == 0)
{
if (negate)
return false;
isMatch = true;
}
}
}
return isMatch;
}
private void initialize(char[] knownHostsData) throws IOException
{
BufferedReader br = new BufferedReader(new CharArrayReader(knownHostsData));
while (true)
{
String line = br.readLine();
if (line == null)
break;
line = line.trim();
if (line.startsWith("#"))
continue;
String[] arr = line.split(" ");
if (arr.length >= 3)
{
if ((arr[1].compareTo("ssh-rsa") == 0) || (arr[1].compareTo("ssh-dss") == 0))
{
String[] hostnames = arr[0].split(",");
byte[] msg = Base64.decode(arr[2].toCharArray());
addHostkey(hostnames, arr[1], msg);
}
}
}
}
private void initialize(File knownHosts) throws IOException
{
char[] buff = new char[512];
CharArrayWriter cw = new CharArrayWriter();
knownHosts.createNewFile();
FileReader fr = new FileReader(knownHosts);
while (true)
{
int len = fr.read(buff);
if (len < 0)
break;
cw.write(buff, 0, len);
}
fr.close();
initialize(cw.toCharArray());
}
private final boolean matchKeys(Object key1, Object key2)
{
if ((key1 instanceof RSAPublicKey) && (key2 instanceof RSAPublicKey))
{
RSAPublicKey savedRSAKey = (RSAPublicKey) key1;
RSAPublicKey remoteRSAKey = (RSAPublicKey) key2;
if (savedRSAKey.getE().equals(remoteRSAKey.getE()) == false)
return false;
if (savedRSAKey.getN().equals(remoteRSAKey.getN()) == false)
return false;
return true;
}
if ((key1 instanceof DSAPublicKey) && (key2 instanceof DSAPublicKey))
{
DSAPublicKey savedDSAKey = (DSAPublicKey) key1;
DSAPublicKey remoteDSAKey = (DSAPublicKey) key2;
if (savedDSAKey.getG().equals(remoteDSAKey.getG()) == false)
return false;
if (savedDSAKey.getP().equals(remoteDSAKey.getP()) == false)
return false;
if (savedDSAKey.getQ().equals(remoteDSAKey.getQ()) == false)
return false;
if (savedDSAKey.getY().equals(remoteDSAKey.getY()) == false)
return false;
return true;
}
return false;
}
private final boolean pseudoRegex(char[] pattern, int i, char[] match, int j)
{
/* This matching logic is equivalent to the one present in OpenSSH 4.1 */
while (true)
{
/* Are we at the end of the pattern? */
if (pattern.length == i)
return (match.length == j);
if (pattern[i] == '*')
{
i++;
if (pattern.length == i)
return true;
if ((pattern[i] != '*') && (pattern[i] != '?'))
{
while (true)
{
if ((pattern[i] == match[j]) && pseudoRegex(pattern, i + 1, match, j + 1))
return true;
j++;
if (match.length == j)
return false;
}
}
while (true)
{
if (pseudoRegex(pattern, i, match, j))
return true;
j++;
if (match.length == j)
return false;
}
}
if (match.length == j)
return false;
if ((pattern[i] != '?') && (pattern[i] != match[j]))
return false;
i++;
j++;
}
}
private String[] recommendHostkeyAlgorithms(String hostname)
{
String preferredAlgo = null;
Vector keys = getAllKeys(hostname);
for (int i = 0; i < keys.size(); i++)
{
String thisAlgo = null;
if (keys.elementAt(i) instanceof RSAPublicKey)
thisAlgo = "ssh-rsa";
else if (keys.elementAt(i) instanceof DSAPublicKey)
thisAlgo = "ssh-dss";
else
continue;
if (preferredAlgo != null)
{
/* If we find different key types, then return null */
if (preferredAlgo.compareTo(thisAlgo) != 0)
return null;
/* OK, we found the same algo again, optimize */
continue;
}
}
/* If we did not find anything that we know of, return null */
if (preferredAlgo == null)
return null;
/* Now put the preferred algo to the start of the array.
* You may ask yourself why we do it that way - basically, we could just
* return only the preferred algorithm: since we have a saved key of that
* type (sent earlier from the remote host), then that should work out.
* However, imagine that the server is (for whatever reasons) not offering
* that type of hostkey anymore (e.g., "ssh-rsa" was disabled and
* now "ssh-dss" is being used). If we then do not let the server send us
* a fresh key of the new type, then we shoot ourself into the foot:
* the connection cannot be established and hence the user cannot decide
* if he/she wants to accept the new key.
*/
if (preferredAlgo.equals("ssh-rsa"))
return new String[] { "ssh-rsa", "ssh-dss" };
return new String[] { "ssh-dss", "ssh-rsa" };
}
/**
* Checks the internal hostkey database for the given hostkey.
* If no matching key can be found, then the hostname is resolved to an IP address
* and the search is repeated using that IP address.
*
* @param hostname the server's hostname, will be matched with all hostname patterns
* @param serverHostKeyAlgorithm type of hostkey, either <code>ssh-rsa</code> or <code>ssh-dss</code>
* @param serverHostKey the key blob
* @return <ul>
* <li><code>HOSTKEY_IS_OK</code>: the given hostkey matches an entry for the given hostname</li>
* <li><code>HOSTKEY_IS_NEW</code>: no entries found for this hostname and this type of hostkey</li>
* <li><code>HOSTKEY_HAS_CHANGED</code>: hostname is known, but with another key of the same type
* (man-in-the-middle attack?)</li>
* </ul>
* @throws IOException if the supplied key blob cannot be parsed or does not match the given hostkey type.
*/
public int verifyHostkey(String hostname, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException
{
Object remoteKey = null;
if ("ssh-rsa".equals(serverHostKeyAlgorithm))
{
remoteKey = RSASHA1Verify.decodeSSHRSAPublicKey(serverHostKey);
}
else if ("ssh-dss".equals(serverHostKeyAlgorithm))
{
remoteKey = DSASHA1Verify.decodeSSHDSAPublicKey(serverHostKey);
}
else
throw new IllegalArgumentException("Unknown hostkey type " + serverHostKeyAlgorithm);
int result = checkKey(hostname, remoteKey);
if (result == HOSTKEY_IS_OK)
return result;
InetAddress[] ipAdresses = null;
try
{
ipAdresses = InetAddress.getAllByName(hostname);
}
catch (UnknownHostException e)
{
return result;
}
for (int i = 0; i < ipAdresses.length; i++)
{
int newresult = checkKey(ipAdresses[i].getHostAddress(), remoteKey);
if (newresult == HOSTKEY_IS_OK)
return newresult;
if (newresult == HOSTKEY_HAS_CHANGED)
result = HOSTKEY_HAS_CHANGED;
}
return result;
}
/**
* Adds a single public key entry to the a known_hosts file.
* This method is designed to be used in a {@link ServerHostKeyVerifier}.
*
* @param knownHosts the file where the publickey entry will be appended.
* @param hostnames a list of hostname patterns - at least one most be specified. Check out the
* OpenSSH sshd man page for a description of the pattern matching algorithm.
* @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
* @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
* @throws IOException
*/
public final static void addHostkeyToFile(File knownHosts, String[] hostnames, String serverHostKeyAlgorithm,
byte[] serverHostKey) throws IOException
{
if ((hostnames == null) || (hostnames.length == 0))
throw new IllegalArgumentException("Need at least one hostname specification");
if ((serverHostKeyAlgorithm == null) || (serverHostKey == null))
throw new IllegalArgumentException();
CharArrayWriter writer = new CharArrayWriter();
for (int i = 0; i < hostnames.length; i++)
{
if (i != 0)
writer.write(',');
writer.write(hostnames[i]);
}
writer.write(' ');
writer.write(serverHostKeyAlgorithm);
writer.write(' ');
writer.write(Base64.encode(serverHostKey));
writer.write("\n");
char[] entry = writer.toCharArray();
RandomAccessFile raf = new RandomAccessFile(knownHosts, "rw");
long len = raf.length();
if (len > 0)
{
raf.seek(len - 1);
int last = raf.read();
if (last != '\n')
raf.write('\n');
}
raf.write(new String(entry).getBytes("ISO-8859-1"));
raf.close();
}
/**
* Generates a "raw" fingerprint of a hostkey.
*
* @param type either "md5" or "sha1"
* @param keyType either "ssh-rsa" or "ssh-dss"
* @param hostkey the hostkey
* @return the raw fingerprint
*/
static final private byte[] rawFingerPrint(String type, String keyType, byte[] hostkey)
{
Digest dig = null;
if ("md5".equals(type))
{
dig = new MD5();
}
else if ("sha1".equals(type))
{
dig = new SHA1();
}
else
throw new IllegalArgumentException("Unknown hash type " + type);
if ("ssh-rsa".equals(keyType))
{
}
else if ("ssh-dss".equals(keyType))
{
}
else
throw new IllegalArgumentException("Unknown key type " + keyType);
if (hostkey == null)
throw new IllegalArgumentException("hostkey is null");
dig.update(hostkey);
byte[] res = new byte[dig.getDigestLength()];
dig.digest(res);
return res;
}
/**
* Convert a raw fingerprint to hex representation (XX:YY:ZZ...).
* @param fingerprint raw fingerprint
* @return the hex representation
*/
static final private String rawToHexFingerprint(byte[] fingerprint)
{
final char[] alpha = "0123456789abcdef".toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < fingerprint.length; i++)
{
if (i != 0)
sb.append(':');
int b = fingerprint[i] & 0xff;
sb.append(alpha[b >> 4]);
sb.append(alpha[b & 15]);
}
return sb.toString();
}
/**
* Convert a raw fingerprint to bubblebabble representation.
* @param raw raw fingerprint
* @return the bubblebabble representation
*/
static final private String rawToBubblebabbleFingerprint(byte[] raw)
{
final char[] v = "aeiouy".toCharArray();
final char[] c = "bcdfghklmnprstvzx".toCharArray();
StringBuffer sb = new StringBuffer();
int seed = 1;
int rounds = (raw.length / 2) + 1;
sb.append('x');
for (int i = 0; i < rounds; i++)
{
if (((i + 1) < rounds) || ((raw.length) % 2 != 0))
{
sb.append(v[(((raw[2 * i] >> 6) & 3) + seed) % 6]);
sb.append(c[(raw[2 * i] >> 2) & 15]);
sb.append(v[((raw[2 * i] & 3) + (seed / 6)) % 6]);
if ((i + 1) < rounds)
{
sb.append(c[(((raw[(2 * i) + 1])) >> 4) & 15]);
sb.append('-');
sb.append(c[(((raw[(2 * i) + 1]))) & 15]);
// As long as seed >= 0, seed will be >= 0 afterwards
seed = ((seed * 5) + (((raw[2 * i] & 0xff) * 7) + (raw[(2 * i) + 1] & 0xff))) % 36;
}
}
else
{
sb.append(v[seed % 6]); // seed >= 0, therefore index positive
sb.append('x');
sb.append(v[seed / 6]);
}
}
sb.append('x');
return sb.toString();
}
/**
* Convert a ssh2 key-blob into a human readable hex fingerprint.
* Generated fingerprints are identical to those generated by OpenSSH.
* <p>
* Example fingerprint: d0:cb:76:19:99:5a:03:fc:73:10:70:93:f2:44:63:47.
* @param keytype either "ssh-rsa" or "ssh-dss"
* @param publickey key blob
* @return Hex fingerprint
*/
public final static String createHexFingerprint(String keytype, byte[] publickey)
{
byte[] raw = rawFingerPrint("md5", keytype, publickey);
return rawToHexFingerprint(raw);
}
/**
* Convert a ssh2 key-blob into a human readable bubblebabble fingerprint.
* The used bubblebabble algorithm (taken from OpenSSH) generates fingerprints
* that are easier to remember for humans.
* <p>
* Example fingerprint: xofoc-bubuz-cazin-zufyl-pivuk-biduk-tacib-pybur-gonar-hotat-lyxux.
*
* @param keytype either "ssh-rsa" or "ssh-dss"
* @param publickey key data
* @return Bubblebabble fingerprint
*/
public final static String createBubblebabbleFingerprint(String keytype, byte[] publickey)
{
byte[] raw = rawFingerPrint("sha1", keytype, publickey);
return rawToBubblebabbleFingerprint(raw);
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/KnownHosts.java | Java | asf20 | 22,370 |
package com.trilead.ssh2;
import java.io.IOException;
import com.trilead.ssh2.sftp.ErrorCodes;
/**
* Used in combination with the SFTPv3Client. This exception wraps
* error messages sent by the SFTP server.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPException extends IOException
{
private static final long serialVersionUID = 578654644222421811L;
private final String sftpErrorMessage;
private final int sftpErrorCode;
private static String constructMessage(String s, int errorCode)
{
String[] detail = ErrorCodes.getDescription(errorCode);
if (detail == null)
return s + " (UNKNOW SFTP ERROR CODE)";
return s + " (" + detail[0] + ": " + detail[1] + ")";
}
SFTPException(String msg, int errorCode)
{
super(constructMessage(msg, errorCode));
sftpErrorMessage = msg;
sftpErrorCode = errorCode;
}
/**
* Get the error message sent by the server. Often, this
* message does not help a lot (e.g., "failure").
*
* @return the plain string as sent by the server.
*/
public String getServerErrorMessage()
{
return sftpErrorMessage;
}
/**
* Get the error code sent by the server.
*
* @return an error code as defined in the SFTP specs.
*/
public int getServerErrorCode()
{
return sftpErrorCode;
}
/**
* Get the symbolic name of the error code as given in the SFTP specs.
*
* @return e.g., "SSH_FX_INVALID_FILENAME".
*/
public String getServerErrorCodeSymbol()
{
String[] detail = ErrorCodes.getDescription(sftpErrorCode);
if (detail == null)
return "UNKNOW SFTP ERROR CODE " + sftpErrorCode;
return detail[0];
}
/**
* Get the description of the error code as given in the SFTP specs.
*
* @return e.g., "The filename is not valid."
*/
public String getServerErrorCodeVerbose()
{
String[] detail = ErrorCodes.getDescription(sftpErrorCode);
if (detail == null)
return "The error code " + sftpErrorCode + " is unknown.";
return detail[1];
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/SFTPException.java | Java | asf20 | 2,153 |
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.trilead.ssh2.channel.Channel;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.LocalAcceptThread;
/**
* A <code>LocalStreamForwarder</code> forwards an Input- and Outputstream
* pair via the secure tunnel to another host (which may or may not be identical
* to the remote SSH-2 server).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: LocalStreamForwarder.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class LocalStreamForwarder
{
ChannelManager cm;
String host_to_connect;
int port_to_connect;
LocalAcceptThread lat;
Channel cn;
LocalStreamForwarder(ChannelManager cm, String host_to_connect, int port_to_connect) throws IOException
{
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
cn = cm.openDirectTCPIPChannel(host_to_connect, port_to_connect, "127.0.0.1", 0);
}
/**
* @return An <code>InputStream</code> object.
* @throws IOException
*/
public InputStream getInputStream() throws IOException
{
return cn.getStdoutStream();
}
/**
* Get the OutputStream. Please be aware that the implementation MAY use an
* internal buffer. To make sure that the buffered data is sent over the
* tunnel, you have to call the <code>flush</code> method of the
* <code>OutputStream</code>. To signal EOF, please use the
* <code>close</code> method of the <code>OutputStream</code>.
*
* @return An <code>OutputStream</code> object.
* @throws IOException
*/
public OutputStream getOutputStream() throws IOException
{
return cn.getStdinStream();
}
/**
* Close the underlying SSH forwarding channel and free up resources.
* You can also use this method to force the shutdown of the underlying
* forwarding channel. Pending output (OutputStream not flushed) will NOT
* be sent. Pending input (InputStream) can still be read. If the shutdown
* operation is already in progress (initiated from either side), then this
* call is a no-op.
*
* @throws IOException
*/
public void close() throws IOException
{
cm.closeChannel(cn, "Closed due to user request.", true);
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/LocalStreamForwarder.java | Java | asf20 | 2,351 |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.DynamicAcceptThread;
/**
* A <code>DynamicPortForwarder</code> forwards TCP/IP connections to a local
* port via the secure tunnel to another host which is selected via the
* SOCKS protocol. Checkout {@link Connection#createDynamicPortForwarder(int)}
* on how to create one.
*
* @author Kenny Root
* @version $Id: $
*/
public class DynamicPortForwarder {
ChannelManager cm;
DynamicAcceptThread dat;
DynamicPortForwarder(ChannelManager cm, int local_port)
throws IOException
{
this.cm = cm;
dat = new DynamicAcceptThread(cm, local_port);
dat.setDaemon(true);
dat.start();
}
DynamicPortForwarder(ChannelManager cm, InetSocketAddress addr) throws IOException {
this.cm = cm;
dat = new DynamicAcceptThread(cm, addr);
dat.setDaemon(true);
dat.start();
}
/**
* Stop TCP/IP forwarding of newly arriving connections.
*
* @throws IOException
*/
public void close() throws IOException
{
dat.stopWorking();
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/DynamicPortForwarder.java | Java | asf20 | 1,806 |
package com.trilead.ssh2.channel;
/**
* IChannelWorkerThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: IChannelWorkerThread.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
interface IChannelWorkerThread
{
public void stopWorking();
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/IChannelWorkerThread.java | Java | asf20 | 285 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import com.trilead.ssh2.log.Logger;
/**
* RemoteX11AcceptThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RemoteX11AcceptThread.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class RemoteX11AcceptThread extends Thread
{
private static final Logger log = Logger.getLogger(RemoteX11AcceptThread.class);
Channel c;
String remoteOriginatorAddress;
int remoteOriginatorPort;
Socket s;
public RemoteX11AcceptThread(Channel c, String remoteOriginatorAddress, int remoteOriginatorPort)
{
this.c = c;
this.remoteOriginatorAddress = remoteOriginatorAddress;
this.remoteOriginatorPort = remoteOriginatorPort;
}
public void run()
{
try
{
/* Send Open Confirmation */
c.cm.sendOpenConfirmation(c);
/* Read startup packet from client */
OutputStream remote_os = c.getStdinStream();
InputStream remote_is = c.getStdoutStream();
/* The following code is based on the protocol description given in:
* Scheifler/Gettys,
* X Windows System: Core and Extension Protocols:
* X Version 11, Releases 6 and 6.1 ISBN 1-55558-148-X
*/
/*
* Client startup:
*
* 1 0X42 MSB first/0x6c lSB first - byteorder
* 1 - unused
* 2 card16 - protocol-major-version
* 2 card16 - protocol-minor-version
* 2 n - lenght of authorization-protocol-name
* 2 d - lenght of authorization-protocol-data
* 2 - unused
* string8 - authorization-protocol-name
* p - unused, p=pad(n)
* string8 - authorization-protocol-data
* q - unused, q=pad(d)
*
* pad(X) = (4 - (X mod 4)) mod 4
*
* Server response:
*
* 1 (0 failed, 2 authenticate, 1 success)
* ...
*
*/
/* Later on we will simply forward the first 6 header bytes to the "real" X11 server */
byte[] header = new byte[6];
if (remote_is.read(header) != 6)
throw new IOException("Unexpected EOF on X11 startup!");
if ((header[0] != 0x42) && (header[0] != 0x6c)) // 0x42 MSB first, 0x6C LSB first
throw new IOException("Unknown endian format in X11 message!");
/* Yes, I came up with this myself - shall I file an application for a patent? =) */
int idxMSB = (header[0] == 0x42) ? 0 : 1;
/* Read authorization data header */
byte[] auth_buff = new byte[6];
if (remote_is.read(auth_buff) != 6)
throw new IOException("Unexpected EOF on X11 startup!");
int authProtocolNameLength = ((auth_buff[idxMSB] & 0xff) << 8) | (auth_buff[1 - idxMSB] & 0xff);
int authProtocolDataLength = ((auth_buff[2 + idxMSB] & 0xff) << 8) | (auth_buff[3 - idxMSB] & 0xff);
if ((authProtocolNameLength > 256) || (authProtocolDataLength > 256))
throw new IOException("Buggy X11 authorization data");
int authProtocolNamePadding = ((4 - (authProtocolNameLength % 4)) % 4);
int authProtocolDataPadding = ((4 - (authProtocolDataLength % 4)) % 4);
byte[] authProtocolName = new byte[authProtocolNameLength];
byte[] authProtocolData = new byte[authProtocolDataLength];
byte[] paddingBuffer = new byte[4];
if (remote_is.read(authProtocolName) != authProtocolNameLength)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolName)");
if (remote_is.read(paddingBuffer, 0, authProtocolNamePadding) != authProtocolNamePadding)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolNamePadding)");
if (remote_is.read(authProtocolData) != authProtocolDataLength)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolData)");
if (remote_is.read(paddingBuffer, 0, authProtocolDataPadding) != authProtocolDataPadding)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolDataPadding)");
if ("MIT-MAGIC-COOKIE-1".equals(new String(authProtocolName, "ISO-8859-1")) == false)
throw new IOException("Unknown X11 authorization protocol!");
if (authProtocolDataLength != 16)
throw new IOException("Wrong data length for X11 authorization data!");
StringBuffer tmp = new StringBuffer(32);
for (int i = 0; i < authProtocolData.length; i++)
{
String digit2 = Integer.toHexString(authProtocolData[i] & 0xff);
tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
}
String hexEncodedFakeCookie = tmp.toString();
/* Order is very important here - it may be that a certain x11 forwarding
* gets disabled right in the moment when we check and register our connection
* */
synchronized (c)
{
/* Please read the comment in Channel.java */
c.hexX11FakeCookie = hexEncodedFakeCookie;
}
/* Now check our fake cookie directory to see if we produced this cookie */
X11ServerData sd = c.cm.checkX11Cookie(hexEncodedFakeCookie);
if (sd == null)
throw new IOException("Invalid X11 cookie received.");
/* If the session which corresponds to this cookie is closed then we will
* detect this: the session's close code will close all channels
* with the session's assigned x11 fake cookie.
*/
s = new Socket(sd.hostname, sd.port);
OutputStream x11_os = s.getOutputStream();
InputStream x11_is = s.getInputStream();
/* Now we are sending the startup packet to the real X11 server */
x11_os.write(header);
if (sd.x11_magic_cookie == null)
{
byte[] emptyAuthData = new byte[6];
/* empty auth data, hopefully you are connecting to localhost =) */
x11_os.write(emptyAuthData);
}
else
{
if (sd.x11_magic_cookie.length != 16)
throw new IOException("The real X11 cookie has an invalid length!");
/* send X11 cookie specified by client */
x11_os.write(auth_buff);
x11_os.write(authProtocolName); /* re-use */
x11_os.write(paddingBuffer, 0, authProtocolNamePadding);
x11_os.write(sd.x11_magic_cookie);
x11_os.write(paddingBuffer, 0, authProtocolDataPadding);
}
x11_os.flush();
/* Start forwarding traffic */
StreamForwarder r2l = new StreamForwarder(c, null, s, remote_is, x11_os, "RemoteToX11");
StreamForwarder l2r = new StreamForwarder(c, null, null, x11_is, remote_os, "X11ToRemote");
/* No need to start two threads, one can be executed in the current thread */
r2l.setDaemon(true);
r2l.start();
l2r.run();
while (r2l.isAlive())
{
try
{
r2l.join();
}
catch (InterruptedException e)
{
}
}
/* If the channel is already closed, then this is a no-op */
c.cm.closeChannel(c, "EOF on both X11 streams reached.", true);
s.close();
}
catch (IOException e)
{
log.log(50, "IOException in X11 proxy code: " + e.getMessage());
try
{
c.cm.closeChannel(c, "IOException in X11 proxy code (" + e.getMessage() + ")", true);
}
catch (IOException e1)
{
}
try
{
if (s != null)
s.close();
}
catch (IOException e1)
{
}
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/RemoteX11AcceptThread.java | Java | asf20 | 7,219 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;
import com.trilead.ssh2.AuthAgentCallback;
import com.trilead.ssh2.ChannelCondition;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketChannelAuthAgentReq;
import com.trilead.ssh2.packets.PacketChannelOpenConfirmation;
import com.trilead.ssh2.packets.PacketChannelOpenFailure;
import com.trilead.ssh2.packets.PacketChannelTrileadPing;
import com.trilead.ssh2.packets.PacketGlobalCancelForwardRequest;
import com.trilead.ssh2.packets.PacketGlobalForwardRequest;
import com.trilead.ssh2.packets.PacketGlobalTrileadPing;
import com.trilead.ssh2.packets.PacketOpenDirectTCPIPChannel;
import com.trilead.ssh2.packets.PacketOpenSessionChannel;
import com.trilead.ssh2.packets.PacketSessionExecCommand;
import com.trilead.ssh2.packets.PacketSessionPtyRequest;
import com.trilead.ssh2.packets.PacketSessionPtyResize;
import com.trilead.ssh2.packets.PacketSessionStartShell;
import com.trilead.ssh2.packets.PacketSessionSubsystemRequest;
import com.trilead.ssh2.packets.PacketSessionX11Request;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.transport.MessageHandler;
import com.trilead.ssh2.transport.TransportManager;
/**
* ChannelManager. Please read the comments in Channel.java.
* <p>
* Besides the crypto part, this is the core of the library.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelManager.java,v 1.2 2008/03/03 07:01:36 cplattne Exp $
*/
public class ChannelManager implements MessageHandler
{
private static final Logger log = Logger.getLogger(ChannelManager.class);
private HashMap x11_magic_cookies = new HashMap();
private TransportManager tm;
private Vector channels = new Vector();
private int nextLocalChannel = 100;
private boolean shutdown = false;
private int globalSuccessCounter = 0;
private int globalFailedCounter = 0;
private HashMap remoteForwardings = new HashMap();
private AuthAgentCallback authAgent;
private Vector listenerThreads = new Vector();
private boolean listenerThreadsAllowed = true;
public ChannelManager(TransportManager tm)
{
this.tm = tm;
tm.registerMessageHandler(this, 80, 100);
}
private Channel getChannel(int id)
{
synchronized (channels)
{
for (int i = 0; i < channels.size(); i++)
{
Channel c = (Channel) channels.elementAt(i);
if (c.localID == id)
return c;
}
}
return null;
}
private void removeChannel(int id)
{
synchronized (channels)
{
for (int i = 0; i < channels.size(); i++)
{
Channel c = (Channel) channels.elementAt(i);
if (c.localID == id)
{
channels.removeElementAt(i);
break;
}
}
}
}
private int addChannel(Channel c)
{
synchronized (channels)
{
channels.addElement(c);
return nextLocalChannel++;
}
}
private void waitUntilChannelOpen(Channel c) throws IOException
{
synchronized (c)
{
while (c.state == Channel.STATE_OPENING)
{
try
{
c.wait();
}
catch (InterruptedException ignore)
{
}
}
if (c.state != Channel.STATE_OPEN)
{
removeChannel(c.localID);
String detail = c.getReasonClosed();
if (detail == null)
detail = "state: " + c.state;
throw new IOException("Could not open channel (" + detail + ")");
}
}
}
private final boolean waitForGlobalRequestResult() throws IOException
{
synchronized (channels)
{
while ((globalSuccessCounter == 0) && (globalFailedCounter == 0))
{
if (shutdown)
{
throw new IOException("The connection is being shutdown");
}
try
{
channels.wait();
}
catch (InterruptedException ignore)
{
}
}
if ((globalFailedCounter == 0) && (globalSuccessCounter == 1))
return true;
if ((globalFailedCounter == 1) && (globalSuccessCounter == 0))
return false;
throw new IOException("Illegal state. The server sent " + globalSuccessCounter
+ " SSH_MSG_REQUEST_SUCCESS and " + globalFailedCounter + " SSH_MSG_REQUEST_FAILURE messages.");
}
}
private final boolean waitForChannelRequestResult(Channel c) throws IOException
{
synchronized (c)
{
while ((c.successCounter == 0) && (c.failedCounter == 0))
{
if (c.state != Channel.STATE_OPEN)
{
String detail = c.getReasonClosed();
if (detail == null)
detail = "state: " + c.state;
throw new IOException("This SSH2 channel is not open (" + detail + ")");
}
try
{
c.wait();
}
catch (InterruptedException ignore)
{
}
}
if ((c.failedCounter == 0) && (c.successCounter == 1))
return true;
if ((c.failedCounter == 1) && (c.successCounter == 0))
return false;
throw new IOException("Illegal state. The server sent " + c.successCounter
+ " SSH_MSG_CHANNEL_SUCCESS and " + c.failedCounter + " SSH_MSG_CHANNEL_FAILURE messages.");
}
}
public void registerX11Cookie(String hexFakeCookie, X11ServerData data)
{
synchronized (x11_magic_cookies)
{
x11_magic_cookies.put(hexFakeCookie, data);
}
}
public void unRegisterX11Cookie(String hexFakeCookie, boolean killChannels)
{
if (hexFakeCookie == null)
throw new IllegalStateException("hexFakeCookie may not be null");
synchronized (x11_magic_cookies)
{
x11_magic_cookies.remove(hexFakeCookie);
}
if (killChannels == false)
return;
if (log.isEnabled())
log.log(50, "Closing all X11 channels for the given fake cookie");
Vector channel_copy;
synchronized (channels)
{
channel_copy = (Vector) channels.clone();
}
for (int i = 0; i < channel_copy.size(); i++)
{
Channel c = (Channel) channel_copy.elementAt(i);
synchronized (c)
{
if (hexFakeCookie.equals(c.hexX11FakeCookie) == false)
continue;
}
try
{
closeChannel(c, "Closing X11 channel since the corresponding session is closing", true);
}
catch (IOException e)
{
}
}
}
public X11ServerData checkX11Cookie(String hexFakeCookie)
{
synchronized (x11_magic_cookies)
{
if (hexFakeCookie != null)
return (X11ServerData) x11_magic_cookies.get(hexFakeCookie);
}
return null;
}
public void closeAllChannels()
{
if (log.isEnabled())
log.log(50, "Closing all channels");
Vector channel_copy;
synchronized (channels)
{
channel_copy = (Vector) channels.clone();
}
for (int i = 0; i < channel_copy.size(); i++)
{
Channel c = (Channel) channel_copy.elementAt(i);
try
{
closeChannel(c, "Closing all channels", true);
}
catch (IOException e)
{
}
}
}
public void closeChannel(Channel c, String reason, boolean force) throws IOException
{
byte msg[] = new byte[5];
synchronized (c)
{
if (force)
{
c.state = Channel.STATE_CLOSED;
c.EOF = true;
}
c.setReasonClosed(reason);
msg[0] = Packets.SSH_MSG_CHANNEL_CLOSE;
msg[1] = (byte) (c.remoteID >> 24);
msg[2] = (byte) (c.remoteID >> 16);
msg[3] = (byte) (c.remoteID >> 8);
msg[4] = (byte) (c.remoteID);
c.notifyAll();
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent == true)
return;
tm.sendMessage(msg);
c.closeMessageSent = true;
}
if (log.isEnabled())
log.log(50, "Sent SSH_MSG_CHANNEL_CLOSE (channel " + c.localID + ")");
}
public void sendEOF(Channel c) throws IOException
{
byte[] msg = new byte[5];
synchronized (c)
{
if (c.state != Channel.STATE_OPEN)
return;
msg[0] = Packets.SSH_MSG_CHANNEL_EOF;
msg[1] = (byte) (c.remoteID >> 24);
msg[2] = (byte) (c.remoteID >> 16);
msg[3] = (byte) (c.remoteID >> 8);
msg[4] = (byte) (c.remoteID);
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent == true)
return;
tm.sendMessage(msg);
}
if (log.isEnabled())
log.log(50, "Sent EOF (Channel " + c.localID + "/" + c.remoteID + ")");
}
public void sendOpenConfirmation(Channel c) throws IOException
{
PacketChannelOpenConfirmation pcoc = null;
synchronized (c)
{
if (c.state != Channel.STATE_OPENING)
return;
c.state = Channel.STATE_OPEN;
pcoc = new PacketChannelOpenConfirmation(c.remoteID, c.localID, c.localWindow, c.localMaxPacketSize);
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent == true)
return;
tm.sendMessage(pcoc.getPayload());
}
}
public void sendData(Channel c, byte[] buffer, int pos, int len) throws IOException
{
while (len > 0)
{
int thislen = 0;
byte[] msg;
synchronized (c)
{
while (true)
{
if (c.state == Channel.STATE_CLOSED)
throw new IOException("SSH channel is closed. (" + c.getReasonClosed() + ")");
if (c.state != Channel.STATE_OPEN)
throw new IOException("SSH channel in strange state. (" + c.state + ")");
if (c.remoteWindow != 0)
break;
try
{
c.wait();
}
catch (InterruptedException ignore)
{
}
}
/* len > 0, no sign extension can happen when comparing */
thislen = (c.remoteWindow >= len) ? len : (int) c.remoteWindow;
int estimatedMaxDataLen = c.remoteMaxPacketSize - (tm.getPacketOverheadEstimate() + 9);
/* The worst case scenario =) a true bottleneck */
if (estimatedMaxDataLen <= 0)
{
estimatedMaxDataLen = 1;
}
if (thislen > estimatedMaxDataLen)
thislen = estimatedMaxDataLen;
c.remoteWindow -= thislen;
msg = new byte[1 + 8 + thislen];
msg[0] = Packets.SSH_MSG_CHANNEL_DATA;
msg[1] = (byte) (c.remoteID >> 24);
msg[2] = (byte) (c.remoteID >> 16);
msg[3] = (byte) (c.remoteID >> 8);
msg[4] = (byte) (c.remoteID);
msg[5] = (byte) (thislen >> 24);
msg[6] = (byte) (thislen >> 16);
msg[7] = (byte) (thislen >> 8);
msg[8] = (byte) (thislen);
System.arraycopy(buffer, pos, msg, 9, thislen);
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent == true)
throw new IOException("SSH channel is closed. (" + c.getReasonClosed() + ")");
tm.sendMessage(msg);
}
pos += thislen;
len -= thislen;
}
}
public int requestGlobalForward(String bindAddress, int bindPort, String targetAddress, int targetPort)
throws IOException
{
RemoteForwardingData rfd = new RemoteForwardingData();
rfd.bindAddress = bindAddress;
rfd.bindPort = bindPort;
rfd.targetAddress = targetAddress;
rfd.targetPort = targetPort;
synchronized (remoteForwardings)
{
Integer key = new Integer(bindPort);
if (remoteForwardings.get(key) != null)
{
throw new IOException("There is already a forwarding for remote port " + bindPort);
}
remoteForwardings.put(key, rfd);
}
synchronized (channels)
{
globalSuccessCounter = globalFailedCounter = 0;
}
PacketGlobalForwardRequest pgf = new PacketGlobalForwardRequest(true, bindAddress, bindPort);
tm.sendMessage(pgf.getPayload());
if (log.isEnabled())
log.log(50, "Requesting a remote forwarding ('" + bindAddress + "', " + bindPort + ")");
try
{
if (waitForGlobalRequestResult() == false)
throw new IOException("The server denied the request (did you enable port forwarding?)");
}
catch (IOException e)
{
synchronized (remoteForwardings)
{
remoteForwardings.remove(rfd);
}
throw e;
}
return bindPort;
}
public void requestCancelGlobalForward(int bindPort) throws IOException
{
RemoteForwardingData rfd = null;
synchronized (remoteForwardings)
{
rfd = (RemoteForwardingData) remoteForwardings.get(new Integer(bindPort));
if (rfd == null)
throw new IOException("Sorry, there is no known remote forwarding for remote port " + bindPort);
}
synchronized (channels)
{
globalSuccessCounter = globalFailedCounter = 0;
}
PacketGlobalCancelForwardRequest pgcf = new PacketGlobalCancelForwardRequest(true, rfd.bindAddress,
rfd.bindPort);
tm.sendMessage(pgcf.getPayload());
if (log.isEnabled())
log.log(50, "Requesting cancelation of remote forward ('" + rfd.bindAddress + "', " + rfd.bindPort + ")");
try
{
if (waitForGlobalRequestResult() == false)
throw new IOException("The server denied the request.");
}
finally
{
synchronized (remoteForwardings)
{
/* Only now we are sure that no more forwarded connections will arrive */
remoteForwardings.remove(rfd);
}
}
}
/**
* @param agent
* @throws IOException
*/
public boolean requestChannelAgentForwarding(Channel c, AuthAgentCallback authAgent) throws IOException {
synchronized (this)
{
if (this.authAgent != null)
throw new IllegalStateException("Auth agent already exists");
this.authAgent = authAgent;
}
synchronized (channels)
{
globalSuccessCounter = globalFailedCounter = 0;
}
if (log.isEnabled())
log.log(50, "Requesting agent forwarding");
PacketChannelAuthAgentReq aar = new PacketChannelAuthAgentReq(c.remoteID);
tm.sendMessage(aar.getPayload());
if (waitForChannelRequestResult(c) == false) {
authAgent = null;
return false;
}
return true;
}
public void registerThread(IChannelWorkerThread thr) throws IOException
{
synchronized (listenerThreads)
{
if (listenerThreadsAllowed == false)
throw new IOException("Too late, this connection is closed.");
listenerThreads.addElement(thr);
}
}
public Channel openDirectTCPIPChannel(String host_to_connect, int port_to_connect, String originator_IP_address,
int originator_port) throws IOException
{
Channel c = new Channel(this);
synchronized (c)
{
c.localID = addChannel(c);
// end of synchronized block forces writing out to main memory
}
PacketOpenDirectTCPIPChannel dtc = new PacketOpenDirectTCPIPChannel(c.localID, c.localWindow,
c.localMaxPacketSize, host_to_connect, port_to_connect, originator_IP_address, originator_port);
tm.sendMessage(dtc.getPayload());
waitUntilChannelOpen(c);
return c;
}
public Channel openSessionChannel() throws IOException
{
Channel c = new Channel(this);
synchronized (c)
{
c.localID = addChannel(c);
// end of synchronized block forces the writing out to main memory
}
if (log.isEnabled())
log.log(50, "Sending SSH_MSG_CHANNEL_OPEN (Channel " + c.localID + ")");
PacketOpenSessionChannel smo = new PacketOpenSessionChannel(c.localID, c.localWindow, c.localMaxPacketSize);
tm.sendMessage(smo.getPayload());
waitUntilChannelOpen(c);
return c;
}
public void requestGlobalTrileadPing() throws IOException
{
synchronized (channels)
{
globalSuccessCounter = globalFailedCounter = 0;
}
PacketGlobalTrileadPing pgtp = new PacketGlobalTrileadPing();
tm.sendMessage(pgtp.getPayload());
if (log.isEnabled())
log.log(50, "Sending SSH_MSG_GLOBAL_REQUEST 'trilead-ping'.");
try
{
if (waitForGlobalRequestResult() == true)
throw new IOException("Your server is alive - but buggy. "
+ "It replied with SSH_MSG_REQUEST_SUCCESS when it actually should not.");
}
catch (IOException e)
{
throw (IOException) new IOException("The ping request failed.").initCause(e);
}
}
public void requestChannelTrileadPing(Channel c) throws IOException
{
PacketChannelTrileadPing pctp;
synchronized (c)
{
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot ping this channel (" + c.getReasonClosed() + ")");
pctp = new PacketChannelTrileadPing(c.remoteID);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent)
throw new IOException("Cannot ping this channel (" + c.getReasonClosed() + ")");
tm.sendMessage(pctp.getPayload());
}
try
{
if (waitForChannelRequestResult(c) == true)
throw new IOException("Your server is alive - but buggy. "
+ "It replied with SSH_MSG_SESSION_SUCCESS when it actually should not.");
}
catch (IOException e)
{
throw (IOException) new IOException("The ping request failed.").initCause(e);
}
}
public void requestPTY(Channel c, String term, int term_width_characters, int term_height_characters,
int term_width_pixels, int term_height_pixels, byte[] terminal_modes) throws IOException
{
PacketSessionPtyRequest spr;
synchronized (c)
{
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot request PTY on this channel (" + c.getReasonClosed() + ")");
spr = new PacketSessionPtyRequest(c.remoteID, true, term, term_width_characters, term_height_characters,
term_width_pixels, term_height_pixels, terminal_modes);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent)
throw new IOException("Cannot request PTY on this channel (" + c.getReasonClosed() + ")");
tm.sendMessage(spr.getPayload());
}
try
{
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
}
catch (IOException e)
{
throw (IOException) new IOException("PTY request failed").initCause(e);
}
}
public void resizePTY(Channel c, int term_width_characters, int term_height_characters,
int term_width_pixels, int term_height_pixels) throws IOException {
PacketSessionPtyResize spr;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot request PTY on this channel ("
+ c.getReasonClosed() + ")");
spr = new PacketSessionPtyResize(c.remoteID, term_width_characters, term_height_characters,
term_width_pixels, term_height_pixels);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException("Cannot request PTY on this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(spr.getPayload());
}
}
public void requestX11(Channel c, boolean singleConnection, String x11AuthenticationProtocol,
String x11AuthenticationCookie, int x11ScreenNumber) throws IOException
{
PacketSessionX11Request psr;
synchronized (c)
{
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot request X11 on this channel (" + c.getReasonClosed() + ")");
psr = new PacketSessionX11Request(c.remoteID, true, singleConnection, x11AuthenticationProtocol,
x11AuthenticationCookie, x11ScreenNumber);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent)
throw new IOException("Cannot request X11 on this channel (" + c.getReasonClosed() + ")");
tm.sendMessage(psr.getPayload());
}
if (log.isEnabled())
log.log(50, "Requesting X11 forwarding (Channel " + c.localID + "/" + c.remoteID + ")");
try
{
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
}
catch (IOException e)
{
throw (IOException) new IOException("The X11 request failed.").initCause(e);
}
}
public void requestSubSystem(Channel c, String subSystemName) throws IOException
{
PacketSessionSubsystemRequest ssr;
synchronized (c)
{
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot request subsystem on this channel (" + c.getReasonClosed() + ")");
ssr = new PacketSessionSubsystemRequest(c.remoteID, true, subSystemName);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent)
throw new IOException("Cannot request subsystem on this channel (" + c.getReasonClosed() + ")");
tm.sendMessage(ssr.getPayload());
}
try
{
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
}
catch (IOException e)
{
throw (IOException) new IOException("The subsystem request failed.").initCause(e);
}
}
public void requestExecCommand(Channel c, String cmd) throws IOException
{
PacketSessionExecCommand sm;
synchronized (c)
{
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot execute command on this channel (" + c.getReasonClosed() + ")");
sm = new PacketSessionExecCommand(c.remoteID, true, cmd);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent)
throw new IOException("Cannot execute command on this channel (" + c.getReasonClosed() + ")");
tm.sendMessage(sm.getPayload());
}
if (log.isEnabled())
log.log(50, "Executing command (channel " + c.localID + ", '" + cmd + "')");
try
{
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
}
catch (IOException e)
{
throw (IOException) new IOException("The execute request failed.").initCause(e);
}
}
public void requestShell(Channel c) throws IOException
{
PacketSessionStartShell sm;
synchronized (c)
{
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot start shell on this channel (" + c.getReasonClosed() + ")");
sm = new PacketSessionStartShell(c.remoteID, true);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock)
{
if (c.closeMessageSent)
throw new IOException("Cannot start shell on this channel (" + c.getReasonClosed() + ")");
tm.sendMessage(sm.getPayload());
}
try
{
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
}
catch (IOException e)
{
throw (IOException) new IOException("The shell request failed.").initCause(e);
}
}
public void msgChannelExtendedData(byte[] msg, int msglen) throws IOException
{
if (msglen <= 13)
throw new IOException("SSH_MSG_CHANNEL_EXTENDED_DATA message has wrong size (" + msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
int dataType = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16) | ((msg[7] & 0xff) << 8) | (msg[8] & 0xff);
int len = ((msg[9] & 0xff) << 24) | ((msg[10] & 0xff) << 16) | ((msg[11] & 0xff) << 8) | (msg[12] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_EXTENDED_DATA message for non-existent channel " + id);
if (dataType != Packets.SSH_EXTENDED_DATA_STDERR)
throw new IOException("SSH_MSG_CHANNEL_EXTENDED_DATA message has unknown type (" + dataType + ")");
if (len != (msglen - 13))
throw new IOException("SSH_MSG_CHANNEL_EXTENDED_DATA message has wrong len (calculated " + (msglen - 13)
+ ", got " + len + ")");
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_EXTENDED_DATA (channel " + id + ", " + len + ")");
synchronized (c)
{
if (c.state == Channel.STATE_CLOSED)
return; // ignore
if (c.state != Channel.STATE_OPEN)
throw new IOException("Got SSH_MSG_CHANNEL_EXTENDED_DATA, but channel is not in correct state ("
+ c.state + ")");
if (c.localWindow < len)
throw new IOException("Remote sent too much data, does not fit into window.");
c.localWindow -= len;
System.arraycopy(msg, 13, c.stderrBuffer, c.stderrWritepos, len);
c.stderrWritepos += len;
c.notifyAll();
}
}
/**
* Wait until for a condition.
*
* @param c
* Channel
* @param timeout
* in ms, 0 means no timeout.
* @param condition_mask
* minimum event mask
* @return all current events
*
*/
public int waitForCondition(Channel c, long timeout, int condition_mask)
{
long end_time = 0;
boolean end_time_set = false;
synchronized (c)
{
while (true)
{
int current_cond = 0;
int stdoutAvail = c.stdoutWritepos - c.stdoutReadpos;
int stderrAvail = c.stderrWritepos - c.stderrReadpos;
if (stdoutAvail > 0)
current_cond = current_cond | ChannelCondition.STDOUT_DATA;
if (stderrAvail > 0)
current_cond = current_cond | ChannelCondition.STDERR_DATA;
if (c.EOF)
current_cond = current_cond | ChannelCondition.EOF;
if (c.getExitStatus() != null)
current_cond = current_cond | ChannelCondition.EXIT_STATUS;
if (c.getExitSignal() != null)
current_cond = current_cond | ChannelCondition.EXIT_SIGNAL;
if (c.state == Channel.STATE_CLOSED)
return current_cond | ChannelCondition.CLOSED | ChannelCondition.EOF;
if ((current_cond & condition_mask) != 0)
return current_cond;
if (timeout > 0)
{
if (!end_time_set)
{
end_time = System.currentTimeMillis() + timeout;
end_time_set = true;
}
else
{
timeout = end_time - System.currentTimeMillis();
if (timeout <= 0)
return current_cond | ChannelCondition.TIMEOUT;
}
}
try
{
if (timeout > 0)
c.wait(timeout);
else
c.wait();
}
catch (InterruptedException e)
{
}
}
}
}
public int getAvailable(Channel c, boolean extended) throws IOException
{
synchronized (c)
{
int avail;
if (extended)
avail = c.stderrWritepos - c.stderrReadpos;
else
avail = c.stdoutWritepos - c.stdoutReadpos;
return ((avail > 0) ? avail : (c.EOF ? -1 : 0));
}
}
public int getChannelData(Channel c, boolean extended, byte[] target, int off, int len) throws IOException
{
int copylen = 0;
int increment = 0;
int remoteID = 0;
int localID = 0;
synchronized (c)
{
int stdoutAvail = 0;
int stderrAvail = 0;
while (true)
{
/*
* Data available? We have to return remaining data even if the
* channel is already closed.
*/
stdoutAvail = c.stdoutWritepos - c.stdoutReadpos;
stderrAvail = c.stderrWritepos - c.stderrReadpos;
if ((!extended) && (stdoutAvail != 0))
break;
if ((extended) && (stderrAvail != 0))
break;
/* Do not wait if more data will never arrive (EOF or CLOSED) */
if ((c.EOF) || (c.state != Channel.STATE_OPEN))
return -1;
try
{
c.wait();
}
catch (InterruptedException ignore)
{
}
}
/* OK, there is some data. Return it. */
if (!extended)
{
copylen = (stdoutAvail > len) ? len : stdoutAvail;
System.arraycopy(c.stdoutBuffer, c.stdoutReadpos, target, off, copylen);
c.stdoutReadpos += copylen;
if (c.stdoutReadpos != c.stdoutWritepos)
System.arraycopy(c.stdoutBuffer, c.stdoutReadpos, c.stdoutBuffer, 0, c.stdoutWritepos
- c.stdoutReadpos);
c.stdoutWritepos -= c.stdoutReadpos;
c.stdoutReadpos = 0;
}
else
{
copylen = (stderrAvail > len) ? len : stderrAvail;
System.arraycopy(c.stderrBuffer, c.stderrReadpos, target, off, copylen);
c.stderrReadpos += copylen;
if (c.stderrReadpos != c.stderrWritepos)
System.arraycopy(c.stderrBuffer, c.stderrReadpos, c.stderrBuffer, 0, c.stderrWritepos
- c.stderrReadpos);
c.stderrWritepos -= c.stderrReadpos;
c.stderrReadpos = 0;
}
if (c.state != Channel.STATE_OPEN)
return copylen;
if (c.localWindow < ((Channel.CHANNEL_BUFFER_SIZE + 1) / 2))
{
int minFreeSpace = Math.min(Channel.CHANNEL_BUFFER_SIZE - c.stdoutWritepos, Channel.CHANNEL_BUFFER_SIZE
- c.stderrWritepos);
increment = minFreeSpace - c.localWindow;
c.localWindow = minFreeSpace;
}
remoteID = c.remoteID; /* read while holding the lock */
localID = c.localID; /* read while holding the lock */
}
/*
* If a consumer reads stdout and stdin in parallel, we may end up with
* sending two msgWindowAdjust messages. Luckily, it
* does not matter in which order they arrive at the server.
*/
if (increment > 0)
{
if (log.isEnabled())
log.log(80, "Sending SSH_MSG_CHANNEL_WINDOW_ADJUST (channel " + localID + ", " + increment + ")");
synchronized (c.channelSendLock)
{
byte[] msg = c.msgWindowAdjust;
msg[0] = Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST;
msg[1] = (byte) (remoteID >> 24);
msg[2] = (byte) (remoteID >> 16);
msg[3] = (byte) (remoteID >> 8);
msg[4] = (byte) (remoteID);
msg[5] = (byte) (increment >> 24);
msg[6] = (byte) (increment >> 16);
msg[7] = (byte) (increment >> 8);
msg[8] = (byte) (increment);
if (c.closeMessageSent == false)
tm.sendMessage(msg);
}
}
return copylen;
}
public void msgChannelData(byte[] msg, int msglen) throws IOException
{
if (msglen <= 9)
throw new IOException("SSH_MSG_CHANNEL_DATA message has wrong size (" + msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
int len = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16) | ((msg[7] & 0xff) << 8) | (msg[8] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_DATA message for non-existent channel " + id);
if (len != (msglen - 9))
throw new IOException("SSH_MSG_CHANNEL_DATA message has wrong len (calculated " + (msglen - 9) + ", got "
+ len + ")");
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_DATA (channel " + id + ", " + len + ")");
synchronized (c)
{
if (c.state == Channel.STATE_CLOSED)
return; // ignore
if (c.state != Channel.STATE_OPEN)
throw new IOException("Got SSH_MSG_CHANNEL_DATA, but channel is not in correct state (" + c.state + ")");
if (c.localWindow < len)
throw new IOException("Remote sent too much data, does not fit into window.");
c.localWindow -= len;
System.arraycopy(msg, 9, c.stdoutBuffer, c.stdoutWritepos, len);
c.stdoutWritepos += len;
c.notifyAll();
}
}
public void msgChannelWindowAdjust(byte[] msg, int msglen) throws IOException
{
if (msglen != 9)
throw new IOException("SSH_MSG_CHANNEL_WINDOW_ADJUST message has wrong size (" + msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
int windowChange = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16) | ((msg[7] & 0xff) << 8) | (msg[8] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_WINDOW_ADJUST message for non-existent channel " + id);
synchronized (c)
{
final long huge = 0xFFFFffffL; /* 2^32 - 1 */
c.remoteWindow += (windowChange & huge); /* avoid sign extension */
/* TODO - is this a good heuristic? */
if ((c.remoteWindow > huge))
c.remoteWindow = huge;
c.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_WINDOW_ADJUST (channel " + id + ", " + windowChange + ")");
}
public void msgChannelOpen(byte[] msg, int msglen) throws IOException
{
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
String channelType = tr.readString();
int remoteID = tr.readUINT32(); /* sender channel */
int remoteWindow = tr.readUINT32(); /* initial window size */
int remoteMaxPacketSize = tr.readUINT32(); /* maximum packet size */
if ("x11".equals(channelType))
{
synchronized (x11_magic_cookies)
{
/* If we did not request X11 forwarding, then simply ignore this bogus request. */
if (x11_magic_cookies.size() == 0)
{
PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(remoteID,
Packets.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED, "X11 forwarding not activated", "");
tm.sendAsynchronousMessage(pcof.getPayload());
if (log.isEnabled())
log.log(20, "Unexpected X11 request, denying it!");
return;
}
}
String remoteOriginatorAddress = tr.readString();
int remoteOriginatorPort = tr.readUINT32();
Channel c = new Channel(this);
synchronized (c)
{
c.remoteID = remoteID;
c.remoteWindow = remoteWindow & 0xFFFFffffL; /* properly convert UINT32 to long */
c.remoteMaxPacketSize = remoteMaxPacketSize;
c.localID = addChannel(c);
}
/*
* The open confirmation message will be sent from another thread
*/
RemoteX11AcceptThread rxat = new RemoteX11AcceptThread(c, remoteOriginatorAddress, remoteOriginatorPort);
rxat.setDaemon(true);
rxat.start();
return;
}
if ("forwarded-tcpip".equals(channelType))
{
String remoteConnectedAddress = tr.readString(); /* address that was connected */
int remoteConnectedPort = tr.readUINT32(); /* port that was connected */
String remoteOriginatorAddress = tr.readString(); /* originator IP address */
int remoteOriginatorPort = tr.readUINT32(); /* originator port */
RemoteForwardingData rfd = null;
synchronized (remoteForwardings)
{
rfd = (RemoteForwardingData) remoteForwardings.get(new Integer(remoteConnectedPort));
}
if (rfd == null)
{
PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(remoteID,
Packets.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED,
"No thanks, unknown port in forwarded-tcpip request", "");
/* Always try to be polite. */
tm.sendAsynchronousMessage(pcof.getPayload());
if (log.isEnabled())
log.log(20, "Unexpected forwarded-tcpip request, denying it!");
return;
}
Channel c = new Channel(this);
synchronized (c)
{
c.remoteID = remoteID;
c.remoteWindow = remoteWindow & 0xFFFFffffL; /* convert UINT32 to long */
c.remoteMaxPacketSize = remoteMaxPacketSize;
c.localID = addChannel(c);
}
/*
* The open confirmation message will be sent from another thread.
*/
RemoteAcceptThread rat = new RemoteAcceptThread(c, remoteConnectedAddress, remoteConnectedPort,
remoteOriginatorAddress, remoteOriginatorPort, rfd.targetAddress, rfd.targetPort);
rat.setDaemon(true);
rat.start();
return;
}
if ("auth-agent@openssh.com".equals(channelType)) {
Channel c = new Channel(this);
synchronized (c)
{
c.remoteID = remoteID;
c.remoteWindow = remoteWindow & 0xFFFFffffL; /* properly convert UINT32 to long */
c.remoteMaxPacketSize = remoteMaxPacketSize;
c.localID = addChannel(c);
}
AuthAgentForwardThread aat = new AuthAgentForwardThread(c, authAgent);
aat.setDaemon(true);
aat.start();
return;
}
/* Tell the server that we have no idea what it is talking about */
PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(remoteID, Packets.SSH_OPEN_UNKNOWN_CHANNEL_TYPE,
"Unknown channel type", "");
tm.sendAsynchronousMessage(pcof.getPayload());
if (log.isEnabled())
log.log(20, "The peer tried to open an unsupported channel type (" + channelType + ")");
}
public void msgChannelRequest(byte[] msg, int msglen) throws IOException
{
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
int id = tr.readUINT32();
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_REQUEST message for non-existent channel " + id);
String type = tr.readString("US-ASCII");
boolean wantReply = tr.readBoolean();
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_REQUEST (channel " + id + ", '" + type + "')");
if (type.equals("exit-status"))
{
if (wantReply != false)
throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message, 'want reply' is true");
int exit_status = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message");
synchronized (c)
{
c.exit_status = new Integer(exit_status);
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got EXIT STATUS (channel " + id + ", status " + exit_status + ")");
return;
}
if (type.equals("exit-signal"))
{
if (wantReply != false)
throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message, 'want reply' is true");
String signame = tr.readString("US-ASCII");
tr.readBoolean();
tr.readString();
tr.readString();
if (tr.remain() != 0)
throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message");
synchronized (c)
{
c.exit_signal = signame;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got EXIT SIGNAL (channel " + id + ", signal " + signame + ")");
return;
}
/* We simply ignore unknown channel requests, however, if the server wants a reply,
* then we signal that we have no idea what it is about.
*/
if (wantReply)
{
byte[] reply = new byte[5];
reply[0] = Packets.SSH_MSG_CHANNEL_FAILURE;
reply[1] = (byte) (c.remoteID >> 24);
reply[2] = (byte) (c.remoteID >> 16);
reply[3] = (byte) (c.remoteID >> 8);
reply[4] = (byte) (c.remoteID);
tm.sendAsynchronousMessage(reply);
}
if (log.isEnabled())
log.log(50, "Channel request '" + type + "' is not known, ignoring it");
}
public void msgChannelEOF(byte[] msg, int msglen) throws IOException
{
if (msglen != 5)
throw new IOException("SSH_MSG_CHANNEL_EOF message has wrong size (" + msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_EOF message for non-existent channel " + id);
synchronized (c)
{
c.EOF = true;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_EOF (channel " + id + ")");
}
public void msgChannelClose(byte[] msg, int msglen) throws IOException
{
if (msglen != 5)
throw new IOException("SSH_MSG_CHANNEL_CLOSE message has wrong size (" + msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_CLOSE message for non-existent channel " + id);
synchronized (c)
{
c.EOF = true;
c.state = Channel.STATE_CLOSED;
c.setReasonClosed("Close requested by remote");
c.closeMessageRecv = true;
removeChannel(c.localID);
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_CLOSE (channel " + id + ")");
}
public void msgChannelSuccess(byte[] msg, int msglen) throws IOException
{
if (msglen != 5)
throw new IOException("SSH_MSG_CHANNEL_SUCCESS message has wrong size (" + msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_SUCCESS message for non-existent channel " + id);
synchronized (c)
{
c.successCounter++;
c.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_SUCCESS (channel " + id + ")");
}
public void msgChannelFailure(byte[] msg, int msglen) throws IOException
{
if (msglen != 5)
throw new IOException("SSH_MSG_CHANNEL_FAILURE message has wrong size (" + msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_FAILURE message for non-existent channel " + id);
synchronized (c)
{
c.failedCounter++;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_FAILURE (channel " + id + ")");
}
public void msgChannelOpenConfirmation(byte[] msg, int msglen) throws IOException
{
PacketChannelOpenConfirmation sm = new PacketChannelOpenConfirmation(msg, 0, msglen);
Channel c = getChannel(sm.recipientChannelID);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION message for non-existent channel "
+ sm.recipientChannelID);
synchronized (c)
{
if (c.state != Channel.STATE_OPENING)
throw new IOException("Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION message for channel "
+ sm.recipientChannelID);
c.remoteID = sm.senderChannelID;
c.remoteWindow = sm.initialWindowSize & 0xFFFFffffL; /* convert UINT32 to long */
c.remoteMaxPacketSize = sm.maxPacketSize;
c.state = Channel.STATE_OPEN;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_OPEN_CONFIRMATION (channel " + sm.recipientChannelID + " / remote: "
+ sm.senderChannelID + ")");
}
public void msgChannelOpenFailure(byte[] msg, int msglen) throws IOException
{
if (msglen < 5)
throw new IOException("SSH_MSG_CHANNEL_OPEN_FAILURE message has wrong size (" + msglen + ")");
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
int id = tr.readUINT32(); /* sender channel */
Channel c = getChannel(id);
if (c == null)
throw new IOException("Unexpected SSH_MSG_CHANNEL_OPEN_FAILURE message for non-existent channel " + id);
int reasonCode = tr.readUINT32();
String description = tr.readString("UTF-8");
String reasonCodeSymbolicName = null;
switch (reasonCode)
{
case 1:
reasonCodeSymbolicName = "SSH_OPEN_ADMINISTRATIVELY_PROHIBITED";
break;
case 2:
reasonCodeSymbolicName = "SSH_OPEN_CONNECT_FAILED";
break;
case 3:
reasonCodeSymbolicName = "SSH_OPEN_UNKNOWN_CHANNEL_TYPE";
break;
case 4:
reasonCodeSymbolicName = "SSH_OPEN_RESOURCE_SHORTAGE";
break;
default:
reasonCodeSymbolicName = "UNKNOWN REASON CODE (" + reasonCode + ")";
}
StringBuffer descriptionBuffer = new StringBuffer();
descriptionBuffer.append(description);
for (int i = 0; i < descriptionBuffer.length(); i++)
{
char cc = descriptionBuffer.charAt(i);
if ((cc >= 32) && (cc <= 126))
continue;
descriptionBuffer.setCharAt(i, '\uFFFD');
}
synchronized (c)
{
c.EOF = true;
c.state = Channel.STATE_CLOSED;
c.setReasonClosed("The server refused to open the channel (" + reasonCodeSymbolicName + ", '"
+ descriptionBuffer.toString() + "')");
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_OPEN_FAILURE (channel " + id + ")");
}
public void msgGlobalRequest(byte[] msg, int msglen) throws IOException
{
/* Currently we do not support any kind of global request */
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
String requestName = tr.readString();
boolean wantReply = tr.readBoolean();
if (wantReply)
{
byte[] reply_failure = new byte[1];
reply_failure[0] = Packets.SSH_MSG_REQUEST_FAILURE;
tm.sendAsynchronousMessage(reply_failure);
}
/* We do not clean up the requestName String - that is OK for debug */
if (log.isEnabled())
log.log(80, "Got SSH_MSG_GLOBAL_REQUEST (" + requestName + ")");
}
public void msgGlobalSuccess() throws IOException
{
synchronized (channels)
{
globalSuccessCounter++;
channels.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_REQUEST_SUCCESS");
}
public void msgGlobalFailure() throws IOException
{
synchronized (channels)
{
globalFailedCounter++;
channels.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_REQUEST_FAILURE");
}
public void handleMessage(byte[] msg, int msglen) throws IOException
{
if (msg == null)
{
if (log.isEnabled())
log.log(50, "HandleMessage: got shutdown");
synchronized (listenerThreads)
{
for (int i = 0; i < listenerThreads.size(); i++)
{
IChannelWorkerThread lat = (IChannelWorkerThread) listenerThreads.elementAt(i);
lat.stopWorking();
}
listenerThreadsAllowed = false;
}
synchronized (channels)
{
shutdown = true;
for (int i = 0; i < channels.size(); i++)
{
Channel c = (Channel) channels.elementAt(i);
synchronized (c)
{
c.EOF = true;
c.state = Channel.STATE_CLOSED;
c.setReasonClosed("The connection is being shutdown");
c.closeMessageRecv = true; /*
* You never know, perhaps
* we are waiting for a
* pending close message
* from the server...
*/
c.notifyAll();
}
}
/* Works with J2ME */
channels.setSize(0);
channels.trimToSize();
channels.notifyAll(); /* Notify global response waiters */
return;
}
}
switch (msg[0])
{
case Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
msgChannelOpenConfirmation(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST:
msgChannelWindowAdjust(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_DATA:
msgChannelData(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_EXTENDED_DATA:
msgChannelExtendedData(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_REQUEST:
msgChannelRequest(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_EOF:
msgChannelEOF(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_OPEN:
msgChannelOpen(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_CLOSE:
msgChannelClose(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_SUCCESS:
msgChannelSuccess(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_FAILURE:
msgChannelFailure(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_OPEN_FAILURE:
msgChannelOpenFailure(msg, msglen);
break;
case Packets.SSH_MSG_GLOBAL_REQUEST:
msgGlobalRequest(msg, msglen);
break;
case Packets.SSH_MSG_REQUEST_SUCCESS:
msgGlobalSuccess();
break;
case Packets.SSH_MSG_REQUEST_FAILURE:
msgGlobalFailure();
break;
default:
throw new IOException("Cannot handle unknown channel message " + (msg[0] & 0xff));
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/ChannelManager.java | Java | asf20 | 47,171 |
package com.trilead.ssh2.channel;
/**
* RemoteForwardingData. Data about a requested remote forwarding.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RemoteForwardingData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class RemoteForwardingData
{
public String bindAddress;
public int bindPort;
String targetAddress;
int targetPort;
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/RemoteForwardingData.java | Java | asf20 | 397 |
package com.trilead.ssh2.channel;
/**
* Channel.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Channel.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class Channel
{
/*
* OK. Here is an important part of the JVM Specification:
* (http://java.sun.com/docs/books/vmspec/2nd-edition/html/Threads.doc.html#22214)
*
* Any association between locks and variables is purely conventional.
* Locking any lock conceptually flushes all variables from a thread's
* working memory, and unlocking any lock forces the writing out to main
* memory of all variables that the thread has assigned. That a lock may be
* associated with a particular object or a class is purely a convention.
* (...)
*
* If a thread uses a particular shared variable only after locking a
* particular lock and before the corresponding unlocking of that same lock,
* then the thread will read the shared value of that variable from main
* memory after the lock operation, if necessary, and will copy back to main
* memory the value most recently assigned to that variable before the
* unlock operation.
*
* This, in conjunction with the mutual exclusion rules for locks, suffices
* to guarantee that values are correctly transmitted from one thread to
* another through shared variables.
*
* ====> Always keep that in mind when modifying the Channel/ChannelManger
* code.
*
*/
static final int STATE_OPENING = 1;
static final int STATE_OPEN = 2;
static final int STATE_CLOSED = 4;
static final int CHANNEL_BUFFER_SIZE = 30000;
/*
* To achieve correctness, the following rules have to be respected when
* accessing this object:
*/
// These fields can always be read
final ChannelManager cm;
final ChannelOutputStream stdinStream;
final ChannelInputStream stdoutStream;
final ChannelInputStream stderrStream;
// These two fields will only be written while the Channel is in state
// STATE_OPENING.
// The code makes sure that the two fields are written out when the state is
// changing to STATE_OPEN.
// Therefore, if you know that the Channel is in state STATE_OPEN, then you
// can read these two fields without synchronizing on the Channel. However, make
// sure that you get the latest values (e.g., flush caches by synchronizing on any
// object). However, to be on the safe side, you can lock the channel.
int localID = -1;
int remoteID = -1;
/*
* Make sure that we never send a data/EOF/WindowChange msg after a CLOSE
* msg.
*
* This is a little bit complicated, but we have to do it in that way, since
* we cannot keep a lock on the Channel during the send operation (this
* would block sometimes the receiver thread, and, in extreme cases, can
* lead to a deadlock on both sides of the connection (senders are blocked
* since the receive buffers on the other side are full, and receiver
* threads wait for the senders to finish). It all depends on the
* implementation on the other side. But we cannot make any assumptions, we
* have to assume the worst case. Confused? Just believe me.
*/
/*
* If you send a message on a channel, then you have to aquire the
* "channelSendLock" and check the "closeMessageSent" flag (this variable
* may only be accessed while holding the "channelSendLock" !!!
*
* BTW: NEVER EVER SEND MESSAGES FROM THE RECEIVE THREAD - see explanation
* above.
*/
final Object channelSendLock = new Object();
boolean closeMessageSent = false;
/*
* Stop memory fragmentation by allocating this often used buffer.
* May only be used while holding the channelSendLock
*/
final byte[] msgWindowAdjust = new byte[9];
// If you access (read or write) any of the following fields, then you have
// to synchronize on the channel.
int state = STATE_OPENING;
boolean closeMessageRecv = false;
/* This is a stupid implementation. At the moment we can only wait
* for one pending request per channel.
*/
int successCounter = 0;
int failedCounter = 0;
int localWindow = 0; /* locally, we use a small window, < 2^31 */
long remoteWindow = 0; /* long for readable 2^32 - 1 window support */
int localMaxPacketSize = -1;
int remoteMaxPacketSize = -1;
final byte[] stdoutBuffer = new byte[CHANNEL_BUFFER_SIZE];
final byte[] stderrBuffer = new byte[CHANNEL_BUFFER_SIZE];
int stdoutReadpos = 0;
int stdoutWritepos = 0;
int stderrReadpos = 0;
int stderrWritepos = 0;
boolean EOF = false;
Integer exit_status;
String exit_signal;
// we keep the x11 cookie so that this channel can be closed when this
// specific x11 forwarding gets stopped
String hexX11FakeCookie;
// reasonClosed is special, since we sometimes need to access it
// while holding the channelSendLock.
// We protect it with a private short term lock.
private final Object reasonClosedLock = new Object();
private String reasonClosed = null;
public Channel(ChannelManager cm)
{
this.cm = cm;
this.localWindow = CHANNEL_BUFFER_SIZE;
this.localMaxPacketSize = 35000 - 1024; // leave enough slack
this.stdinStream = new ChannelOutputStream(this);
this.stdoutStream = new ChannelInputStream(this, false);
this.stderrStream = new ChannelInputStream(this, true);
}
/* Methods to allow access from classes outside of this package */
public ChannelInputStream getStderrStream()
{
return stderrStream;
}
public ChannelOutputStream getStdinStream()
{
return stdinStream;
}
public ChannelInputStream getStdoutStream()
{
return stdoutStream;
}
public String getExitSignal()
{
synchronized (this)
{
return exit_signal;
}
}
public Integer getExitStatus()
{
synchronized (this)
{
return exit_status;
}
}
public String getReasonClosed()
{
synchronized (reasonClosedLock)
{
return reasonClosed;
}
}
public void setReasonClosed(String reasonClosed)
{
synchronized (reasonClosedLock)
{
if (this.reasonClosed == null)
this.reasonClosed = reasonClosed;
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/Channel.java | Java | asf20 | 6,205 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
/**
* ChannelInputStream.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelInputStream.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public final class ChannelInputStream extends InputStream
{
Channel c;
boolean isClosed = false;
boolean isEOF = false;
boolean extendedFlag = false;
ChannelInputStream(Channel c, boolean isExtended)
{
this.c = c;
this.extendedFlag = isExtended;
}
public int available() throws IOException
{
if (isEOF)
return 0;
int avail = c.cm.getAvailable(c, extendedFlag);
/* We must not return -1 on EOF */
return (avail > 0) ? avail : 0;
}
public void close() throws IOException
{
isClosed = true;
}
public int read(byte[] b, int off, int len) throws IOException
{
if (b == null)
throw new NullPointerException();
if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
throw new IndexOutOfBoundsException();
if (len == 0)
return 0;
if (isEOF)
return -1;
int ret = c.cm.getChannelData(c, extendedFlag, b, off, len);
if (ret == -1)
{
isEOF = true;
}
return ret;
}
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
public int read() throws IOException
{
/* Yes, this stream is pure and unbuffered, a single byte read() is slow */
final byte b[] = new byte[1];
int ret = read(b, 0, 1);
if (ret != 1)
return -1;
return b[0] & 0xff;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/ChannelInputStream.java | Java | asf20 | 1,646 |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Map.Entry;
import com.trilead.ssh2.AuthAgentCallback;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.packets.TypesWriter;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.DSASignature;
import com.trilead.ssh2.signature.RSAPrivateKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
import com.trilead.ssh2.signature.RSASignature;
/**
* AuthAgentForwardThread.
*
* @author Kenny Root
* @version $Id$
*/
public class AuthAgentForwardThread extends Thread implements IChannelWorkerThread
{
private static final byte[] SSH_AGENT_FAILURE = {0, 0, 0, 1, 5}; // 5
private static final byte[] SSH_AGENT_SUCCESS = {0, 0, 0, 1, 6}; // 6
private static final int SSH2_AGENTC_REQUEST_IDENTITIES = 11;
private static final int SSH2_AGENT_IDENTITIES_ANSWER = 12;
private static final int SSH2_AGENTC_SIGN_REQUEST = 13;
private static final int SSH2_AGENT_SIGN_RESPONSE = 14;
private static final int SSH2_AGENTC_ADD_IDENTITY = 17;
private static final int SSH2_AGENTC_REMOVE_IDENTITY = 18;
private static final int SSH2_AGENTC_REMOVE_ALL_IDENTITIES = 19;
// private static final int SSH_AGENTC_ADD_SMARTCARD_KEY = 20;
// private static final int SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21;
private static final int SSH_AGENTC_LOCK = 22;
private static final int SSH_AGENTC_UNLOCK = 23;
private static final int SSH2_AGENTC_ADD_ID_CONSTRAINED = 25;
// private static final int SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26;
// Constraints for adding keys
private static final int SSH_AGENT_CONSTRAIN_LIFETIME = 1;
private static final int SSH_AGENT_CONSTRAIN_CONFIRM = 2;
// Flags for signature requests
// private static final int SSH_AGENT_OLD_SIGNATURE = 1;
private static final Logger log = Logger.getLogger(RemoteAcceptThread.class);
AuthAgentCallback authAgent;
OutputStream os;
InputStream is;
Channel c;
byte[] buffer = new byte[Channel.CHANNEL_BUFFER_SIZE];
public AuthAgentForwardThread(Channel c, AuthAgentCallback authAgent)
{
this.c = c;
this.authAgent = authAgent;
if (log.isEnabled())
log.log(20, "AuthAgentForwardThread started");
}
@Override
public void run()
{
try
{
c.cm.registerThread(this);
}
catch (IOException e)
{
stopWorking();
return;
}
try
{
c.cm.sendOpenConfirmation(c);
is = c.getStdoutStream();
os = c.getStdinStream();
int totalSize = 4;
int readSoFar = 0;
while (true) {
int len;
try
{
len = is.read(buffer, readSoFar, buffer.length - readSoFar);
}
catch (IOException e)
{
stopWorking();
return;
}
if (len <= 0)
break;
readSoFar += len;
if (readSoFar >= 4) {
TypesReader tr = new TypesReader(buffer, 0, 4);
totalSize = tr.readUINT32() + 4;
}
if (totalSize == readSoFar) {
TypesReader tr = new TypesReader(buffer, 4, readSoFar - 4);
int messageType = tr.readByte();
switch (messageType) {
case SSH2_AGENTC_REQUEST_IDENTITIES:
sendIdentities();
break;
case SSH2_AGENTC_ADD_IDENTITY:
addIdentity(tr, false);
break;
case SSH2_AGENTC_ADD_ID_CONSTRAINED:
addIdentity(tr, true);
break;
case SSH2_AGENTC_REMOVE_IDENTITY:
removeIdentity(tr);
break;
case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
removeAllIdentities(tr);
break;
case SSH2_AGENTC_SIGN_REQUEST:
processSignRequest(tr);
break;
case SSH_AGENTC_LOCK:
processLockRequest(tr);
break;
case SSH_AGENTC_UNLOCK:
processUnlockRequest(tr);
break;
default:
os.write(SSH_AGENT_FAILURE);
break;
}
readSoFar = 0;
}
}
c.cm.closeChannel(c, "EOF on both streams reached.", true);
}
catch (IOException e)
{
log.log(50, "IOException in agent forwarder: " + e.getMessage());
try
{
is.close();
}
catch (IOException e1)
{
}
try
{
os.close();
}
catch (IOException e2)
{
}
try
{
c.cm.closeChannel(c, "IOException in agent forwarder (" + e.getMessage() + ")", true);
}
catch (IOException e3)
{
}
}
}
public void stopWorking() {
try
{
/* This will lead to an IOException in the is.read() call */
is.close();
}
catch (IOException e)
{
}
}
/**
* @return whether the agent is locked
*/
private boolean failWhenLocked() throws IOException
{
if (authAgent.isAgentLocked()) {
os.write(SSH_AGENT_FAILURE);
return true;
} else
return false;
}
private void sendIdentities() throws IOException
{
Map<String,byte[]> keys = null;
TypesWriter tw = new TypesWriter();
tw.writeByte(SSH2_AGENT_IDENTITIES_ANSWER);
int numKeys = 0;
if (!authAgent.isAgentLocked())
keys = authAgent.retrieveIdentities();
if (keys != null)
numKeys = keys.size();
tw.writeUINT32(numKeys);
if (keys != null) {
for (Entry<String,byte[]> entry : keys.entrySet()) {
byte[] keyBytes = entry.getValue();
tw.writeString(keyBytes, 0, keyBytes.length);
tw.writeString(entry.getKey());
}
}
sendPacket(tw.getBytes());
}
/**
* @param tr
*/
private void addIdentity(TypesReader tr, boolean checkConstraints) {
try
{
if (failWhenLocked())
return;
String type = tr.readString();
Object key;
String comment;
if (type.equals("ssh-rsa")) {
BigInteger n = tr.readMPINT();
BigInteger e = tr.readMPINT();
BigInteger d = tr.readMPINT();
tr.readMPINT(); // iqmp
tr.readMPINT(); // p
tr.readMPINT(); // q
comment = tr.readString();
key = new RSAPrivateKey(d, e, n);
} else if (type.equals("ssh-dss")) {
BigInteger p = tr.readMPINT();
BigInteger q = tr.readMPINT();
BigInteger g = tr.readMPINT();
BigInteger y = tr.readMPINT();
BigInteger x = tr.readMPINT();
comment = tr.readString();
key = new DSAPrivateKey(p, q, g, y, x);
} else {
os.write(SSH_AGENT_FAILURE);
return;
}
boolean confirmUse = false;
int lifetime = 0;
if (checkConstraints) {
while (tr.remain() > 0) {
int constraint = tr.readByte();
if (constraint == SSH_AGENT_CONSTRAIN_CONFIRM)
confirmUse = true;
else if (constraint == SSH_AGENT_CONSTRAIN_LIFETIME)
lifetime = tr.readUINT32();
else {
// Unknown constraint. Bail.
os.write(SSH_AGENT_FAILURE);
return;
}
}
}
if (authAgent.addIdentity(key, comment, confirmUse, lifetime))
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e)
{
try
{
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e1)
{
}
}
}
/**
* @param tr
*/
private void removeIdentity(TypesReader tr) {
try
{
if (failWhenLocked())
return;
byte[] publicKey = tr.readByteString();
if (authAgent.removeIdentity(publicKey))
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e)
{
try
{
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e1)
{
}
}
}
/**
* @param tr
*/
private void removeAllIdentities(TypesReader tr) {
try
{
if (failWhenLocked())
return;
if (authAgent.removeAllIdentities())
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e)
{
try
{
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e1)
{
}
}
}
private void processSignRequest(TypesReader tr)
{
try
{
if (failWhenLocked())
return;
byte[] publicKey = tr.readByteString();
byte[] challenge = tr.readByteString();
int flags = tr.readUINT32();
if (flags != 0) {
// We don't understand any flags; abort!
os.write(SSH_AGENT_FAILURE);
return;
}
Object trileadKey = authAgent.getPrivateKey(publicKey);
if (trileadKey == null) {
os.write(SSH_AGENT_FAILURE);
return;
}
byte[] response;
if (trileadKey instanceof RSAPrivateKey) {
RSASignature signature = RSASHA1Verify.generateSignature(challenge,
(RSAPrivateKey) trileadKey);
response = RSASHA1Verify.encodeSSHRSASignature(signature);
} else if (trileadKey instanceof DSAPrivateKey) {
DSASignature signature = DSASHA1Verify.generateSignature(challenge,
(DSAPrivateKey) trileadKey, new SecureRandom());
response = DSASHA1Verify.encodeSSHDSASignature(signature);
} else {
os.write(SSH_AGENT_FAILURE);
return;
}
TypesWriter tw = new TypesWriter();
tw.writeByte(SSH2_AGENT_SIGN_RESPONSE);
tw.writeString(response, 0, response.length);
sendPacket(tw.getBytes());
}
catch (IOException e)
{
try
{
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e1)
{
}
}
}
/**
* @param tr
*/
private void processLockRequest(TypesReader tr) {
try
{
if (failWhenLocked())
return;
String lockPassphrase = tr.readString();
if (!authAgent.setAgentLock(lockPassphrase)) {
os.write(SSH_AGENT_FAILURE);
return;
} else
os.write(SSH_AGENT_SUCCESS);
}
catch (IOException e)
{
try
{
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e1)
{
}
}
}
/**
* @param tr
*/
private void processUnlockRequest(TypesReader tr)
{
try
{
String unlockPassphrase = tr.readString();
if (authAgent.requestAgentUnlock(unlockPassphrase))
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e)
{
try
{
os.write(SSH_AGENT_FAILURE);
}
catch (IOException e1)
{
}
}
}
/**
* @param tw
* @throws IOException
*/
private void sendPacket(byte[] message) throws IOException
{
TypesWriter packet = new TypesWriter();
packet.writeUINT32(message.length);
packet.writeBytes(message);
os.write(packet.getBytes());
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/AuthAgentForwardThread.java | Java | asf20 | 10,812 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.OutputStream;
/**
* ChannelOutputStream.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelOutputStream.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public final class ChannelOutputStream extends OutputStream
{
Channel c;
private byte[] writeBuffer;
boolean isClosed = false;
ChannelOutputStream(Channel c)
{
this.c = c;
writeBuffer = new byte[1];
}
public void write(int b) throws IOException
{
writeBuffer[0] = (byte) b;
write(writeBuffer, 0, 1);
}
public void close() throws IOException
{
if (isClosed == false)
{
isClosed = true;
c.cm.sendEOF(c);
}
}
public void flush() throws IOException
{
if (isClosed)
throw new IOException("This OutputStream is closed.");
/* This is a no-op, since this stream is unbuffered */
}
public void write(byte[] b, int off, int len) throws IOException
{
if (isClosed)
throw new IOException("This OutputStream is closed.");
if (b == null)
throw new NullPointerException();
if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
throw new IndexOutOfBoundsException();
if (len == 0)
return;
c.cm.sendData(c, b, off, len);
}
public void write(byte[] b) throws IOException
{
write(b, 0, b.length);
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/ChannelOutputStream.java | Java | asf20 | 1,454 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* LocalAcceptThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: LocalAcceptThread.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class LocalAcceptThread extends Thread implements IChannelWorkerThread
{
ChannelManager cm;
String host_to_connect;
int port_to_connect;
final ServerSocket ss;
public LocalAcceptThread(ChannelManager cm, int local_port, String host_to_connect, int port_to_connect)
throws IOException
{
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
ss = new ServerSocket(local_port);
}
public LocalAcceptThread(ChannelManager cm, InetSocketAddress localAddress, String host_to_connect,
int port_to_connect) throws IOException
{
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
ss = new ServerSocket();
ss.bind(localAddress);
}
public void run()
{
try
{
cm.registerThread(this);
}
catch (IOException e)
{
stopWorking();
return;
}
while (true)
{
Socket s = null;
try
{
s = ss.accept();
}
catch (IOException e)
{
stopWorking();
return;
}
Channel cn = null;
StreamForwarder r2l = null;
StreamForwarder l2r = null;
try
{
/* This may fail, e.g., if the remote port is closed (in optimistic terms: not open yet) */
cn = cm.openDirectTCPIPChannel(host_to_connect, port_to_connect, s.getInetAddress().getHostAddress(), s
.getPort());
}
catch (IOException e)
{
/* Simply close the local socket and wait for the next incoming connection */
try
{
s.close();
}
catch (IOException ignore)
{
}
continue;
}
try
{
r2l = new StreamForwarder(cn, null, s, cn.stdoutStream, s.getOutputStream(), "RemoteToLocal");
l2r = new StreamForwarder(cn, r2l, s, s.getInputStream(), cn.stdinStream, "LocalToRemote");
}
catch (IOException e)
{
try
{
/* This message is only visible during debugging, since we discard the channel immediatelly */
cn.cm.closeChannel(cn, "Weird error during creation of StreamForwarder (" + e.getMessage() + ")",
true);
}
catch (IOException ignore)
{
}
continue;
}
r2l.setDaemon(true);
l2r.setDaemon(true);
r2l.start();
l2r.start();
}
}
public void stopWorking()
{
try
{
/* This will lead to an IOException in the ss.accept() call */
ss.close();
}
catch (IOException e)
{
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/LocalAcceptThread.java | Java | asf20 | 2,810 |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.ServerSocket;
import java.net.Socket;
import net.sourceforge.jsocks.Proxy;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.Socks4Message;
import net.sourceforge.jsocks.Socks5Message;
import net.sourceforge.jsocks.SocksException;
import net.sourceforge.jsocks.server.ServerAuthenticator;
import net.sourceforge.jsocks.server.ServerAuthenticatorNone;
/**
* DynamicAcceptThread.
*
* @author Kenny Root
* @version $Id$
*/
public class DynamicAcceptThread extends Thread implements IChannelWorkerThread {
private ChannelManager cm;
private ServerSocket ss;
class DynamicAcceptRunnable implements Runnable {
private static final int idleTimeout = 180000; //3 minutes
private ServerAuthenticator auth;
private Socket sock;
private InputStream in;
private OutputStream out;
private ProxyMessage msg;
public DynamicAcceptRunnable(ServerAuthenticator auth, Socket sock) {
this.auth = auth;
this.sock = sock;
setName("DynamicAcceptRunnable");
}
public void run() {
try {
startSession();
} catch (IOException ioe) {
int error_code = Proxy.SOCKS_FAILURE;
if (ioe instanceof SocksException)
error_code = ((SocksException) ioe).errCode;
else if (ioe instanceof NoRouteToHostException)
error_code = Proxy.SOCKS_HOST_UNREACHABLE;
else if (ioe instanceof ConnectException)
error_code = Proxy.SOCKS_CONNECTION_REFUSED;
else if (ioe instanceof InterruptedIOException)
error_code = Proxy.SOCKS_TTL_EXPIRE;
if (error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED
|| error_code < 0) {
error_code = Proxy.SOCKS_FAILURE;
}
sendErrorMessage(error_code);
} finally {
if (auth != null)
auth.endSession();
}
}
private ProxyMessage readMsg(InputStream in) throws IOException {
PushbackInputStream push_in;
if (in instanceof PushbackInputStream)
push_in = (PushbackInputStream) in;
else
push_in = new PushbackInputStream(in);
int version = push_in.read();
push_in.unread(version);
ProxyMessage msg;
if (version == 5) {
msg = new Socks5Message(push_in, false);
} else if (version == 4) {
msg = new Socks4Message(push_in, false);
} else {
throw new SocksException(Proxy.SOCKS_FAILURE);
}
return msg;
}
private void sendErrorMessage(int error_code) {
ProxyMessage err_msg;
if (msg instanceof Socks4Message)
err_msg = new Socks4Message(Socks4Message.REPLY_REJECTED);
else
err_msg = new Socks5Message(error_code);
try {
err_msg.write(out);
} catch (IOException ioe) {
}
}
private void handleRequest(ProxyMessage msg) throws IOException {
if (!auth.checkRequest(msg))
throw new SocksException(Proxy.SOCKS_FAILURE);
switch (msg.command) {
case Proxy.SOCKS_CMD_CONNECT:
onConnect(msg);
break;
default:
throw new SocksException(Proxy.SOCKS_CMD_NOT_SUPPORTED);
}
}
private void startSession() throws IOException {
sock.setSoTimeout(idleTimeout);
try {
auth = auth.startSession(sock);
} catch (IOException ioe) {
System.out.println("Could not start SOCKS session");
ioe.printStackTrace();
auth = null;
return;
}
if (auth == null) { // Authentication failed
System.out.println("SOCKS auth failed");
return;
}
in = auth.getInputStream();
out = auth.getOutputStream();
msg = readMsg(in);
handleRequest(msg);
}
private void onConnect(ProxyMessage msg) throws IOException {
ProxyMessage response = null;
Channel cn = null;
StreamForwarder r2l = null;
StreamForwarder l2r = null;
if (msg instanceof Socks5Message) {
response = new Socks5Message(Proxy.SOCKS_SUCCESS, (InetAddress)null, 0);
} else {
response = new Socks4Message(Socks4Message.REPLY_OK, (InetAddress)null, 0);
}
response.write(out);
String destHost = msg.host;
if (msg.ip != null)
destHost = msg.ip.getHostAddress();
try {
/*
* This may fail, e.g., if the remote port is closed (in
* optimistic terms: not open yet)
*/
cn = cm.openDirectTCPIPChannel(destHost, msg.port,
"127.0.0.1", 0);
} catch (IOException e) {
/*
* Simply close the local socket and wait for the next incoming
* connection
*/
try {
sock.close();
} catch (IOException ignore) {
}
return;
}
try {
r2l = new StreamForwarder(cn, null, sock, cn.stdoutStream, out, "RemoteToLocal");
l2r = new StreamForwarder(cn, r2l, sock, in, cn.stdinStream, "LocalToRemote");
} catch (IOException e) {
try {
/*
* This message is only visible during debugging, since we
* discard the channel immediatelly
*/
cn.cm.closeChannel(cn,
"Weird error during creation of StreamForwarder ("
+ e.getMessage() + ")", true);
} catch (IOException ignore) {
}
return;
}
r2l.setDaemon(true);
l2r.setDaemon(true);
r2l.start();
l2r.start();
}
}
public DynamicAcceptThread(ChannelManager cm, int local_port)
throws IOException {
this.cm = cm;
setName("DynamicAcceptThread");
ss = new ServerSocket(local_port);
}
public DynamicAcceptThread(ChannelManager cm, InetSocketAddress localAddress)
throws IOException {
this.cm = cm;
ss = new ServerSocket();
ss.bind(localAddress);
}
@Override
public void run() {
try {
cm.registerThread(this);
} catch (IOException e) {
stopWorking();
return;
}
while (true) {
Socket sock = null;
try {
sock = ss.accept();
} catch (IOException e) {
stopWorking();
return;
}
DynamicAcceptRunnable dar = new DynamicAcceptRunnable(new ServerAuthenticatorNone(), sock);
Thread t = new Thread(dar);
t.setDaemon(true);
t.start();
}
}
/*
* (non-Javadoc)
*
* @see com.trilead.ssh2.channel.IChannelWorkerThread#stopWorking()
*/
public void stopWorking() {
try {
/* This will lead to an IOException in the ss.accept() call */
ss.close();
} catch (IOException e) {
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/DynamicAcceptThread.java | Java | asf20 | 7,051 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.net.Socket;
import com.trilead.ssh2.log.Logger;
/**
* RemoteAcceptThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RemoteAcceptThread.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class RemoteAcceptThread extends Thread
{
private static final Logger log = Logger.getLogger(RemoteAcceptThread.class);
Channel c;
String remoteConnectedAddress;
int remoteConnectedPort;
String remoteOriginatorAddress;
int remoteOriginatorPort;
String targetAddress;
int targetPort;
Socket s;
public RemoteAcceptThread(Channel c, String remoteConnectedAddress, int remoteConnectedPort,
String remoteOriginatorAddress, int remoteOriginatorPort, String targetAddress, int targetPort)
{
this.c = c;
this.remoteConnectedAddress = remoteConnectedAddress;
this.remoteConnectedPort = remoteConnectedPort;
this.remoteOriginatorAddress = remoteOriginatorAddress;
this.remoteOriginatorPort = remoteOriginatorPort;
this.targetAddress = targetAddress;
this.targetPort = targetPort;
if (log.isEnabled())
log.log(20, "RemoteAcceptThread: " + remoteConnectedAddress + "/" + remoteConnectedPort + ", R: "
+ remoteOriginatorAddress + "/" + remoteOriginatorPort);
}
public void run()
{
try
{
c.cm.sendOpenConfirmation(c);
s = new Socket(targetAddress, targetPort);
StreamForwarder r2l = new StreamForwarder(c, null, s, c.getStdoutStream(), s.getOutputStream(),
"RemoteToLocal");
StreamForwarder l2r = new StreamForwarder(c, null, null, s.getInputStream(), c.getStdinStream(),
"LocalToRemote");
/* No need to start two threads, one can be executed in the current thread */
r2l.setDaemon(true);
r2l.start();
l2r.run();
while (r2l.isAlive())
{
try
{
r2l.join();
}
catch (InterruptedException e)
{
}
}
/* If the channel is already closed, then this is a no-op */
c.cm.closeChannel(c, "EOF on both streams reached.", true);
s.close();
}
catch (IOException e)
{
log.log(50, "IOException in proxy code: " + e.getMessage());
try
{
c.cm.closeChannel(c, "IOException in proxy code (" + e.getMessage() + ")", true);
}
catch (IOException e1)
{
}
try
{
if (s != null)
s.close();
}
catch (IOException e1)
{
}
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/RemoteAcceptThread.java | Java | asf20 | 2,493 |
package com.trilead.ssh2.channel;
/**
* X11ServerData. Data regarding an x11 forwarding target.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: X11ServerData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*
*/
public class X11ServerData
{
public String hostname;
public int port;
public byte[] x11_magic_cookie; /* not the remote (fake) one, the local (real) one */
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/X11ServerData.java | Java | asf20 | 416 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* A StreamForwarder forwards data between two given streams.
* If two StreamForwarder threads are used (one for each direction)
* then one can be configured to shutdown the underlying channel/socket
* if both threads have finished forwarding (EOF).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: StreamForwarder.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class StreamForwarder extends Thread
{
final OutputStream os;
final InputStream is;
final byte[] buffer = new byte[Channel.CHANNEL_BUFFER_SIZE];
final Channel c;
final StreamForwarder sibling;
final Socket s;
final String mode;
StreamForwarder(Channel c, StreamForwarder sibling, Socket s, InputStream is, OutputStream os, String mode)
throws IOException
{
this.is = is;
this.os = os;
this.mode = mode;
this.c = c;
this.sibling = sibling;
this.s = s;
}
public void run()
{
try
{
while (true)
{
int len = is.read(buffer);
if (len <= 0)
break;
os.write(buffer, 0, len);
os.flush();
}
}
catch (IOException ignore)
{
try
{
c.cm.closeChannel(c, "Closed due to exception in StreamForwarder (" + mode + "): "
+ ignore.getMessage(), true);
}
catch (IOException e)
{
}
}
finally
{
try
{
os.close();
}
catch (IOException e1)
{
}
try
{
is.close();
}
catch (IOException e2)
{
}
if (sibling != null)
{
while (sibling.isAlive())
{
try
{
sibling.join();
}
catch (InterruptedException e)
{
}
}
try
{
c.cm.closeChannel(c, "StreamForwarder (" + mode + ") is cleaning up the connection", true);
}
catch (IOException e3)
{
}
}
if (s != null) {
try
{
s.close();
}
catch (IOException e1)
{
}
}
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/channel/StreamForwarder.java | Java | asf20 | 2,115 |
package com.trilead.ssh2;
/**
* An interface which needs to be implemented if you
* want to capture debugging messages.
*
* @see Connection#enableDebugging(boolean, DebugLogger)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DebugLogger.java,v 1.1 2008/03/03 07:01:36 cplattne Exp $
*/
public interface DebugLogger
{
/**
* Log a debug message.
*
* @param level 0-99, 99 is a the most verbose level
* @param className the class that generated the message
* @param message the debug message
*/
public void log(int level, String className, String message);
}
| 1030365071-xuechao | src/com/trilead/ssh2/DebugLogger.java | Java | asf20 | 622 |
package com.trilead.ssh2.log;
import com.trilead.ssh2.DebugLogger;
/**
* Logger - a very simple logger, mainly used during development.
* Is not based on log4j (to reduce external dependencies).
* However, if needed, something like log4j could easily be
* hooked in.
* <p>
* For speed reasons, the static variables are not protected
* with semaphores. In other words, if you dynamicaly change the
* logging settings, then some threads may still use the old setting.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Logger.java,v 1.2 2008/03/03 07:01:36 cplattne Exp $
*/
public class Logger
{
public static boolean enabled = false;
public static DebugLogger logger = null;
private String className;
public final static Logger getLogger(Class x)
{
return new Logger(x);
}
public Logger(Class x)
{
this.className = x.getName();
}
public final boolean isEnabled()
{
return enabled;
}
public final void log(int level, String message)
{
if (!enabled)
return;
DebugLogger target = logger;
if (target == null)
return;
target.log(level, className, message);
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/log/Logger.java | Java | asf20 | 1,195 |
package com.trilead.ssh2.signature;
import java.math.BigInteger;
/**
* RSAPublicKey.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RSAPublicKey.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class RSAPublicKey
{
BigInteger e;
BigInteger n;
public RSAPublicKey(BigInteger e, BigInteger n)
{
this.e = e;
this.n = n;
}
public BigInteger getE()
{
return e;
}
public BigInteger getN()
{
return n;
}
} | 1030365071-xuechao | src/com/trilead/ssh2/signature/RSAPublicKey.java | Java | asf20 | 487 |
package com.trilead.ssh2.signature;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import com.trilead.ssh2.crypto.digest.SHA1;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.packets.TypesWriter;
/**
* DSASHA1Verify.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DSASHA1Verify.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class DSASHA1Verify
{
private static final Logger log = Logger.getLogger(DSASHA1Verify.class);
public static DSAPublicKey decodeSSHDSAPublicKey(byte[] key) throws IOException
{
TypesReader tr = new TypesReader(key);
String key_format = tr.readString();
if (key_format.equals("ssh-dss") == false)
throw new IllegalArgumentException("This is not a ssh-dss public key!");
BigInteger p = tr.readMPINT();
BigInteger q = tr.readMPINT();
BigInteger g = tr.readMPINT();
BigInteger y = tr.readMPINT();
if (tr.remain() != 0)
throw new IOException("Padding in DSA public key!");
return new DSAPublicKey(p, q, g, y);
}
public static byte[] encodeSSHDSAPublicKey(DSAPublicKey pk) throws IOException
{
TypesWriter tw = new TypesWriter();
tw.writeString("ssh-dss");
tw.writeMPInt(pk.getP());
tw.writeMPInt(pk.getQ());
tw.writeMPInt(pk.getG());
tw.writeMPInt(pk.getY());
return tw.getBytes();
}
public static byte[] encodeSSHDSASignature(DSASignature ds)
{
TypesWriter tw = new TypesWriter();
tw.writeString("ssh-dss");
byte[] r = ds.getR().toByteArray();
byte[] s = ds.getS().toByteArray();
byte[] a40 = new byte[40];
/* Patch (unsigned) r and s into the target array. */
int r_copylen = (r.length < 20) ? r.length : 20;
int s_copylen = (s.length < 20) ? s.length : 20;
System.arraycopy(r, r.length - r_copylen, a40, 20 - r_copylen, r_copylen);
System.arraycopy(s, s.length - s_copylen, a40, 40 - s_copylen, s_copylen);
tw.writeString(a40, 0, 40);
return tw.getBytes();
}
public static DSASignature decodeSSHDSASignature(byte[] sig) throws IOException
{
byte[] rsArray = null;
if (sig.length == 40)
{
/* OK, another broken SSH server. */
rsArray = sig;
}
else
{
/* Hopefully a server obeing the standard... */
TypesReader tr = new TypesReader(sig);
String sig_format = tr.readString();
if (sig_format.equals("ssh-dss") == false)
throw new IOException("Peer sent wrong signature format");
rsArray = tr.readByteString();
if (rsArray.length != 40)
throw new IOException("Peer sent corrupt signature");
if (tr.remain() != 0)
throw new IOException("Padding in DSA signature!");
}
/* Remember, s and r are unsigned ints. */
byte[] tmp = new byte[20];
System.arraycopy(rsArray, 0, tmp, 0, 20);
BigInteger r = new BigInteger(1, tmp);
System.arraycopy(rsArray, 20, tmp, 0, 20);
BigInteger s = new BigInteger(1, tmp);
if (log.isEnabled())
{
log.log(30, "decoded ssh-dss signature: first bytes r(" + ((rsArray[0]) & 0xff) + "), s("
+ ((rsArray[20]) & 0xff) + ")");
}
return new DSASignature(r, s);
}
public static boolean verifySignature(byte[] message, DSASignature ds, DSAPublicKey dpk) throws IOException
{
/* Inspired by Bouncycastle's DSASigner class */
SHA1 md = new SHA1();
md.update(message);
byte[] sha_message = new byte[md.getDigestLength()];
md.digest(sha_message);
BigInteger m = new BigInteger(1, sha_message);
BigInteger r = ds.getR();
BigInteger s = ds.getS();
BigInteger g = dpk.getG();
BigInteger p = dpk.getP();
BigInteger q = dpk.getQ();
BigInteger y = dpk.getY();
BigInteger zero = BigInteger.ZERO;
if (log.isEnabled())
{
log.log(60, "ssh-dss signature: m: " + m.toString(16));
log.log(60, "ssh-dss signature: r: " + r.toString(16));
log.log(60, "ssh-dss signature: s: " + s.toString(16));
log.log(60, "ssh-dss signature: g: " + g.toString(16));
log.log(60, "ssh-dss signature: p: " + p.toString(16));
log.log(60, "ssh-dss signature: q: " + q.toString(16));
log.log(60, "ssh-dss signature: y: " + y.toString(16));
}
if (zero.compareTo(r) >= 0 || q.compareTo(r) <= 0)
{
log.log(20, "ssh-dss signature: zero.compareTo(r) >= 0 || q.compareTo(r) <= 0");
return false;
}
if (zero.compareTo(s) >= 0 || q.compareTo(s) <= 0)
{
log.log(20, "ssh-dss signature: zero.compareTo(s) >= 0 || q.compareTo(s) <= 0");
return false;
}
BigInteger w = s.modInverse(q);
BigInteger u1 = m.multiply(w).mod(q);
BigInteger u2 = r.multiply(w).mod(q);
u1 = g.modPow(u1, p);
u2 = y.modPow(u2, p);
BigInteger v = u1.multiply(u2).mod(p).mod(q);
return v.equals(r);
}
public static DSASignature generateSignature(byte[] message, DSAPrivateKey pk, SecureRandom rnd)
{
SHA1 md = new SHA1();
md.update(message);
byte[] sha_message = new byte[md.getDigestLength()];
md.digest(sha_message);
BigInteger m = new BigInteger(1, sha_message);
BigInteger k;
int qBitLength = pk.getQ().bitLength();
do
{
k = new BigInteger(qBitLength, rnd);
}
while (k.compareTo(pk.getQ()) >= 0);
BigInteger r = pk.getG().modPow(k, pk.getP()).mod(pk.getQ());
k = k.modInverse(pk.getQ()).multiply(m.add((pk).getX().multiply(r)));
BigInteger s = k.mod(pk.getQ());
return new DSASignature(r, s);
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/signature/DSASHA1Verify.java | Java | asf20 | 5,551 |
package com.trilead.ssh2.signature;
import java.math.BigInteger;
/**
* RSAPrivateKey.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RSAPrivateKey.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class RSAPrivateKey
{
private BigInteger d;
private BigInteger e;
private BigInteger n;
public RSAPrivateKey(BigInteger d, BigInteger e, BigInteger n)
{
this.d = d;
this.e = e;
this.n = n;
}
public BigInteger getD()
{
return d;
}
public BigInteger getE()
{
return e;
}
public BigInteger getN()
{
return n;
}
public RSAPublicKey getPublicKey()
{
return new RSAPublicKey(e, n);
}
} | 1030365071-xuechao | src/com/trilead/ssh2/signature/RSAPrivateKey.java | Java | asf20 | 693 |
package com.trilead.ssh2.signature;
import java.math.BigInteger;
/**
* DSAPublicKey.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DSAPublicKey.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class DSAPublicKey
{
private BigInteger p;
private BigInteger q;
private BigInteger g;
private BigInteger y;
public DSAPublicKey(BigInteger p, BigInteger q, BigInteger g, BigInteger y)
{
this.p = p;
this.q = q;
this.g = g;
this.y = y;
}
public BigInteger getP()
{
return p;
}
public BigInteger getQ()
{
return q;
}
public BigInteger getG()
{
return g;
}
public BigInteger getY()
{
return y;
}
} | 1030365071-xuechao | src/com/trilead/ssh2/signature/DSAPublicKey.java | Java | asf20 | 709 |
package com.trilead.ssh2.signature;
import java.math.BigInteger;
/**
* RSASignature.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RSASignature.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class RSASignature
{
BigInteger s;
public BigInteger getS()
{
return s;
}
public RSASignature(BigInteger s)
{
this.s = s;
}
} | 1030365071-xuechao | src/com/trilead/ssh2/signature/RSASignature.java | Java | asf20 | 398 |
package com.trilead.ssh2.signature;
import java.io.IOException;
import java.math.BigInteger;
import com.trilead.ssh2.crypto.SimpleDERReader;
import com.trilead.ssh2.crypto.digest.SHA1;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.packets.TypesWriter;
/**
* RSASHA1Verify.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RSASHA1Verify.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class RSASHA1Verify
{
private static final Logger log = Logger.getLogger(RSASHA1Verify.class);
public static RSAPublicKey decodeSSHRSAPublicKey(byte[] key) throws IOException
{
TypesReader tr = new TypesReader(key);
String key_format = tr.readString();
if (key_format.equals("ssh-rsa") == false)
throw new IllegalArgumentException("This is not a ssh-rsa public key");
BigInteger e = tr.readMPINT();
BigInteger n = tr.readMPINT();
if (tr.remain() != 0)
throw new IOException("Padding in RSA public key!");
return new RSAPublicKey(e, n);
}
public static byte[] encodeSSHRSAPublicKey(RSAPublicKey pk) throws IOException
{
TypesWriter tw = new TypesWriter();
tw.writeString("ssh-rsa");
tw.writeMPInt(pk.getE());
tw.writeMPInt(pk.getN());
return tw.getBytes();
}
public static RSASignature decodeSSHRSASignature(byte[] sig) throws IOException
{
TypesReader tr = new TypesReader(sig);
String sig_format = tr.readString();
if (sig_format.equals("ssh-rsa") == false)
throw new IOException("Peer sent wrong signature format");
/* S is NOT an MPINT. "The value for 'rsa_signature_blob' is encoded as a string
* containing s (which is an integer, without lengths or padding, unsigned and in
* network byte order)." See also below.
*/
byte[] s = tr.readByteString();
if (s.length == 0)
throw new IOException("Error in RSA signature, S is empty.");
if (log.isEnabled())
{
log.log(80, "Decoding ssh-rsa signature string (length: " + s.length + ")");
}
if (tr.remain() != 0)
throw new IOException("Padding in RSA signature!");
return new RSASignature(new BigInteger(1, s));
}
public static byte[] encodeSSHRSASignature(RSASignature sig) throws IOException
{
TypesWriter tw = new TypesWriter();
tw.writeString("ssh-rsa");
/* S is NOT an MPINT. "The value for 'rsa_signature_blob' is encoded as a string
* containing s (which is an integer, without lengths or padding, unsigned and in
* network byte order)."
*/
byte[] s = sig.getS().toByteArray();
/* Remove first zero sign byte, if present */
if ((s.length > 1) && (s[0] == 0x00))
tw.writeString(s, 1, s.length - 1);
else
tw.writeString(s, 0, s.length);
return tw.getBytes();
}
public static RSASignature generateSignature(byte[] message, RSAPrivateKey pk) throws IOException
{
SHA1 md = new SHA1();
md.update(message);
byte[] sha_message = new byte[md.getDigestLength()];
md.digest(sha_message);
byte[] der_header = new byte[] { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00,
0x04, 0x14 };
int rsa_block_len = (pk.getN().bitLength() + 7) / 8;
int num_pad = rsa_block_len - (2 + der_header.length + sha_message.length) - 1;
if (num_pad < 8)
throw new IOException("Cannot sign with RSA, message too long");
byte[] sig = new byte[der_header.length + sha_message.length + 2 + num_pad];
sig[0] = 0x01;
for (int i = 0; i < num_pad; i++)
{
sig[i + 1] = (byte) 0xff;
}
sig[num_pad + 1] = 0x00;
System.arraycopy(der_header, 0, sig, 2 + num_pad, der_header.length);
System.arraycopy(sha_message, 0, sig, 2 + num_pad + der_header.length, sha_message.length);
BigInteger m = new BigInteger(1, sig);
BigInteger s = m.modPow(pk.getD(), pk.getN());
return new RSASignature(s);
}
public static boolean verifySignature(byte[] message, RSASignature ds, RSAPublicKey dpk) throws IOException
{
SHA1 md = new SHA1();
md.update(message);
byte[] sha_message = new byte[md.getDigestLength()];
md.digest(sha_message);
BigInteger n = dpk.getN();
BigInteger e = dpk.getE();
BigInteger s = ds.getS();
if (n.compareTo(s) <= 0)
{
log.log(20, "ssh-rsa signature: n.compareTo(s) <= 0");
return false;
}
int rsa_block_len = (n.bitLength() + 7) / 8;
/* And now the show begins */
if (rsa_block_len < 1)
{
log.log(20, "ssh-rsa signature: rsa_block_len < 1");
return false;
}
byte[] v = s.modPow(e, n).toByteArray();
int startpos = 0;
if ((v.length > 0) && (v[0] == 0x00))
startpos++;
if ((v.length - startpos) != (rsa_block_len - 1))
{
log.log(20, "ssh-rsa signature: (v.length - startpos) != (rsa_block_len - 1)");
return false;
}
if (v[startpos] != 0x01)
{
log.log(20, "ssh-rsa signature: v[startpos] != 0x01");
return false;
}
int pos = startpos + 1;
while (true)
{
if (pos >= v.length)
{
log.log(20, "ssh-rsa signature: pos >= v.length");
return false;
}
if (v[pos] == 0x00)
break;
if (v[pos] != (byte) 0xff)
{
log.log(20, "ssh-rsa signature: v[pos] != (byte) 0xff");
return false;
}
pos++;
}
int num_pad = pos - (startpos + 1);
if (num_pad < 8)
{
log.log(20, "ssh-rsa signature: num_pad < 8");
return false;
}
pos++;
if (pos >= v.length)
{
log.log(20, "ssh-rsa signature: pos >= v.length");
return false;
}
SimpleDERReader dr = new SimpleDERReader(v, pos, v.length - pos);
byte[] seq = dr.readSequenceAsByteArray();
if (dr.available() != 0)
{
log.log(20, "ssh-rsa signature: dr.available() != 0");
return false;
}
dr.resetInput(seq);
/* Read digestAlgorithm */
byte digestAlgorithm[] = dr.readSequenceAsByteArray();
/* Inspired by RFC 3347, however, ignoring the comment regarding old BER based implementations */
if ((digestAlgorithm.length < 8) || (digestAlgorithm.length > 9))
{
log.log(20, "ssh-rsa signature: (digestAlgorithm.length < 8) || (digestAlgorithm.length > 9)");
return false;
}
byte[] digestAlgorithm_sha1 = new byte[] { 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00 };
for (int i = 0; i < digestAlgorithm.length; i++)
{
if (digestAlgorithm[i] != digestAlgorithm_sha1[i])
{
log.log(20, "ssh-rsa signature: digestAlgorithm[i] != digestAlgorithm_sha1[i]");
return false;
}
}
byte[] digest = dr.readOctetString();
if (dr.available() != 0)
{
log.log(20, "ssh-rsa signature: dr.available() != 0 (II)");
return false;
}
if (digest.length != sha_message.length)
{
log.log(20, "ssh-rsa signature: digest.length != sha_message.length");
return false;
}
for (int i = 0; i < sha_message.length; i++)
{
if (sha_message[i] != digest[i])
{
log.log(20, "ssh-rsa signature: sha_message[i] != digest[i]");
return false;
}
}
return true;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/signature/RSASHA1Verify.java | Java | asf20 | 7,162 |
package com.trilead.ssh2.signature;
import java.math.BigInteger;
/**
* DSAPrivateKey.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DSAPrivateKey.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class DSAPrivateKey
{
private BigInteger p;
private BigInteger q;
private BigInteger g;
private BigInteger x;
private BigInteger y;
public DSAPrivateKey(BigInteger p, BigInteger q, BigInteger g,
BigInteger y, BigInteger x)
{
this.p = p;
this.q = q;
this.g = g;
this.y = y;
this.x = x;
}
public BigInteger getP()
{
return p;
}
public BigInteger getQ()
{
return q;
}
public BigInteger getG()
{
return g;
}
public BigInteger getY()
{
return y;
}
public BigInteger getX()
{
return x;
}
public DSAPublicKey getPublicKey()
{
return new DSAPublicKey(p, q, g, y);
}
} | 1030365071-xuechao | src/com/trilead/ssh2/signature/DSAPrivateKey.java | Java | asf20 | 910 |
package com.trilead.ssh2.signature;
import java.math.BigInteger;
/**
* DSASignature.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DSASignature.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class DSASignature
{
private BigInteger r;
private BigInteger s;
public DSASignature(BigInteger r, BigInteger s)
{
this.r = r;
this.s = s;
}
public BigInteger getR()
{
return r;
}
public BigInteger getS()
{
return s;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/signature/DSASignature.java | Java | asf20 | 505 |
package com.trilead.ssh2;
/**
* Contains constants that can be used to specify what conditions to wait for on
* a SSH-2 channel (e.g., represented by a {@link Session}).
*
* @see Session#waitForCondition(int, long)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelCondition.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public abstract interface ChannelCondition
{
/**
* A timeout has occurred, none of your requested conditions is fulfilled.
* However, other conditions may be true - therefore, NEVER use the "=="
* operator to test for this (or any other) condition. Always use
* something like <code>((cond & ChannelCondition.CLOSED) != 0)</code>.
*/
public static final int TIMEOUT = 1;
/**
* The underlying SSH-2 channel, however not necessarily the whole connection,
* has been closed. This implies <code>EOF</code>. Note that there may still
* be unread stdout or stderr data in the local window, i.e, <code>STDOUT_DATA</code>
* or/and <code>STDERR_DATA</code> may be set at the same time.
*/
public static final int CLOSED = 2;
/**
* There is stdout data available that is ready to be consumed.
*/
public static final int STDOUT_DATA = 4;
/**
* There is stderr data available that is ready to be consumed.
*/
public static final int STDERR_DATA = 8;
/**
* EOF on has been reached, no more _new_ stdout or stderr data will arrive
* from the remote server. However, there may be unread stdout or stderr
* data, i.e, <code>STDOUT_DATA</code> or/and <code>STDERR_DATA</code>
* may be set at the same time.
*/
public static final int EOF = 16;
/**
* The exit status of the remote process is available.
* Some servers never send the exist status, or occasionally "forget" to do so.
*/
public static final int EXIT_STATUS = 32;
/**
* The exit signal of the remote process is available.
*/
public static final int EXIT_SIGNAL = 64;
}
| 1030365071-xuechao | src/com/trilead/ssh2/ChannelCondition.java | Java | asf20 | 2,005 |
package com.trilead.ssh2;
/**
* A <code>HTTPProxyData</code> object is used to specify the needed connection data
* to connect through a HTTP proxy.
*
* @see Connection#setProxyData(ProxyData)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HTTPProxyData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class HTTPProxyData implements ProxyData
{
public final String proxyHost;
public final int proxyPort;
public final String proxyUser;
public final String proxyPass;
public final String[] requestHeaderLines;
/**
* Same as calling {@link #HTTPProxyData(String, int, String, String) HTTPProxyData(proxyHost, proxyPort, <code>null</code>, <code>null</code>)}
*
* @param proxyHost Proxy hostname.
* @param proxyPort Proxy port.
*/
public HTTPProxyData(String proxyHost, int proxyPort)
{
this(proxyHost, proxyPort, null, null);
}
/**
* Same as calling {@link #HTTPProxyData(String, int, String, String, String[]) HTTPProxyData(proxyHost, proxyPort, <code>null</code>, <code>null</code>, <code>null</code>)}
*
* @param proxyHost Proxy hostname.
* @param proxyPort Proxy port.
* @param proxyUser Username for basic authentication (<code>null</code> if no authentication is needed).
* @param proxyPass Password for basic authentication (<code>null</code> if no authentication is needed).
*/
public HTTPProxyData(String proxyHost, int proxyPort, String proxyUser, String proxyPass)
{
this(proxyHost, proxyPort, proxyUser, proxyPass, null);
}
/**
* Connection data for a HTTP proxy. It is possible to specify a username and password
* if the proxy requires basic authentication. Also, additional request header lines can
* be specified (e.g., "User-Agent: CERN-LineMode/2.15 libwww/2.17b3").
* <p>
* Please note: if you want to use basic authentication, then both <code>proxyUser</code>
* and <code>proxyPass</code> must be non-null.
* <p>
* Here is an example:
* <p>
* <code>
* new HTTPProxyData("192.168.1.1", "3128", "proxyuser", "secret", new String[] {"User-Agent: TrileadBasedClient/1.0", "X-My-Proxy-Option: something"});
* </code>
*
* @param proxyHost Proxy hostname.
* @param proxyPort Proxy port.
* @param proxyUser Username for basic authentication (<code>null</code> if no authentication is needed).
* @param proxyPass Password for basic authentication (<code>null</code> if no authentication is needed).
* @param requestHeaderLines An array with additional request header lines (without end-of-line markers)
* that have to be sent to the server. May be <code>null</code>.
*/
public HTTPProxyData(String proxyHost, int proxyPort, String proxyUser, String proxyPass,
String[] requestHeaderLines)
{
if (proxyHost == null)
throw new IllegalArgumentException("proxyHost must be non-null");
if (proxyPort < 0)
throw new IllegalArgumentException("proxyPort must be non-negative");
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.proxyUser = proxyUser;
this.proxyPass = proxyPass;
this.requestHeaderLines = requestHeaderLines;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/HTTPProxyData.java | Java | asf20 | 3,189 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.Vector;
import com.trilead.ssh2.ConnectionInfo;
import com.trilead.ssh2.ConnectionMonitor;
import com.trilead.ssh2.DHGexParameters;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.HTTPProxyException;
import com.trilead.ssh2.ProxyData;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.compression.ICompressor;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketDisconnect;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.util.Tokenizer;
/*
* Yes, the "standard" is a big mess. On one side, the say that arbitary channel
* packets are allowed during kex exchange, on the other side we need to blindly
* ignore the next _packet_ if the KEX guess was wrong. Where do we know from that
* the next packet is not a channel data packet? Yes, we could check if it is in
* the KEX range. But the standard says nothing about this. The OpenSSH guys
* block local "normal" traffic during KEX. That's fine - however, they assume
* that the other side is doing the same. During re-key, if they receive traffic
* other than KEX, they become horribly irritated and kill the connection. Since
* we are very likely going to communicate with OpenSSH servers, we have to play
* the same game - even though we could do better.
*
* btw: having stdout and stderr on the same channel, with a shared window, is
* also a VERY good idea... =(
*/
/**
* TransportManager.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TransportManager.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class TransportManager
{
private static final Logger log = Logger.getLogger(TransportManager.class);
class HandlerEntry
{
MessageHandler mh;
int low;
int high;
}
private final Vector<byte[]> asynchronousQueue = new Vector<byte[]>();
private Thread asynchronousThread = null;
class AsynchronousWorker extends Thread
{
public void run()
{
while (true)
{
byte[] msg = null;
synchronized (asynchronousQueue)
{
if (asynchronousQueue.size() == 0)
{
/* After the queue is empty for about 2 seconds, stop this thread */
try
{
asynchronousQueue.wait(2000);
}
catch (InterruptedException e)
{
/* OKOK, if somebody interrupts us, then we may die earlier. */
}
if (asynchronousQueue.size() == 0)
{
asynchronousThread = null;
return;
}
}
msg = asynchronousQueue.remove(0);
}
/* The following invocation may throw an IOException.
* There is no point in handling it - it simply means
* that the connection has a problem and we should stop
* sending asynchronously messages. We do not need to signal that
* we have exited (asynchronousThread = null): further
* messages in the queue cannot be sent by this or any
* other thread.
* Other threads will sooner or later (when receiving or
* sending the next message) get the same IOException and
* get to the same conclusion.
*/
try
{
sendMessage(msg);
}
catch (IOException e)
{
return;
}
}
}
}
String hostname;
int port;
final Socket sock = new Socket();
Object connectionSemaphore = new Object();
boolean flagKexOngoing = false;
boolean connectionClosed = false;
Throwable reasonClosedCause = null;
TransportConnection tc;
KexManager km;
Vector<HandlerEntry> messageHandlers = new Vector<HandlerEntry>();
Thread receiveThread;
Vector connectionMonitors = new Vector();
boolean monitorsWereInformed = false;
/**
* There were reports that there are JDKs which use
* the resolver even though one supplies a dotted IP
* address in the Socket constructor. That is why we
* try to generate the InetAdress "by hand".
*
* @param host
* @return the InetAddress
* @throws UnknownHostException
*/
private InetAddress createInetAddress(String host) throws UnknownHostException
{
/* Check if it is a dotted IP4 address */
InetAddress addr = parseIPv4Address(host);
if (addr != null)
return addr;
return InetAddress.getByName(host);
}
private InetAddress parseIPv4Address(String host) throws UnknownHostException
{
if (host == null)
return null;
String[] quad = Tokenizer.parseTokens(host, '.');
if ((quad == null) || (quad.length != 4))
return null;
byte[] addr = new byte[4];
for (int i = 0; i < 4; i++)
{
int part = 0;
if ((quad[i].length() == 0) || (quad[i].length() > 3))
return null;
for (int k = 0; k < quad[i].length(); k++)
{
char c = quad[i].charAt(k);
/* No, Character.isDigit is not the same */
if ((c < '0') || (c > '9'))
return null;
part = part * 10 + (c - '0');
}
if (part > 255) /* 300.1.2.3 is invalid =) */
return null;
addr[i] = (byte) part;
}
return InetAddress.getByAddress(host, addr);
}
public TransportManager(String host, int port) throws IOException
{
this.hostname = host;
this.port = port;
}
public int getPacketOverheadEstimate()
{
return tc.getPacketOverheadEstimate();
}
public void setTcpNoDelay(boolean state) throws IOException
{
sock.setTcpNoDelay(state);
}
public void setSoTimeout(int timeout) throws IOException
{
sock.setSoTimeout(timeout);
}
public ConnectionInfo getConnectionInfo(int kexNumber) throws IOException
{
return km.getOrWaitForConnectionInfo(kexNumber);
}
public Throwable getReasonClosedCause()
{
synchronized (connectionSemaphore)
{
return reasonClosedCause;
}
}
public byte[] getSessionIdentifier()
{
return km.sessionId;
}
public void close(Throwable cause, boolean useDisconnectPacket)
{
if (useDisconnectPacket == false)
{
/* OK, hard shutdown - do not aquire the semaphore,
* perhaps somebody is inside (and waits until the remote
* side is ready to accept new data). */
try
{
sock.close();
}
catch (IOException ignore)
{
}
/* OK, whoever tried to send data, should now agree that
* there is no point in further waiting =)
* It is safe now to aquire the semaphore.
*/
}
synchronized (connectionSemaphore)
{
if (connectionClosed == false)
{
if (useDisconnectPacket == true)
{
try
{
byte[] msg = new PacketDisconnect(Packets.SSH_DISCONNECT_BY_APPLICATION, cause.getMessage(), "")
.getPayload();
if (tc != null)
tc.sendMessage(msg);
}
catch (IOException ignore)
{
}
try
{
sock.close();
}
catch (IOException ignore)
{
}
}
connectionClosed = true;
reasonClosedCause = cause; /* may be null */
}
connectionSemaphore.notifyAll();
}
/* No check if we need to inform the monitors */
Vector monitors = null;
synchronized (this)
{
/* Short term lock to protect "connectionMonitors"
* and "monitorsWereInformed"
* (they may be modified concurrently)
*/
if (monitorsWereInformed == false)
{
monitorsWereInformed = true;
monitors = (Vector) connectionMonitors.clone();
}
}
if (monitors != null)
{
for (int i = 0; i < monitors.size(); i++)
{
try
{
ConnectionMonitor cmon = (ConnectionMonitor) monitors.elementAt(i);
cmon.connectionLost(reasonClosedCause);
}
catch (Exception ignore)
{
}
}
}
}
private void establishConnection(ProxyData proxyData, int connectTimeout) throws IOException
{
/* See the comment for createInetAddress() */
if (proxyData == null)
{
InetAddress addr = createInetAddress(hostname);
sock.connect(new InetSocketAddress(addr, port), connectTimeout);
sock.setSoTimeout(0);
return;
}
if (proxyData instanceof HTTPProxyData)
{
HTTPProxyData pd = (HTTPProxyData) proxyData;
/* At the moment, we only support HTTP proxies */
InetAddress addr = createInetAddress(pd.proxyHost);
sock.connect(new InetSocketAddress(addr, pd.proxyPort), connectTimeout);
sock.setSoTimeout(0);
/* OK, now tell the proxy where we actually want to connect to */
StringBuffer sb = new StringBuffer();
sb.append("CONNECT ");
sb.append(hostname);
sb.append(':');
sb.append(port);
sb.append(" HTTP/1.0\r\n");
if ((pd.proxyUser != null) && (pd.proxyPass != null))
{
String credentials = pd.proxyUser + ":" + pd.proxyPass;
char[] encoded = Base64.encode(credentials.getBytes("ISO-8859-1"));
sb.append("Proxy-Authorization: Basic ");
sb.append(encoded);
sb.append("\r\n");
}
if (pd.requestHeaderLines != null)
{
for (int i = 0; i < pd.requestHeaderLines.length; i++)
{
if (pd.requestHeaderLines[i] != null)
{
sb.append(pd.requestHeaderLines[i]);
sb.append("\r\n");
}
}
}
sb.append("\r\n");
OutputStream out = sock.getOutputStream();
out.write(sb.toString().getBytes("ISO-8859-1"));
out.flush();
/* Now parse the HTTP response */
byte[] buffer = new byte[1024];
InputStream in = sock.getInputStream();
int len = ClientServerHello.readLineRN(in, buffer);
String httpReponse = new String(buffer, 0, len, "ISO-8859-1");
if (httpReponse.startsWith("HTTP/") == false)
throw new IOException("The proxy did not send back a valid HTTP response.");
/* "HTTP/1.X XYZ X" => 14 characters minimum */
if ((httpReponse.length() < 14) || (httpReponse.charAt(8) != ' ') || (httpReponse.charAt(12) != ' '))
throw new IOException("The proxy did not send back a valid HTTP response.");
int errorCode = 0;
try
{
errorCode = Integer.parseInt(httpReponse.substring(9, 12));
}
catch (NumberFormatException ignore)
{
throw new IOException("The proxy did not send back a valid HTTP response.");
}
if ((errorCode < 0) || (errorCode > 999))
throw new IOException("The proxy did not send back a valid HTTP response.");
if (errorCode != 200)
{
throw new HTTPProxyException(httpReponse.substring(13), errorCode);
}
/* OK, read until empty line */
while (true)
{
len = ClientServerHello.readLineRN(in, buffer);
if (len == 0)
break;
}
return;
}
throw new IOException("Unsupported ProxyData");
}
public void initialize(CryptoWishList cwl, ServerHostKeyVerifier verifier, DHGexParameters dhgex,
int connectTimeout, SecureRandom rnd, ProxyData proxyData) throws IOException
{
/* First, establish the TCP connection to the SSH-2 server */
establishConnection(proxyData, connectTimeout);
/* Parse the server line and say hello - important: this information is later needed for the
* key exchange (to stop man-in-the-middle attacks) - that is why we wrap it into an object
* for later use.
*/
ClientServerHello csh = new ClientServerHello(sock.getInputStream(), sock.getOutputStream());
tc = new TransportConnection(sock.getInputStream(), sock.getOutputStream(), rnd);
km = new KexManager(this, csh, cwl, hostname, port, verifier, rnd);
km.initiateKEX(cwl, dhgex);
receiveThread = new Thread(new Runnable()
{
public void run()
{
try
{
receiveLoop();
}
catch (IOException e)
{
close(e, false);
if (log.isEnabled())
log.log(10, "Receive thread: error in receiveLoop: " + e.getMessage());
}
if (log.isEnabled())
log.log(50, "Receive thread: back from receiveLoop");
/* Tell all handlers that it is time to say goodbye */
if (km != null)
{
try
{
km.handleMessage(null, 0);
}
catch (IOException e)
{
}
}
for (int i = 0; i < messageHandlers.size(); i++)
{
HandlerEntry he = messageHandlers.elementAt(i);
try
{
he.mh.handleMessage(null, 0);
}
catch (Exception ignore)
{
}
}
}
});
receiveThread.setDaemon(true);
receiveThread.start();
}
public void registerMessageHandler(MessageHandler mh, int low, int high)
{
HandlerEntry he = new HandlerEntry();
he.mh = mh;
he.low = low;
he.high = high;
synchronized (messageHandlers)
{
messageHandlers.addElement(he);
}
}
public void removeMessageHandler(MessageHandler mh, int low, int high)
{
synchronized (messageHandlers)
{
for (int i = 0; i < messageHandlers.size(); i++)
{
HandlerEntry he = messageHandlers.elementAt(i);
if ((he.mh == mh) && (he.low == low) && (he.high == high))
{
messageHandlers.removeElementAt(i);
break;
}
}
}
}
public void sendKexMessage(byte[] msg) throws IOException
{
synchronized (connectionSemaphore)
{
if (connectionClosed)
{
throw (IOException) new IOException("Sorry, this connection is closed.").initCause(reasonClosedCause);
}
flagKexOngoing = true;
try
{
tc.sendMessage(msg);
}
catch (IOException e)
{
close(e, false);
throw e;
}
}
}
public void kexFinished() throws IOException
{
synchronized (connectionSemaphore)
{
flagKexOngoing = false;
connectionSemaphore.notifyAll();
}
}
public void forceKeyExchange(CryptoWishList cwl, DHGexParameters dhgex) throws IOException
{
km.initiateKEX(cwl, dhgex);
}
public void changeRecvCipher(BlockCipher bc, MAC mac)
{
tc.changeRecvCipher(bc, mac);
}
public void changeSendCipher(BlockCipher bc, MAC mac)
{
tc.changeSendCipher(bc, mac);
}
/**
* @param comp
*/
public void changeRecvCompression(ICompressor comp) {
tc.changeRecvCompression(comp);
}
/**
* @param comp
*/
public void changeSendCompression(ICompressor comp) {
tc.changeSendCompression(comp);
}
/**
*
*/
public void startCompression() {
tc.startCompression();
}
public void sendAsynchronousMessage(byte[] msg) throws IOException
{
synchronized (asynchronousQueue)
{
asynchronousQueue.addElement(msg);
/* This limit should be flexible enough. We need this, otherwise the peer
* can flood us with global requests (and other stuff where we have to reply
* with an asynchronous message) and (if the server just sends data and does not
* read what we send) this will probably put us in a low memory situation
* (our send queue would grow and grow and...) */
if (asynchronousQueue.size() > 100)
throw new IOException("Error: the peer is not consuming our asynchronous replies.");
/* Check if we have an asynchronous sending thread */
if (asynchronousThread == null)
{
asynchronousThread = new AsynchronousWorker();
asynchronousThread.setDaemon(true);
asynchronousThread.start();
/* The thread will stop after 2 seconds of inactivity (i.e., empty queue) */
}
}
}
public void setConnectionMonitors(Vector monitors)
{
synchronized (this)
{
connectionMonitors = (Vector) monitors.clone();
}
}
public void sendMessage(byte[] msg) throws IOException
{
if (Thread.currentThread() == receiveThread)
throw new IOException("Assertion error: sendMessage may never be invoked by the receiver thread!");
synchronized (connectionSemaphore)
{
while (true)
{
if (connectionClosed)
{
throw (IOException) new IOException("Sorry, this connection is closed.")
.initCause(reasonClosedCause);
}
if (flagKexOngoing == false)
break;
try
{
connectionSemaphore.wait();
}
catch (InterruptedException e)
{
}
}
try
{
tc.sendMessage(msg);
}
catch (IOException e)
{
close(e, false);
throw e;
}
}
}
public void receiveLoop() throws IOException
{
byte[] msg = new byte[35000];
while (true)
{
int msglen = tc.receiveMessage(msg, 0, msg.length);
int type = msg[0] & 0xff;
if (type == Packets.SSH_MSG_IGNORE)
continue;
if (type == Packets.SSH_MSG_DEBUG)
{
if (log.isEnabled())
{
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte();
tr.readBoolean();
StringBuffer debugMessageBuffer = new StringBuffer();
debugMessageBuffer.append(tr.readString("UTF-8"));
for (int i = 0; i < debugMessageBuffer.length(); i++)
{
char c = debugMessageBuffer.charAt(i);
if ((c >= 32) && (c <= 126))
continue;
debugMessageBuffer.setCharAt(i, '\uFFFD');
}
log.log(50, "DEBUG Message from remote: '" + debugMessageBuffer.toString() + "'");
}
continue;
}
if (type == Packets.SSH_MSG_UNIMPLEMENTED)
{
throw new IOException("Peer sent UNIMPLEMENTED message, that should not happen.");
}
if (type == Packets.SSH_MSG_DISCONNECT)
{
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte();
int reason_code = tr.readUINT32();
StringBuffer reasonBuffer = new StringBuffer();
reasonBuffer.append(tr.readString("UTF-8"));
/*
* Do not get fooled by servers that send abnormal long error
* messages
*/
if (reasonBuffer.length() > 255)
{
reasonBuffer.setLength(255);
reasonBuffer.setCharAt(254, '.');
reasonBuffer.setCharAt(253, '.');
reasonBuffer.setCharAt(252, '.');
}
/*
* Also, check that the server did not send charcaters that may
* screw up the receiver -> restrict to reasonable US-ASCII
* subset -> "printable characters" (ASCII 32 - 126). Replace
* all others with 0xFFFD (UNICODE replacement character).
*/
for (int i = 0; i < reasonBuffer.length(); i++)
{
char c = reasonBuffer.charAt(i);
if ((c >= 32) && (c <= 126))
continue;
reasonBuffer.setCharAt(i, '\uFFFD');
}
throw new IOException("Peer sent DISCONNECT message (reason code " + reason_code + "): "
+ reasonBuffer.toString());
}
/*
* Is it a KEX Packet?
*/
if ((type == Packets.SSH_MSG_KEXINIT) || (type == Packets.SSH_MSG_NEWKEYS)
|| ((type >= 30) && (type <= 49)))
{
km.handleMessage(msg, msglen);
continue;
}
if (type == Packets.SSH_MSG_USERAUTH_SUCCESS) {
tc.startCompression();
}
MessageHandler mh = null;
for (int i = 0; i < messageHandlers.size(); i++)
{
HandlerEntry he = messageHandlers.elementAt(i);
if ((he.low <= type) && (type <= he.high))
{
mh = he.mh;
break;
}
}
if (mh == null)
throw new IOException("Unexpected SSH message (type " + type + ")");
mh.handleMessage(msg, msglen);
}
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/TransportManager.java | Java | asf20 | 19,652 |
package com.trilead.ssh2.transport;
/**
* NegotiateException.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: NegotiateException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class NegotiateException extends Exception
{
private static final long serialVersionUID = 3689910669428143157L;
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/NegotiateException.java | Java | asf20 | 340 |
package com.trilead.ssh2.transport;
import java.io.IOException;
/**
* MessageHandler.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: MessageHandler.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public interface MessageHandler
{
public void handleMessage(byte[] msg, int msglen) throws IOException;
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/MessageHandler.java | Java | asf20 | 348 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import com.trilead.ssh2.Connection;
/**
* ClientServerHello.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ClientServerHello.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class ClientServerHello
{
String server_line;
String client_line;
String server_versioncomment;
public final static int readLineRN(InputStream is, byte[] buffer) throws IOException
{
int pos = 0;
boolean need10 = false;
int len = 0;
while (true)
{
int c = is.read();
if (c == -1)
throw new IOException("Premature connection close");
buffer[pos++] = (byte) c;
if (c == 13)
{
need10 = true;
continue;
}
if (c == 10)
break;
if (need10 == true)
throw new IOException("Malformed line sent by the server, the line does not end correctly.");
len++;
if (pos >= buffer.length)
throw new IOException("The server sent a too long line.");
}
return len;
}
public ClientServerHello(InputStream bi, OutputStream bo) throws IOException
{
client_line = "SSH-2.0-" + Connection.identification;
bo.write((client_line + "\r\n").getBytes("ISO-8859-1"));
bo.flush();
byte[] serverVersion = new byte[512];
for (int i = 0; i < 50; i++)
{
int len = readLineRN(bi, serverVersion);
server_line = new String(serverVersion, 0, len, "ISO-8859-1");
if (server_line.startsWith("SSH-"))
break;
}
if (server_line.startsWith("SSH-") == false)
throw new IOException(
"Malformed server identification string. There was no line starting with 'SSH-' amongst the first 50 lines.");
if (server_line.startsWith("SSH-1.99-"))
server_versioncomment = server_line.substring(9);
else if (server_line.startsWith("SSH-2.0-"))
server_versioncomment = server_line.substring(8);
else
throw new IOException("Server uses incompatible protocol, it is not SSH-2 compatible.");
}
/**
* @return Returns the client_versioncomment.
*/
public byte[] getClientString()
{
byte[] result;
try
{
result = client_line.getBytes("ISO-8859-1");
}
catch (UnsupportedEncodingException ign)
{
result = client_line.getBytes();
}
return result;
}
/**
* @return Returns the server_versioncomment.
*/
public byte[] getServerString()
{
byte[] result;
try
{
result = server_line.getBytes("ISO-8859-1");
}
catch (UnsupportedEncodingException ign)
{
result = server_line.getBytes();
}
return result;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/ClientServerHello.java | Java | asf20 | 2,740 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import com.trilead.ssh2.compression.ICompressor;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.cipher.CipherInputStream;
import com.trilead.ssh2.crypto.cipher.CipherOutputStream;
import com.trilead.ssh2.crypto.cipher.NullCipher;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.Packets;
/**
* TransportConnection.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TransportConnection.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class TransportConnection
{
private static final Logger log = Logger.getLogger(TransportConnection.class);
int send_seq_number = 0;
int recv_seq_number = 0;
CipherInputStream cis;
CipherOutputStream cos;
boolean useRandomPadding = false;
/* Depends on current MAC and CIPHER */
MAC send_mac;
byte[] send_mac_buffer;
int send_padd_blocksize = 8;
MAC recv_mac;
byte[] recv_mac_buffer;
byte[] recv_mac_buffer_cmp;
int recv_padd_blocksize = 8;
ICompressor recv_comp = null;
ICompressor send_comp = null;
boolean can_recv_compress = false;
boolean can_send_compress = false;
byte[] recv_comp_buffer;
byte[] send_comp_buffer;
/* won't change */
final byte[] send_padding_buffer = new byte[256];
final byte[] send_packet_header_buffer = new byte[5];
final byte[] recv_padding_buffer = new byte[256];
final byte[] recv_packet_header_buffer = new byte[5];
boolean recv_packet_header_present = false;
ClientServerHello csh;
final SecureRandom rnd;
public TransportConnection(InputStream is, OutputStream os, SecureRandom rnd)
{
this.cis = new CipherInputStream(new NullCipher(), is);
this.cos = new CipherOutputStream(new NullCipher(), os);
this.rnd = rnd;
}
public void changeRecvCipher(BlockCipher bc, MAC mac)
{
cis.changeCipher(bc);
recv_mac = mac;
recv_mac_buffer = (mac != null) ? new byte[mac.size()] : null;
recv_mac_buffer_cmp = (mac != null) ? new byte[mac.size()] : null;
recv_padd_blocksize = bc.getBlockSize();
if (recv_padd_blocksize < 8)
recv_padd_blocksize = 8;
}
public void changeSendCipher(BlockCipher bc, MAC mac)
{
if ((bc instanceof NullCipher) == false)
{
/* Only use zero byte padding for the first few packets */
useRandomPadding = true;
/* Once we start encrypting, there is no way back */
}
cos.changeCipher(bc);
send_mac = mac;
send_mac_buffer = (mac != null) ? new byte[mac.size()] : null;
send_padd_blocksize = bc.getBlockSize();
if (send_padd_blocksize < 8)
send_padd_blocksize = 8;
}
public void changeRecvCompression(ICompressor comp)
{
recv_comp = comp;
if (comp != null) {
recv_comp_buffer = new byte[comp.getBufferSize()];
can_recv_compress |= recv_comp.canCompressPreauth();
}
}
public void changeSendCompression(ICompressor comp)
{
send_comp = comp;
if (comp != null) {
send_comp_buffer = new byte[comp.getBufferSize()];
can_send_compress |= send_comp.canCompressPreauth();
}
}
public void sendMessage(byte[] message) throws IOException
{
sendMessage(message, 0, message.length, 0);
}
public void sendMessage(byte[] message, int off, int len) throws IOException
{
sendMessage(message, off, len, 0);
}
public int getPacketOverheadEstimate()
{
// return an estimate for the paket overhead (for send operations)
return 5 + 4 + (send_padd_blocksize - 1) + send_mac_buffer.length;
}
public void sendMessage(byte[] message, int off, int len, int padd) throws IOException
{
if (padd < 4)
padd = 4;
else if (padd > 64)
padd = 64;
if (send_comp != null && can_send_compress) {
if (send_comp_buffer.length < message.length + 1024)
send_comp_buffer = new byte[message.length + 1024];
len = send_comp.compress(message, off, len, send_comp_buffer);
message = send_comp_buffer;
}
int packet_len = 5 + len + padd; /* Minimum allowed padding is 4 */
int slack = packet_len % send_padd_blocksize;
if (slack != 0)
{
packet_len += (send_padd_blocksize - slack);
}
if (packet_len < 16)
packet_len = 16;
int padd_len = packet_len - (5 + len);
if (useRandomPadding)
{
for (int i = 0; i < padd_len; i = i + 4)
{
/*
* don't waste calls to rnd.nextInt() (by using only 8bit of the
* output). just believe me: even though we may write here up to 3
* bytes which won't be used, there is no "buffer overflow" (i.e.,
* arrayindexoutofbounds). the padding buffer is big enough =) (256
* bytes, and that is bigger than any current cipher block size + 64).
*/
int r = rnd.nextInt();
send_padding_buffer[i] = (byte) r;
send_padding_buffer[i + 1] = (byte) (r >> 8);
send_padding_buffer[i + 2] = (byte) (r >> 16);
send_padding_buffer[i + 3] = (byte) (r >> 24);
}
}
else
{
/* use zero padding for unencrypted traffic */
for (int i = 0; i < padd_len; i++)
send_padding_buffer[i] = 0;
/* Actually this code is paranoid: we never filled any
* bytes into the padding buffer so far, therefore it should
* consist of zeros only.
*/
}
send_packet_header_buffer[0] = (byte) ((packet_len - 4) >> 24);
send_packet_header_buffer[1] = (byte) ((packet_len - 4) >> 16);
send_packet_header_buffer[2] = (byte) ((packet_len - 4) >> 8);
send_packet_header_buffer[3] = (byte) ((packet_len - 4));
send_packet_header_buffer[4] = (byte) padd_len;
cos.write(send_packet_header_buffer, 0, 5);
cos.write(message, off, len);
cos.write(send_padding_buffer, 0, padd_len);
if (send_mac != null)
{
send_mac.initMac(send_seq_number);
send_mac.update(send_packet_header_buffer, 0, 5);
send_mac.update(message, off, len);
send_mac.update(send_padding_buffer, 0, padd_len);
send_mac.getMac(send_mac_buffer, 0);
cos.writePlain(send_mac_buffer, 0, send_mac_buffer.length);
}
cos.flush();
if (log.isEnabled())
{
log.log(90, "Sent " + Packets.getMessageName(message[off] & 0xff) + " " + len + " bytes payload");
}
send_seq_number++;
}
public int peekNextMessageLength() throws IOException
{
if (recv_packet_header_present == false)
{
cis.read(recv_packet_header_buffer, 0, 5);
recv_packet_header_present = true;
}
int packet_length = ((recv_packet_header_buffer[0] & 0xff) << 24)
| ((recv_packet_header_buffer[1] & 0xff) << 16) | ((recv_packet_header_buffer[2] & 0xff) << 8)
| ((recv_packet_header_buffer[3] & 0xff));
int padding_length = recv_packet_header_buffer[4] & 0xff;
if (packet_length > 35000 || packet_length < 12)
throw new IOException("Illegal packet size! (" + packet_length + ")");
int payload_length = packet_length - padding_length - 1;
if (payload_length < 0)
throw new IOException("Illegal padding_length in packet from remote (" + padding_length + ")");
return payload_length;
}
public int receiveMessage(byte buffer[], int off, int len) throws IOException
{
if (recv_packet_header_present == false)
{
cis.read(recv_packet_header_buffer, 0, 5);
}
else
recv_packet_header_present = false;
int packet_length = ((recv_packet_header_buffer[0] & 0xff) << 24)
| ((recv_packet_header_buffer[1] & 0xff) << 16) | ((recv_packet_header_buffer[2] & 0xff) << 8)
| ((recv_packet_header_buffer[3] & 0xff));
int padding_length = recv_packet_header_buffer[4] & 0xff;
if (packet_length > 35000 || packet_length < 12)
throw new IOException("Illegal packet size! (" + packet_length + ")");
int payload_length = packet_length - padding_length - 1;
if (payload_length < 0)
throw new IOException("Illegal padding_length in packet from remote (" + padding_length + ")");
if (payload_length >= len)
throw new IOException("Receive buffer too small (" + len + ", need " + payload_length + ")");
cis.read(buffer, off, payload_length);
cis.read(recv_padding_buffer, 0, padding_length);
if (recv_mac != null)
{
cis.readPlain(recv_mac_buffer, 0, recv_mac_buffer.length);
recv_mac.initMac(recv_seq_number);
recv_mac.update(recv_packet_header_buffer, 0, 5);
recv_mac.update(buffer, off, payload_length);
recv_mac.update(recv_padding_buffer, 0, padding_length);
recv_mac.getMac(recv_mac_buffer_cmp, 0);
for (int i = 0; i < recv_mac_buffer.length; i++)
{
if (recv_mac_buffer[i] != recv_mac_buffer_cmp[i])
throw new IOException("Remote sent corrupt MAC.");
}
}
recv_seq_number++;
if (log.isEnabled())
{
log.log(90, "Received " + Packets.getMessageName(buffer[off] & 0xff) + " " + payload_length
+ " bytes payload");
}
if (recv_comp != null && can_recv_compress) {
int[] uncomp_len = new int[] { payload_length };
buffer = recv_comp.uncompress(buffer, off, uncomp_len);
if (buffer == null) {
throw new IOException("Error while inflating remote data");
} else {
return uncomp_len[0];
}
} else {
return payload_length;
}
}
/**
*
*/
public void startCompression() {
can_recv_compress = true;
can_send_compress = true;
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/TransportConnection.java | Java | asf20 | 9,543 |
package com.trilead.ssh2.transport;
/**
* NegotiatedParameters.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: NegotiatedParameters.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class NegotiatedParameters
{
public boolean guessOK;
public String kex_algo;
public String server_host_key_algo;
public String enc_algo_client_to_server;
public String enc_algo_server_to_client;
public String mac_algo_client_to_server;
public String mac_algo_server_to_client;
public String comp_algo_client_to_server;
public String comp_algo_server_to_client;
public String lang_client_to_server;
public String lang_server_to_client;
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/NegotiatedParameters.java | Java | asf20 | 687 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.security.SecureRandom;
import com.trilead.ssh2.ConnectionInfo;
import com.trilead.ssh2.DHGexParameters;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.compression.CompressionFactory;
import com.trilead.ssh2.compression.ICompressor;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.crypto.KeyMaterial;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.cipher.BlockCipherFactory;
import com.trilead.ssh2.crypto.dh.DhExchange;
import com.trilead.ssh2.crypto.dh.DhGroupExchange;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketKexDHInit;
import com.trilead.ssh2.packets.PacketKexDHReply;
import com.trilead.ssh2.packets.PacketKexDhGexGroup;
import com.trilead.ssh2.packets.PacketKexDhGexInit;
import com.trilead.ssh2.packets.PacketKexDhGexReply;
import com.trilead.ssh2.packets.PacketKexDhGexRequest;
import com.trilead.ssh2.packets.PacketKexDhGexRequestOld;
import com.trilead.ssh2.packets.PacketKexInit;
import com.trilead.ssh2.packets.PacketNewKeys;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.signature.DSAPublicKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.DSASignature;
import com.trilead.ssh2.signature.RSAPublicKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
import com.trilead.ssh2.signature.RSASignature;
/**
* KexManager.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KexManager.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class KexManager
{
private static final Logger log = Logger.getLogger(KexManager.class);
KexState kxs;
int kexCount = 0;
KeyMaterial km;
byte[] sessionId;
ClientServerHello csh;
final Object accessLock = new Object();
ConnectionInfo lastConnInfo = null;
boolean connectionClosed = false;
boolean ignore_next_kex_packet = false;
final TransportManager tm;
CryptoWishList nextKEXcryptoWishList;
DHGexParameters nextKEXdhgexParameters;
ServerHostKeyVerifier verifier;
final String hostname;
final int port;
final SecureRandom rnd;
public KexManager(TransportManager tm, ClientServerHello csh, CryptoWishList initialCwl, String hostname, int port,
ServerHostKeyVerifier keyVerifier, SecureRandom rnd)
{
this.tm = tm;
this.csh = csh;
this.nextKEXcryptoWishList = initialCwl;
this.nextKEXdhgexParameters = new DHGexParameters();
this.hostname = hostname;
this.port = port;
this.verifier = keyVerifier;
this.rnd = rnd;
}
public ConnectionInfo getOrWaitForConnectionInfo(int minKexCount) throws IOException
{
synchronized (accessLock)
{
while (true)
{
if ((lastConnInfo != null) && (lastConnInfo.keyExchangeCounter >= minKexCount))
return lastConnInfo;
if (connectionClosed)
throw (IOException) new IOException("Key exchange was not finished, connection is closed.")
.initCause(tm.getReasonClosedCause());
try
{
accessLock.wait();
}
catch (InterruptedException e)
{
}
}
}
}
private String getFirstMatch(String[] client, String[] server) throws NegotiateException
{
if (client == null || server == null)
throw new IllegalArgumentException();
if (client.length == 0)
return null;
for (int i = 0; i < client.length; i++)
{
for (int j = 0; j < server.length; j++)
{
if (client[i].equals(server[j]))
return client[i];
}
}
throw new NegotiateException();
}
private boolean compareFirstOfNameList(String[] a, String[] b)
{
if (a == null || b == null)
throw new IllegalArgumentException();
if ((a.length == 0) && (b.length == 0))
return true;
if ((a.length == 0) || (b.length == 0))
return false;
return (a[0].equals(b[0]));
}
private boolean isGuessOK(KexParameters cpar, KexParameters spar)
{
if (cpar == null || spar == null)
throw new IllegalArgumentException();
if (compareFirstOfNameList(cpar.kex_algorithms, spar.kex_algorithms) == false)
{
return false;
}
if (compareFirstOfNameList(cpar.server_host_key_algorithms, spar.server_host_key_algorithms) == false)
{
return false;
}
/*
* We do NOT check here if the other algorithms can be agreed on, this
* is just a check if kex_algorithms and server_host_key_algorithms were
* guessed right!
*/
return true;
}
private NegotiatedParameters mergeKexParameters(KexParameters client, KexParameters server)
{
NegotiatedParameters np = new NegotiatedParameters();
try
{
np.kex_algo = getFirstMatch(client.kex_algorithms, server.kex_algorithms);
log.log(20, "kex_algo=" + np.kex_algo);
np.server_host_key_algo = getFirstMatch(client.server_host_key_algorithms,
server.server_host_key_algorithms);
log.log(20, "server_host_key_algo=" + np.server_host_key_algo);
np.enc_algo_client_to_server = getFirstMatch(client.encryption_algorithms_client_to_server,
server.encryption_algorithms_client_to_server);
np.enc_algo_server_to_client = getFirstMatch(client.encryption_algorithms_server_to_client,
server.encryption_algorithms_server_to_client);
log.log(20, "enc_algo_client_to_server=" + np.enc_algo_client_to_server);
log.log(20, "enc_algo_server_to_client=" + np.enc_algo_server_to_client);
np.mac_algo_client_to_server = getFirstMatch(client.mac_algorithms_client_to_server,
server.mac_algorithms_client_to_server);
np.mac_algo_server_to_client = getFirstMatch(client.mac_algorithms_server_to_client,
server.mac_algorithms_server_to_client);
log.log(20, "mac_algo_client_to_server=" + np.mac_algo_client_to_server);
log.log(20, "mac_algo_server_to_client=" + np.mac_algo_server_to_client);
np.comp_algo_client_to_server = getFirstMatch(client.compression_algorithms_client_to_server,
server.compression_algorithms_client_to_server);
np.comp_algo_server_to_client = getFirstMatch(client.compression_algorithms_server_to_client,
server.compression_algorithms_server_to_client);
log.log(20, "comp_algo_client_to_server=" + np.comp_algo_client_to_server);
log.log(20, "comp_algo_server_to_client=" + np.comp_algo_server_to_client);
}
catch (NegotiateException e)
{
return null;
}
try
{
np.lang_client_to_server = getFirstMatch(client.languages_client_to_server,
server.languages_client_to_server);
}
catch (NegotiateException e1)
{
np.lang_client_to_server = null;
}
try
{
np.lang_server_to_client = getFirstMatch(client.languages_server_to_client,
server.languages_server_to_client);
}
catch (NegotiateException e2)
{
np.lang_server_to_client = null;
}
if (isGuessOK(client, server))
np.guessOK = true;
return np;
}
public synchronized void initiateKEX(CryptoWishList cwl, DHGexParameters dhgex) throws IOException
{
nextKEXcryptoWishList = cwl;
nextKEXdhgexParameters = dhgex;
if (kxs == null)
{
kxs = new KexState();
kxs.dhgexParameters = nextKEXdhgexParameters;
PacketKexInit kp = new PacketKexInit(nextKEXcryptoWishList, rnd);
kxs.localKEX = kp;
tm.sendKexMessage(kp.getPayload());
}
}
private boolean establishKeyMaterial()
{
try
{
int mac_cs_key_len = MAC.getKeyLen(kxs.np.mac_algo_client_to_server);
int enc_cs_key_len = BlockCipherFactory.getKeySize(kxs.np.enc_algo_client_to_server);
int enc_cs_block_len = BlockCipherFactory.getBlockSize(kxs.np.enc_algo_client_to_server);
int mac_sc_key_len = MAC.getKeyLen(kxs.np.mac_algo_server_to_client);
int enc_sc_key_len = BlockCipherFactory.getKeySize(kxs.np.enc_algo_server_to_client);
int enc_sc_block_len = BlockCipherFactory.getBlockSize(kxs.np.enc_algo_server_to_client);
km = KeyMaterial.create("SHA1", kxs.H, kxs.K, sessionId, enc_cs_key_len, enc_cs_block_len, mac_cs_key_len,
enc_sc_key_len, enc_sc_block_len, mac_sc_key_len);
}
catch (IllegalArgumentException e)
{
return false;
}
return true;
}
private void finishKex() throws IOException
{
if (sessionId == null)
sessionId = kxs.H;
establishKeyMaterial();
/* Tell the other side that we start using the new material */
PacketNewKeys ign = new PacketNewKeys();
tm.sendKexMessage(ign.getPayload());
BlockCipher cbc;
MAC mac;
ICompressor comp;
try
{
cbc = BlockCipherFactory.createCipher(kxs.np.enc_algo_client_to_server, true, km.enc_key_client_to_server,
km.initial_iv_client_to_server);
mac = new MAC(kxs.np.mac_algo_client_to_server, km.integrity_key_client_to_server);
comp = CompressionFactory.createCompressor(kxs.np.comp_algo_client_to_server);
}
catch (IllegalArgumentException e1)
{
throw new IOException("Fatal error during MAC startup!");
}
tm.changeSendCipher(cbc, mac);
tm.changeSendCompression(comp);
tm.kexFinished();
}
public static final String[] getDefaultServerHostkeyAlgorithmList()
{
return new String[] { "ssh-rsa", "ssh-dss" };
}
public static final void checkServerHostkeyAlgorithmsList(String[] algos)
{
for (int i = 0; i < algos.length; i++)
{
if (("ssh-rsa".equals(algos[i]) == false) && ("ssh-dss".equals(algos[i]) == false))
throw new IllegalArgumentException("Unknown server host key algorithm '" + algos[i] + "'");
}
}
public static final String[] getDefaultKexAlgorithmList()
{
return new String[] { "diffie-hellman-group-exchange-sha1", "diffie-hellman-group14-sha1",
"diffie-hellman-group1-sha1" };
}
public static final void checkKexAlgorithmList(String[] algos)
{
for (int i = 0; i < algos.length; i++)
{
if ("diffie-hellman-group-exchange-sha1".equals(algos[i]))
continue;
if ("diffie-hellman-group14-sha1".equals(algos[i]))
continue;
if ("diffie-hellman-group1-sha1".equals(algos[i]))
continue;
throw new IllegalArgumentException("Unknown kex algorithm '" + algos[i] + "'");
}
}
private boolean verifySignature(byte[] sig, byte[] hostkey) throws IOException
{
if (kxs.np.server_host_key_algo.equals("ssh-rsa"))
{
RSASignature rs = RSASHA1Verify.decodeSSHRSASignature(sig);
RSAPublicKey rpk = RSASHA1Verify.decodeSSHRSAPublicKey(hostkey);
log.log(50, "Verifying ssh-rsa signature");
return RSASHA1Verify.verifySignature(kxs.H, rs, rpk);
}
if (kxs.np.server_host_key_algo.equals("ssh-dss"))
{
DSASignature ds = DSASHA1Verify.decodeSSHDSASignature(sig);
DSAPublicKey dpk = DSASHA1Verify.decodeSSHDSAPublicKey(hostkey);
log.log(50, "Verifying ssh-dss signature");
return DSASHA1Verify.verifySignature(kxs.H, ds, dpk);
}
throw new IOException("Unknown server host key algorithm '" + kxs.np.server_host_key_algo + "'");
}
public synchronized void handleMessage(byte[] msg, int msglen) throws IOException
{
PacketKexInit kip;
if (msg == null)
{
synchronized (accessLock)
{
connectionClosed = true;
accessLock.notifyAll();
return;
}
}
if ((kxs == null) && (msg[0] != Packets.SSH_MSG_KEXINIT))
throw new IOException("Unexpected KEX message (type " + msg[0] + ")");
if (ignore_next_kex_packet)
{
ignore_next_kex_packet = false;
return;
}
if (msg[0] == Packets.SSH_MSG_KEXINIT)
{
if ((kxs != null) && (kxs.state != 0))
throw new IOException("Unexpected SSH_MSG_KEXINIT message during on-going kex exchange!");
if (kxs == null)
{
/*
* Ah, OK, peer wants to do KEX. Let's be nice and play
* together.
*/
kxs = new KexState();
kxs.dhgexParameters = nextKEXdhgexParameters;
kip = new PacketKexInit(nextKEXcryptoWishList, rnd);
kxs.localKEX = kip;
tm.sendKexMessage(kip.getPayload());
}
kip = new PacketKexInit(msg, 0, msglen);
kxs.remoteKEX = kip;
kxs.np = mergeKexParameters(kxs.localKEX.getKexParameters(), kxs.remoteKEX.getKexParameters());
if (kxs.np == null)
throw new IOException("Cannot negotiate, proposals do not match.");
if (kxs.remoteKEX.isFirst_kex_packet_follows() && (kxs.np.guessOK == false))
{
/*
* Guess was wrong, we need to ignore the next kex packet.
*/
ignore_next_kex_packet = true;
}
if (kxs.np.kex_algo.equals("diffie-hellman-group-exchange-sha1"))
{
if (kxs.dhgexParameters.getMin_group_len() == 0 || csh.server_versioncomment.matches("OpenSSH_2\\.([0-4]\\.|5\\.[0-2]).*"))
{
PacketKexDhGexRequestOld dhgexreq = new PacketKexDhGexRequestOld(kxs.dhgexParameters);
tm.sendKexMessage(dhgexreq.getPayload());
}
else
{
PacketKexDhGexRequest dhgexreq = new PacketKexDhGexRequest(kxs.dhgexParameters);
tm.sendKexMessage(dhgexreq.getPayload());
}
kxs.state = 1;
return;
}
if (kxs.np.kex_algo.equals("diffie-hellman-group1-sha1")
|| kxs.np.kex_algo.equals("diffie-hellman-group14-sha1"))
{
kxs.dhx = new DhExchange();
if (kxs.np.kex_algo.equals("diffie-hellman-group1-sha1"))
kxs.dhx.init(1, rnd);
else
kxs.dhx.init(14, rnd);
PacketKexDHInit kp = new PacketKexDHInit(kxs.dhx.getE());
tm.sendKexMessage(kp.getPayload());
kxs.state = 1;
return;
}
throw new IllegalStateException("Unkown KEX method!");
}
if (msg[0] == Packets.SSH_MSG_NEWKEYS)
{
if (km == null)
throw new IOException("Peer sent SSH_MSG_NEWKEYS, but I have no key material ready!");
BlockCipher cbc;
MAC mac;
ICompressor comp;
try
{
cbc = BlockCipherFactory.createCipher(kxs.np.enc_algo_server_to_client, false,
km.enc_key_server_to_client, km.initial_iv_server_to_client);
mac = new MAC(kxs.np.mac_algo_server_to_client, km.integrity_key_server_to_client);
comp = CompressionFactory.createCompressor(kxs.np.comp_algo_server_to_client);
}
catch (IllegalArgumentException e1)
{
throw new IOException("Fatal error during MAC startup!");
}
tm.changeRecvCipher(cbc, mac);
tm.changeRecvCompression(comp);
ConnectionInfo sci = new ConnectionInfo();
kexCount++;
sci.keyExchangeAlgorithm = kxs.np.kex_algo;
sci.keyExchangeCounter = kexCount;
sci.clientToServerCryptoAlgorithm = kxs.np.enc_algo_client_to_server;
sci.serverToClientCryptoAlgorithm = kxs.np.enc_algo_server_to_client;
sci.clientToServerMACAlgorithm = kxs.np.mac_algo_client_to_server;
sci.serverToClientMACAlgorithm = kxs.np.mac_algo_server_to_client;
sci.serverHostKeyAlgorithm = kxs.np.server_host_key_algo;
sci.serverHostKey = kxs.hostkey;
synchronized (accessLock)
{
lastConnInfo = sci;
accessLock.notifyAll();
}
kxs = null;
return;
}
if ((kxs == null) || (kxs.state == 0))
throw new IOException("Unexpected Kex submessage!");
if (kxs.np.kex_algo.equals("diffie-hellman-group-exchange-sha1"))
{
if (kxs.state == 1)
{
PacketKexDhGexGroup dhgexgrp = new PacketKexDhGexGroup(msg, 0, msglen);
kxs.dhgx = new DhGroupExchange(dhgexgrp.getP(), dhgexgrp.getG());
kxs.dhgx.init(rnd);
PacketKexDhGexInit dhgexinit = new PacketKexDhGexInit(kxs.dhgx.getE());
tm.sendKexMessage(dhgexinit.getPayload());
kxs.state = 2;
return;
}
if (kxs.state == 2)
{
PacketKexDhGexReply dhgexrpl = new PacketKexDhGexReply(msg, 0, msglen);
kxs.hostkey = dhgexrpl.getHostKey();
if (verifier != null)
{
boolean vres = false;
try
{
vres = verifier.verifyServerHostKey(hostname, port, kxs.np.server_host_key_algo, kxs.hostkey);
}
catch (Exception e)
{
throw (IOException) new IOException(
"The server hostkey was not accepted by the verifier callback.").initCause(e);
}
if (vres == false)
throw new IOException("The server hostkey was not accepted by the verifier callback");
}
kxs.dhgx.setF(dhgexrpl.getF());
try
{
kxs.H = kxs.dhgx.calculateH(csh.getClientString(), csh.getServerString(),
kxs.localKEX.getPayload(), kxs.remoteKEX.getPayload(), dhgexrpl.getHostKey(),
kxs.dhgexParameters);
}
catch (IllegalArgumentException e)
{
throw (IOException) new IOException("KEX error.").initCause(e);
}
boolean res = verifySignature(dhgexrpl.getSignature(), kxs.hostkey);
if (res == false)
throw new IOException("Hostkey signature sent by remote is wrong!");
kxs.K = kxs.dhgx.getK();
finishKex();
kxs.state = -1;
return;
}
throw new IllegalStateException("Illegal State in KEX Exchange!");
}
if (kxs.np.kex_algo.equals("diffie-hellman-group1-sha1")
|| kxs.np.kex_algo.equals("diffie-hellman-group14-sha1"))
{
if (kxs.state == 1)
{
PacketKexDHReply dhr = new PacketKexDHReply(msg, 0, msglen);
kxs.hostkey = dhr.getHostKey();
if (verifier != null)
{
boolean vres = false;
try
{
vres = verifier.verifyServerHostKey(hostname, port, kxs.np.server_host_key_algo, kxs.hostkey);
}
catch (Exception e)
{
throw (IOException) new IOException(
"The server hostkey was not accepted by the verifier callback.").initCause(e);
}
if (vres == false)
throw new IOException("The server hostkey was not accepted by the verifier callback");
}
kxs.dhx.setF(dhr.getF());
try
{
kxs.H = kxs.dhx.calculateH(csh.getClientString(), csh.getServerString(), kxs.localKEX.getPayload(),
kxs.remoteKEX.getPayload(), dhr.getHostKey());
}
catch (IllegalArgumentException e)
{
throw (IOException) new IOException("KEX error.").initCause(e);
}
boolean res = verifySignature(dhr.getSignature(), kxs.hostkey);
if (res == false)
throw new IOException("Hostkey signature sent by remote is wrong!");
kxs.K = kxs.dhx.getK();
finishKex();
kxs.state = -1;
return;
}
}
throw new IllegalStateException("Unkown KEX method! (" + kxs.np.kex_algo + ")");
}
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/KexManager.java | Java | asf20 | 18,503 |
package com.trilead.ssh2.transport;
/**
* KexParameters.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KexParameters.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class KexParameters
{
public byte[] cookie;
public String[] kex_algorithms;
public String[] server_host_key_algorithms;
public String[] encryption_algorithms_client_to_server;
public String[] encryption_algorithms_server_to_client;
public String[] mac_algorithms_client_to_server;
public String[] mac_algorithms_server_to_client;
public String[] compression_algorithms_client_to_server;
public String[] compression_algorithms_server_to_client;
public String[] languages_client_to_server;
public String[] languages_server_to_client;
public boolean first_kex_packet_follows;
public int reserved_field1;
}
| 1030365071-xuechao | src/com/trilead/ssh2/transport/KexParameters.java | Java | asf20 | 843 |