com.enterprisedt.net.ftp.ssl
Class SSLFTPClient

java.lang.Object
  extended by com.enterprisedt.net.ftp.FTPClient
      extended by com.enterprisedt.net.ftp.pro.ProFTPClient
          extended by com.enterprisedt.net.ftp.ssl.SSLFTPClient
All Implemented Interfaces:
FTPClientInterface, ProFTPClientInterface

public class SSLFTPClient
extends ProFTPClient
implements ProFTPClientInterface

SSLFTPClient supports standard FTP and the two types of FTPS, explicit and implicit.

Explicit FTPS is specified by the Internet Draft, "Securing FTP with TLS", Ford-Hutchinson, et al. As directed by the draft, the FTP client connects in plain (non-SSL) mode and operates in this mode until the "AUTH" command is issued by means of the auth(String) method. This will cause the client and server to negotiate an SSL connection. Once complete commands sent from the client to the server, and their corresponding replies will be secure. Below is an example of a simple explicit FTPS session:

   // create an explicit FTPS client
   SSLFTPClient ftp = new SSLFTPClient("123.123.123.123", 0);

   // Turn off server validation (ONLY do this when testing)
   ftp.setValidateServer(false);
 
   // connect to the server
   ftp.connect();                        

   // switch to secure command channel
   ftp.auth(SSLFTPClient.AUTH_SSL);

   // log in
   ftp.login("test", "test");

   // get a file
   ftp.get("file.txt", "file.txt");

   // close the connection
   ftp.quit();
 
This example uses no client authentication and does not attempt to verify server certificates (which should be done only when testing).

Implicit FTPS is an older form of FTPS which uses pure SSL connection, i.e. SSL sessions are established immediately upon socket connection for all FTP channels. The following is an example of a simple implicit FTPS session:

   // create an implicit FTPS client
   SSLFTPClient ftp = new SSLFTPClient("123.123.123.123", SSLFTPClient.ConfigFlags.IMPLICIT_FTPS);

   // Turn off server validation (ONLY do this when testing)
   ftp.setValidateServer(false);
 
   // connect to the server
   ftp.connect();                        

   // log in
   ftp.login("test", "test");

   // get a file
   ftp.get("file.txt", "file.txt");

   // close the connection
   ftp.quit();
 
Like the previous example, this example uses no client authentication and does not attempt to verify server certificates (which should be done only when testing).

SSL Certificates: Both the examples above used no server validation. This is only normally acceptable only when testing. To be secure applications should always validate the server that they're communicating with. If setValidateServer() is not called then SSLFTPClient will attempt to validate the server's certificate. In explicit FTPS this occurs when the auth(String) method is invoked, whereas in implicit FTPS, it occurs upon connection.

The server's certificate is matched against the root certificates in the root certificate-store (accessible via getRootCertificateStore(). Some server certificates are issued by Certificate Authorities (CAs). In such cases, it is sufficient for the CA's certificate to be in the root certicate file. If a non-CA certificate is used then the server certificate itself must be in root certificate file.

If client authentication is required then a user's private key and certificate must be set using the loadClientCertificate(String,String), loadClientCertificate(InputStream,String) or setClientCertificate(Certificate,PrivateKey) methods.

Configuration flags:There are variations in the interpretation of the FTPS standard as implemented in various servers. For this reason non-standard compatibility options may activated by passing ConfigFlags to the SSLFTPClient constructor. For example, to communicate with a GlobalSCAPE (tm) server, the following code would be used:

   SSLFTPClient ftp = new SSLFTPClient("123.123.123.123",
                                       SSLFTPClient.ConfigFlags.DISABLE_SSL_CLOSURE
                                       | SSLFTPClient.ConfigFlags.DISABLE_WAIT_ON_CLOSURE);
 

Cipher-Suites: A cipher-suite is a set of algorithms that is used for various aspects of SSL security. For a client and a server to be able to communicate, they must be able to agree on a particular cipher-suite. Different types of servers recognize different cipher-suites, so it is usually up to the client make sure that it shares at least one cipher-suite with the server that it is trying to communicate securely with. By itself, this fact would imply that the client should simply enable all possible suites in order to increase the chances of overlap. However, this is not necessarily wise since some cipher-suites (esp. those which adhered to the (now defunct) US export restrictions are relatively easy to break, whereas some others are trusted as currently being virtually unbreakable.

This library supports many cipher-suites (see SSLFTPCipherSuite) so it should be possible to find a suitable cipher-suite in most cases. Cipher-suites are configured on the client using the disableAllCipherSuites(), enableCipherSuite(SSLFTPCipherSuite), and getEnabledCipherSuites() methods.

(Note: GlobalSCAPE is a registered trademark of GlobalSCAPE)

Version:
$Revision: 1.50 $
Author:
Hans Andersen

Nested Class Summary
static class SSLFTPClient.ConfigFlags
          ConfigFlags contains various static integers which are used to configure clients.
 
Field Summary
static java.lang.String AUTH_SSL
          Deprecated - use AUTH_TLS.
static java.lang.String AUTH_TLS
          Synonym for AUTH_TLS_C.
static java.lang.String AUTH_TLS_C
          May be passed to the auth(String) method to ask for SSL negotiation without implicitly protecting the data connection.
static char PROT_CLEAR
          May be passed to the prot(char) method to specify that data-transfers should be done WITHOUT security.
static char PROT_PRIVATE
          May be passed to the prot(char) method to specify that data-transfers should be done WITH security.
 
Fields inherited from class com.enterprisedt.net.ftp.pro.ProFTPClient
cvsId
 
Fields inherited from class com.enterprisedt.net.ftp.FTPClient
CARRIAGE_RETURN, control, controlEncoding, controlPort, data, DEFAULT_BUFFER_SIZE, DEFAULT_ENCODING, DEFAULT_LISTING_LOCALES, DEFAULT_MONITOR_INTERVAL, DEFAULT_TIMEOUT, dirEmptyStrings, fileNotFoundStrings, FTP_LINE_SEPARATOR, id, lastReply, lastValidReply, LINE_FEED, messageListener, monitor, monitorEx, monitorInterval, remoteAddr, remoteHost, serverWakeupInterval, timeout, transferBufferSize, transferCompleteStrings, transferType
 
Fields inherited from interface com.enterprisedt.net.ftp.pro.ProFTPClientInterface
cvsId
 
Constructor Summary
SSLFTPClient()
          Constructs an FTPS client for the given remote host.
SSLFTPClient(java.net.InetAddress remoteAddr, int configFlags)
          Deprecated. use setter methods to set properties
SSLFTPClient(java.net.InetAddress remoteAddr, int controlPort, int configFlags)
          Deprecated. use setter methods to set properties
SSLFTPClient(java.net.InetAddress remoteAddr, int controlPort, int timeout, int configFlags)
          Deprecated. use setter methods to set properties
SSLFTPClient(java.lang.String remoteHost, int configFlags)
          Deprecated. use setter methods to set properties
SSLFTPClient(java.lang.String remoteHost, int controlPort, int configFlags)
          Deprecated. use setter methods to set properties
SSLFTPClient(java.lang.String remoteHost, int controlPort, int timeout, int configFlags)
          Deprecated. use setter methods to set properties
 
Method Summary
 void auth(char command)
          Required for certain implementations of implicit SSL.
 void auth(java.lang.String securityMechanism)
          Switches the control-channel (the connection which carries commands) to secure mode.
 void ccc()
          Clears the control channel, setting it back to plain text.
 void connect()
          Connects to the server at the address and port number defined in the constructor.
 void disableAllCipherSuites()
          Disables all cipher-suites.
 void enableCipherSuite(SSLFTPCipherSuite cipherSuite)
          Enables the given cipher-suite.
 void enableCipherSuites(SSLFTPCipherSuite[] cipherSuites)
          Enables the given cipher-suites.
 java.util.Vector getCertificateChain()
          Returns a vector containing the certificates (SSLFTPCertificate) presented by the server with the Certificate Authority's certificate first and the server's certificate last.
 int getConfigFlags()
          Get the set configuration flags.
 SSLFTPCipherSuite[] getEnabledCipherSuites()
          Returns an array of all currently enabled cipher-suites.
 SSLFTPCertificateStore getRootCertificateStore()
          Returns a reference to the SSLFTPCertificateStore which contains the root certificates that will be used to validate the server certificate.
static SSLFTPCertificate getServerCertificate(java.lang.String hostName)
          Connects to the given host and retrieves its certificate.
static SSLFTPCertificate getServerCertificate(java.lang.String hostName, int remotePort)
          Connects to the given host and retrieves its certificate.
static java.lang.String getServerSecurityMechanism(java.lang.String remoteHost)
          Returns the safest explicit FTPS security mechanism supported by the server.
static java.lang.String getServerSecurityMechanism(java.lang.String remoteHost, int remotePort)
          Returns the safest explicit FTPS security mechanism supported by the server.
 boolean getValidateServer()
          Returns a flag indicating whether or not this client will attempt to validate server certificates.
 boolean isImplicitFTPS()
          Is implicit FTPS being used?
 void loadClientCertificate(java.io.InputStream inputStream, java.lang.String password)
          Loads the client's private key and certificate in PEM format from the given input-stream.
 void loadClientCertificate(java.lang.String path, java.lang.String password)
          Loads the client's private key and certificate in PEM format from the given file.
 void loadClientKeyFile(java.io.InputStream inputStream, java.lang.String password)
          Deprecated. Use setClientCertificate<(inputStream, password)/code>.
 void loadClientKeyFile(java.lang.String path, java.lang.String password)
          Deprecated. Use loadClientCertificate<(path, password)/code>.
 void loadRootCertificates(java.io.InputStream inputStream)
          Deprecated. Use getRootCertificateStore().SSLFTPCertificateStore.importPEMFile(InputStream)
 void loadRootCertificates(java.lang.String path)
          Deprecated. Use getRootCertificateStore().SSLFTPCertificateStore.importPEMFile(String)
 void pbsz(int bufferSize)
          Defines the buffer-size to be used on data-connections.
 void prot(char command)
          Defines the security-level of subsequent data-transfers.
protected  int readChar(java.io.LineNumberReader in)
          Attempts to read a single character from the given InputStream.
 int readChunk(java.io.BufferedInputStream in, byte[] chunk, int chunksize)
          Attempts to read a specified number of bytes from the given InputStream and place it in the given byte-array.
protected  java.lang.String readLine(java.io.LineNumberReader in)
          Attempts to read a single line from the given InputStream.
 void setClientCertificate(java.security.cert.Certificate certificate, java.security.PrivateKey privateKey)
          Sets the client's certificate and private key given standard Java Certificate and PrivateKey objects.
 void setConfigFlags(int configFlags)
          Set the configuration flags which control various compatibility features.
 void setCustomValidator(SSLFTPValidator newValidator)
          Sets the validator.
 void setImplicitFTPS(boolean implicitFTPS)
          Set implicit FTPS on or off.
 void setRootCertificateStore(SSLFTPCertificateStore store)
          Sets the SSLFTPCertificateStore which contains the root certificates that will be used to validate the server certificate.
 void setValidateServer(boolean validate)
          Determines whether or not this client will attempt to validate server certificates.
 java.lang.String toString()
          String representation
 
Methods inherited from class com.enterprisedt.net.ftp.pro.ProFTPClient
getCountBeforeSleep, getSleepTime, isSleepEnabled, mdelete, mdelete, mdelete, mdelete, mget, mget, mget, mget, mput, mput, mput, mput, rmdir, setCountBeforeSleep, setSleepEnabled, setSleepTime
 
Methods inherited from class com.enterprisedt.net.ftp.FTPClient
abort, account, cancelResume, cancelTransfer, cdup, chdir, checkConnection, chooseTransferMode, clearSOCKS, closeDataSocket, closeDataSocket, connected, debugResponses, delete, dir, dir, dir, dirDetails, executeCommand, exists, features, fileDetails, forceResumeOff, get, get, get, getActiveHighPort, getActiveIPAddress, getActiveLowPort, getBuildTimestamp, getConnectMode, getControlEncoding, getControlPort, getDeleteCount, getDetectTransferMode, getDirectoryEmptyMessages, getDownloadCount, getFileNotFoundMessages, getId, getLastReply, getLastValidReply, getListenOnAllInterfaces, getMessageListener, getMonitorInterval, getProgressMonitor, getProgressMonitorEx, getRemoteAddr, getRemoteHost, getRemotePort, getServerWakeupInterval, getTimeout, getTransferBufferSize, getTransferCompleteMessages, getType, getUploadCount, getVersion, help, initGet, initialize, initPut, initSOCKS, initSOCKSAuthentication, isAutoPassiveIPSubstitution, isDeleteOnFailure, isStrictReturnCodes, isTransferCancelled, keepAlive, list, list, login, login, mkdir, modtime, noOperation, password, put, put, put, put, put, put, pwd, quit, quitImmediately, quote, quote, rename, resetDeleteCount, resetDownloadCount, resetTransferMode, resetUploadCount, restart, resume, rmdir, sendCommand, sendServerWakeup, setActiveIPAddress, setActivePortRange, setAutoPassiveIPSubstitution, setConnectMode, setControlEncoding, setControlPort, setDeleteOnFailure, setDetectTransferMode, setDirectoryEmptyMessages, setFileNotFoundMessages, setForceUniqueNames, setFTPFileFactory, setId, setListenOnAllInterfaces, setMessageListener, setModTime, setMonitorInterval, setParserLocale, setParserLocales, setPORTIP, setProgressMonitor, setProgressMonitor, setProgressMonitorEx, setRemoteAddr, setRemoteHost, setRemotePort, setServerWakeupInterval, setStrictReturnCodes, setTimeout, setTransferBufferSize, setTransferCompleteMessages, setType, setupDataSocket, site, size, stat, system, user, validateReply, validateReply, validateTransfer, validateTransferOnError
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface com.enterprisedt.net.ftp.pro.ProFTPClientInterface
getCountBeforeSleep, getSleepTime, isSleepEnabled, mdelete, mdelete, mdelete, mdelete, mget, mget, mget, mget, mput, mput, mput, mput, rmdir, setCountBeforeSleep, setSleepEnabled, setSleepTime
 
Methods inherited from interface com.enterprisedt.net.ftp.FTPClientInterface
cancelResume, cancelTransfer, cdup, chdir, connected, delete, dir, dir, dir, dirDetails, executeCommand, exists, get, get, get, getDeleteCount, getDetectTransferMode, getDownloadCount, getId, getMonitorInterval, getRemoteHost, getRemotePort, getTimeout, getType, getUploadCount, keepAlive, mkdir, modtime, put, put, put, put, put, put, pwd, quit, quitImmediately, rename, resetDeleteCount, resetDownloadCount, resetUploadCount, resume, rmdir, setControlEncoding, setDetectTransferMode, setId, setModTime, setProgressMonitor, setProgressMonitor, setRemoteHost, setRemotePort, setTimeout, setType, size, system
 

Field Detail

AUTH_TLS

public static final java.lang.String AUTH_TLS
Synonym for AUTH_TLS_C. May be passed to the auth(String) method to ask for SSL negotiation without implicitly protecting the data connection.

See Also:
Constant Field Values

AUTH_TLS_C

public static final java.lang.String AUTH_TLS_C
May be passed to the auth(String) method to ask for SSL negotiation without implicitly protecting the data connection.

See Also:
Constant Field Values

AUTH_SSL

public static final java.lang.String AUTH_SSL
Deprecated - use AUTH_TLS. May be passed to the auth(String) method to ask for SSL negotiation and implicitly protect further data connections.

See Also:
Constant Field Values

PROT_CLEAR

public static final char PROT_CLEAR
May be passed to the prot(char) method to specify that data-transfers should be done WITHOUT security.

See Also:
Constant Field Values

PROT_PRIVATE

public static final char PROT_PRIVATE
May be passed to the prot(char) method to specify that data-transfers should be done WITH security.

See Also:
Constant Field Values
Constructor Detail

SSLFTPClient

public SSLFTPClient()
             throws FTPException
Constructs an FTPS client for the given remote host.

IMPORTANT NOTE: This constructor does NOT connect to the server. The connect() method must be called to do this.

All other constructors are deprecated. This constructor should be used, and then setter methods used (most inherited from FTPClient) to set the control port, remote host etc

Throws:
FTPException

SSLFTPClient

public SSLFTPClient(java.lang.String remoteHost,
                    int configFlags)
             throws java.net.UnknownHostException
Deprecated. use setter methods to set properties

Constructs an FTPS client for the given remote host.

IMPORTANT NOTE: This constructor does NOT connect to the server. The connect() method must be called to do this.

Parameters:
remoteHost - Remote FTP server to connect to.
configFlags - Combination of flags used to configure the client for implicit FTPS or compatibility with servers that don't fully comply with standards (see SSLFTPClient.ConfigFlags). For servers that comply with standards this value may be set to 0.
Throws:
java.net.UnknownHostException - Thrown if the remoteHost argument does not resolved to a known host.

SSLFTPClient

public SSLFTPClient(java.lang.String remoteHost,
                    int controlPort,
                    int configFlags)
             throws java.net.UnknownHostException
Deprecated. use setter methods to set properties

Constructs an FTPS client for the given remote host.

IMPORTANT NOTE: This constructor does NOT connect to the server. The connect() method must be called to do this.

Parameters:
remoteHost - Remote FTP server to connect to.
controlPort - Port on remote FTP server to connect to.
configFlags - Combination of flags used to configure the client for implicit FTPS or compatibility with servers that don't fully comply with standards (see SSLFTPClient.ConfigFlags). For servers that comply with standards this value may be set to 0.
Throws:
java.net.UnknownHostException - Thrown if the remoteHost argument does not resolved to a known host.

SSLFTPClient

public SSLFTPClient(java.lang.String remoteHost,
                    int controlPort,
                    int timeout,
                    int configFlags)
             throws java.net.UnknownHostException
Deprecated. use setter methods to set properties

Constructs an FTPS client for the given remote host.

IMPORTANT NOTE: This constructor does NOT connect to the server. The connect() method must be called to do this.

Parameters:
remoteHost - Remote FTP server to connect to.
controlPort - Port on remote FTP server to connect to.
timeout - Time-out of connections (0 means no time-out).
configFlags - Combination of flags used to configure the client for implicit FTPS or compatibility with servers that don't fully comply with standards (see SSLFTPClient.ConfigFlags). For servers that comply with standards this value may be set to 0.
Throws:
java.net.UnknownHostException - Thrown if the remoteHost argument does not resolved to a known host.

SSLFTPClient

public SSLFTPClient(java.net.InetAddress remoteAddr,
                    int configFlags)
Deprecated. use setter methods to set properties

Constructs an FTPS client for the given remote host.

IMPORTANT NOTE: This constructor does NOT connect to the server. The connect() method must be called to do this.

Parameters:
remoteAddr - Address of remote FTP server to connect to.
configFlags - Combination of flags used to configure the client for implicit FTPS or compatibility with servers that don't fully comply with standards (see SSLFTPClient.ConfigFlags). For servers that comply with standards this value may be set to 0.

SSLFTPClient

public SSLFTPClient(java.net.InetAddress remoteAddr,
                    int controlPort,
                    int configFlags)
Deprecated. use setter methods to set properties

Constructs an FTPS client for the given remote host.

IMPORTANT NOTE: This constructor does NOT connect to the server. The connect() method must be called to do this.

Parameters:
remoteAddr - Address of remote FTP server to connect to.
controlPort - Port on remote FTP server to connect to.
configFlags - Combination of flags used to configure the client for implicit FTPS or compatibility with servers that don't fully comply with standards (see SSLFTPClient.ConfigFlags). For servers that comply with standards this value may be set to 0.

SSLFTPClient

public SSLFTPClient(java.net.InetAddress remoteAddr,
                    int controlPort,
                    int timeout,
                    int configFlags)
Deprecated. use setter methods to set properties

Constructs an FTPS client for the given remote host.

IMPORTANT NOTE: This constructor does NOT connect to the server. The connect() method must be called to do this.

Parameters:
remoteAddr - Address of remote FTP server to connect to.
controlPort - Port on remote FTP server to connect to.
timeout - Time-out of connections (0 means no time-out).
configFlags - Combination of flags used to configure the client for implicit FTPS or compatibility with servers that don't fully comply with standards (see SSLFTPClient.ConfigFlags). For servers that comply with standards this value may be set to 0.
Method Detail

setConfigFlags

public void setConfigFlags(int configFlags)
                    throws FTPException
Set the configuration flags which control various compatibility features. The configuration flag constants are in SSLFTPClient.ConfigFlags. They are integers so they should be OR'd together if more than one is required. For example,
     ftpClient.SetConfigFlags(SSLFTPClient.ConfigFlags.DISABLE_SESSION_RESUMPTION
                              | SSLFTPClient.ConfigFlags.DISABLE_SSL_CLOSURE);
 
Note that implict FTPS should not longer be set via ConfigFlags.IMPLICIT_FTPS, which is now deprecated. Instead, use setImplicitFTPS(boolean). If ConfigFlags.IMPLICIT_FTPS is supplied, implict FTPS will be enabled for backward compatibility. However if it is not supplied, the implicit FTPS mode will be unaltered, i.e. if implicit FTPS is currently enabled, it will not be disabled by not supplying ConfigFlags.IMPLICIT_FTPS.

Parameters:
configFlags - Configuration flags to set (see SSLFTPClient.ConfigFlags)
Throws:
FTPException - Thrown if the client is already connected to the server.

getConfigFlags

public int getConfigFlags()
Get the set configuration flags.

Returns:
configuration flags

connect

public void connect()
             throws java.io.IOException,
                    FTPException,
                    SSLFTPCertificateException
Connects to the server at the address and port number defined in the constructor. Must be performed before login() or user() is called. If connecting in implicit FTPS mode (i.e. see SSLFTPClient.ConfigFlags.IMPLICIT_FTPS) then the client and server will negotiate a secure connection upon connection.

Specified by:
connect in interface FTPClientInterface
Overrides:
connect in class ProFTPClient
Throws:
java.io.IOException - Thrown if there is a TCP/IP-related error.
FTPException - Thrown if there is an error related to the FTP protocol.
SSLFTPCertificateException - If connecting in implicit FTPS mode (i.e. see SSLFTPClient.ConfigFlags.IMPLICIT_FTPS) then the SSLFTPCertificateException may be thrown if there's a certificate validation error. In this case, SSLFTPCertificateException.getCertificates() returns the server's certificate(s).

readChar

protected int readChar(java.io.LineNumberReader in)
                throws java.io.IOException
Description copied from class: FTPClient
Attempts to read a single character from the given InputStream. The purpose of this method is to permit subclasses to execute any additional code necessary when performing this operation.

Overrides:
readChar in class FTPClient
Parameters:
in - The LineNumberReader to read from.
Returns:
The character read.
Throws:
java.io.IOException - Thrown if there was an error while reading.

readLine

protected java.lang.String readLine(java.io.LineNumberReader in)
                             throws java.io.IOException
Description copied from class: FTPClient
Attempts to read a single line from the given InputStream. The purpose of this method is to permit subclasses to execute any additional code necessary when performing this operation.

Overrides:
readLine in class FTPClient
Parameters:
in - The LineNumberReader to read from.
Returns:
The string read.
Throws:
java.io.IOException - Thrown if there was an error while reading.

readChunk

public int readChunk(java.io.BufferedInputStream in,
                     byte[] chunk,
                     int chunksize)
              throws java.io.IOException
Description copied from class: FTPClient
Attempts to read a specified number of bytes from the given InputStream and place it in the given byte-array. The purpose of this method is to permit subclasses to execute any additional code necessary when performing this operation.

Overrides:
readChunk in class FTPClient
Parameters:
in - The InputStream to read from.
chunk - The byte-array to place read bytes in.
chunksize - Number of bytes to read.
Returns:
Number of bytes actually read.
Throws:
java.io.IOException - Thrown if there was an error while reading.

getCertificateChain

public java.util.Vector getCertificateChain()
Returns a vector containing the certificates (SSLFTPCertificate) presented by the server with the Certificate Authority's certificate first and the server's certificate last. It allows you to inspect the certificates that the server presented to the client during the establishment of a secure connection. There should be one or more certificates in this chain. The last one in the chain is the server's certificate. Any preceding certificates are certificates of issuers. For example, if there are three: A, B, and C. Then C is the server certificate. C was issued by B, and B was issued by A. At least one of these three certificates must be in the root certificate store for the server to be validated.

Returns:
Vector containing SSLFTPCertificate objects.

getValidateServer

public boolean getValidateServer()
Returns a flag indicating whether or not this client will attempt to validate server certificates. For a certificate to be valid, the certificate of the Certificate Authority (CA) which issued it must be in the set of root certificates. The root certificates managed by means of the root certificate-store (accessible through getRootCertificateStore()). Setting this method to false makes it trivial for an attacker to impersonate a server, so it should be done only for testing purposes.

Returns:
True if servers are to be validated.

setValidateServer

public void setValidateServer(boolean validate)
                       throws FTPException
Determines whether or not this client will attempt to validate server certificates. For a certificate to be valid, the certificate of the Certificate Authority (CA) which issued it must be in the set of root certificates. The root certificates are loaded using the loadRootCertificates(String) method. Setting this method to false makes it trivial for an attacker to impersonate a server, so it should be done only for testing purposes.

Parameters:
validate - True if servers are to be validated.
Throws:
FTPException

setCustomValidator

public void setCustomValidator(SSLFTPValidator newValidator)
                        throws FTPException
Sets the validator. Validators are used for validating server certificates. If this method is not called then the standard validator SSLFTPStandardValidator will be used.

Custom validators may be used to provide user interaction, such as allowing the user view a server's certificate before accepting the connection. See SSLFTPValidator and SSLFTPStandardValidator.

Note that this method must be called before auth is called, otherwise the standard validator will be used.

Parameters:
newValidator - Custom validator to use.
Throws:
FTPException

getEnabledCipherSuites

public SSLFTPCipherSuite[] getEnabledCipherSuites()
Returns an array of all currently enabled cipher-suites.

Returns:
Array of all currently enabled cipher-suites.

disableAllCipherSuites

public void disableAllCipherSuites()
                            throws FTPException
Disables all cipher-suites.

Throws:
FTPException

enableCipherSuite

public void enableCipherSuite(SSLFTPCipherSuite cipherSuite)
                       throws FTPException
Enables the given cipher-suite.

Parameters:
cipherSuite - Cipher-suite to enable.
Throws:
SSLFTPException - Thrown if the given cipher-suite is not valid.
FTPException

enableCipherSuites

public void enableCipherSuites(SSLFTPCipherSuite[] cipherSuites)
                        throws FTPException
Enables the given cipher-suites.

Parameters:
cipherSuites - Cipher-suites to enable.
Throws:
SSLFTPException - Thrown if a cipher-suite is not valid.
FTPException

loadClientKeyFile

public void loadClientKeyFile(java.io.InputStream inputStream,
                              java.lang.String password)
                       throws java.io.FileNotFoundException,
                              java.io.IOException,
                              FTPException
Deprecated. Use setClientCertificate<(inputStream, password)/code>.

Loads the client's private key and certificate from the given input-stream.

Throws:
java.io.FileNotFoundException
java.io.IOException
FTPException

loadClientKeyFile

public void loadClientKeyFile(java.lang.String path,
                              java.lang.String password)
                       throws java.io.FileNotFoundException,
                              java.io.IOException,
                              FTPException
Deprecated. Use loadClientCertificate<(path, password)/code>.

Loads the client's private key and certificate from the given file.

Throws:
java.io.FileNotFoundException
java.io.IOException
FTPException

loadClientCertificate

public void loadClientCertificate(java.io.InputStream inputStream,
                                  java.lang.String password)
                           throws java.io.FileNotFoundException,
                                  java.io.IOException,
                                  FTPException
Loads the client's private key and certificate in PEM format from the given input-stream. The stream must be formatted as follows:
   -----BEGIN xxx PRIVATE KEY-----
   ... client's private key ...
   -----END xxx PRIVATE KEY-----
   -----BEGIN CERTIFICATE-----
   ... client's certificate ...
   -----END CERTIFICATE-----
 
where xxx defines the keytype which must be either RSA or DSA.

A chain of keys (ordered from client's certificate to the root) may be placed in the file. Each certificate must be bracketed as shown above.

Parameters:
inputStream - InputStream to read from.
password - Pass-phrase for accessing the key.
Throws:
java.io.FileNotFoundException - Thrown if the file could not be found.
java.io.IOException - Thrown if there was an error reading the key.
FTPException

loadClientCertificate

public void loadClientCertificate(java.lang.String path,
                                  java.lang.String password)
                           throws java.io.FileNotFoundException,
                                  java.io.IOException,
                                  FTPException
Loads the client's private key and certificate in PEM format from the given file. The file must be formatted as follows:
   -----BEGIN xxx PRIVATE KEY-----
   ... client's private key ...
   -----END xxx PRIVATE KEY-----
   -----BEGIN CERTIFICATE-----
   ... client's certificate ...
   -----END CERTIFICATE-----
 
where xxx defines the keytype which must be either RSA or DSA.

A chain of keys (ordered from client's certificate to the root) may be placed in the file. Each certificate must be bracketed as shown above.

Parameters:
path - Path of the file
password - Pass-phrase for accessing the key.
Throws:
java.io.FileNotFoundException - Thrown if the file could not be found.
java.io.IOException - Thrown if there was an error reading the key.
FTPException

setClientCertificate

public void setClientCertificate(java.security.cert.Certificate certificate,
                                 java.security.PrivateKey privateKey)
                          throws SSLFTPCertificateException
Sets the client's certificate and private key given standard Java Certificate and PrivateKey objects. To load a certificate and a private key from a Java keystore, code similar to the following should be used:
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(keyStoreFileName, keyStorePassword.toCharArray());
    Certificate certificate = keyStore.getCertificate(alias);
    PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, privateKeyPassword.toCharArray());
    ftp.setClientCertificate(certificate, privateKey);
 

Parameters:
certificate - The client's certificate.
privateKey - The client's private key.
Throws:
SSLFTPCertificateException - Thrown if there was a problem accessing the key or the private key.

loadRootCertificates

public void loadRootCertificates(java.io.InputStream inputStream)
                          throws java.io.FileNotFoundException,
                                 java.io.IOException,
                                 FTPException
Deprecated. Use getRootCertificateStore().SSLFTPCertificateStore.importPEMFile(InputStream)

Loads a set of acceptable root certificates from an input-stream. These are used to verify the server's certificate. The certificates in the file must be of the OpenSSL PEM format and be bracketed as follows:
   -----BEGIN CERTIFICATE-----
   ... first certificate ...
   -----END CERTIFICATE-----
   -----BEGIN CERTIFICATE-----
   ... second certificate ...
   -----END CERTIFICATE-----
   etc
 

The ca-root package of FreeBSD has a file, ca-roots.crt, which contains a list of root certificates. It may be downloaded from the FreeBSD website (search for "ca-root") It is important to be aware that the root certificates file is a potential point of attack since an errant entry in this file may allow attackers obtain access to secured resources.

Parameters:
inputStream - InputStream to read from.
Throws:
java.io.FileNotFoundException - Thrown if the file could not be found.
java.io.IOException - Thrown if there was an error reading the certificates.
FTPException

loadRootCertificates

public void loadRootCertificates(java.lang.String path)
                          throws java.io.IOException,
                                 FTPException
Deprecated. Use getRootCertificateStore().SSLFTPCertificateStore.importPEMFile(String)

Loads a set of acceptable root certificates from a file. These are used to verify the server's certificate. The certificates in the file must be of the OpenSSL PEM format and be bracketed as follows:
   -----BEGIN CERTIFICATE-----
   ... first certificate ...
   -----END CERTIFICATE-----
   -----BEGIN CERTIFICATE-----
   ... second certificate ...
   -----END CERTIFICATE-----
   etc
 

The ca-root package of FreeBSD has a file, ca-roots.crt, which contains a list of root certificates. It may be downloaded from the FreeBSD website (search for "ca-root") It is important to be aware that the root certificates file is a potential point of attack since an errant entry in this file may allow attackers obtain access to secured resources.

Parameters:
path - Path of the file.
Throws:
java.io.FileNotFoundException - Thrown if the file could not be found.
java.io.IOException - Thrown if there was an error reading the certificates.
FTPException

getRootCertificateStore

public SSLFTPCertificateStore getRootCertificateStore()
Returns a reference to the SSLFTPCertificateStore which contains the root certificates that will be used to validate the server certificate.

Returns:
The root certificate-store.

setRootCertificateStore

public void setRootCertificateStore(SSLFTPCertificateStore store)
Sets the SSLFTPCertificateStore which contains the root certificates that will be used to validate the server certificate.

Parameters:
store - The root certificate-store to use

auth

public void auth(java.lang.String securityMechanism)
          throws java.io.IOException,
                 FTPException
Switches the control-channel (the connection which carries commands) to secure mode. If this command succeeds, then all subsequent commands and their corresponding replies will be secure. Unless the ConfigFlags.START_WITH_CLEAR_DATA_CHANNELS flag was passed in during construction, the client will switch to private (i.e. secure) data channels immediately after a connection is made. It does this by invoking pbsz(0) and prot('P').

This library supports three arguments to this methods, SSLFTPClient.AUTH_TLS, SSLFTPClient.AUTH_TLS_C, and SSLFTPClient.SSL.

Parameters:
securityMechanism - Security mechanism to use (see above)
Throws:
java.io.IOException - Thrown if a communication error occurred.
FTPException - Thrown if an FTP-protocol related error occurred.
SSLFTPCertificateException - thrown if there's a certificate validation error. Use SSLFTPCertificateException.getCertificates() to obtain the server's certificate(s).

ccc

public void ccc()
         throws FTPException,
                java.io.IOException
Clears the control channel, setting it back to plain text. After this command is issued, the server will continue the control connection in plaintext, expecting the next command from the client to be in plaintext. This command is often used in conjunction with firewalls, which need to be able to inspect the control channel to open data channel ports in the firewall. This can only be done if the control channel is not encrypted.

The server will not accept any more PBSZ or PROT commands. All subsequent data transfers must be protected with the current PROT settings.

Throws:
FTPException
java.io.IOException

auth

public void auth(char command)
          throws java.io.IOException,
                 FTPException
Required for certain implementations of implicit SSL. Some servers supporting implicit SSL do not require this method to be called, others do.

Parameters:
command - Seurity level to be used (must be either SSLFTPClient.PROT_PRIVATE or SSLFTPClient.PROT_CLEAR.
Throws:
java.io.IOException - Thrown if a communication error occurred.
FTPException - Thrown if an FTP-protocol related error occurred.

prot

public void prot(char command)
          throws java.io.IOException,
                 FTPException
Defines the security-level of subsequent data-transfers. There are two security levels, 'C' (Clear) and 'P' (Private). The former dictates that data-transfers should be insecure and the latter that they should be secure. There are two public member-variables, SSLFTPClient.PROT_PRIVATE and SSLFTPClient.PROT_CLEAR defined for use with this method.

Parameters:
command - Seurity level to be used (must be either SSLFTPClient.PROT_PRIVATE or SSLFTPClient.PROT_CLEAR.
Throws:
java.io.IOException - Thrown if a communication error occurred.
FTPException - Thrown if an FTP-protocol related error occurred.

pbsz

public void pbsz(int bufferSize)
          throws java.io.IOException,
                 FTPException
Defines the buffer-size to be used on data-connections. In conformity with the standard, this method must be 0 (zero). Note that this method is required only to conform with the standard.

Parameters:
bufferSize - Buffer-size to use (must be zero).
Throws:
java.io.IOException - Thrown if a communication error occurred.
FTPException - Thrown if an FTP-protocol related error occurred.

getServerCertificate

public static SSLFTPCertificate getServerCertificate(java.lang.String hostName)
                                              throws FTPException,
                                                     java.io.IOException
Connects to the given host and retrieves its certificate. This method simply connects to the given host and tries to establish a secure connection. This always fails since the server certificate can't be validated, but in the process the server presents its certificate. This certificate is returned. It should be verified by some means (e.g. a dialog pop-up) to ensure that it is the correct certificate. It should not be added as a root certificate without independent verification since this defeats the purpose of server validation and means that the client essentially could be connected to any (potentially attacking) server.

Parameters:
hostName - Host-name of server.
Returns:
The server's certificate.
Throws:
FTPException - Thrown if an FTP-related error occurred.
java.io.IOException - Thrown if a TCP/IP-related error occurred.

getServerCertificate

public static SSLFTPCertificate getServerCertificate(java.lang.String hostName,
                                                     int remotePort)
                                              throws FTPException,
                                                     java.io.IOException
Connects to the given host and retrieves its certificate. This method simply connects to the given host and tries to establish a secure connection. This always fails since the server certificate can't be validated, but in the process the server presents its certificate. This certificate is returned. It should be verified by some means (e.g. a dialog pop-up) to ensure that it is the correct certificate. It should not be added as a root certificate without independent verification since this defeats the purpose of server validation and means that the client essentially could be connected to any (potentially attacking) server.

Parameters:
hostName - Host-name of server.
remotePort - Port to connect to.
Returns:
The server's certificate.
Throws:
FTPException - Thrown if an FTP-related error occurred.
java.io.IOException - Thrown if a TCP/IP-related error occurred.

getServerSecurityMechanism

public static java.lang.String getServerSecurityMechanism(java.lang.String remoteHost)
                                                   throws FTPException,
                                                          java.io.IOException
Returns the safest explicit FTPS security mechanism supported by the server. If the server supports explicit FTPS using TLS then AUTH_TLS is returned. If the server supports explicit FTPS using SLL but not TLS then AUTH_SSL is returned. If explicit FTPS is not supported then the method returns null.

Parameters:
remoteHost - Host from which to retrieve a security mechanism.
Returns:
AUTH_TLS, AUTH_SSL or null (see above).
Throws:
FTPException - Thrown if an FTP-related error occurred.
java.io.IOException - Thrown if a TCP/IP-related error occurred.

getServerSecurityMechanism

public static java.lang.String getServerSecurityMechanism(java.lang.String remoteHost,
                                                          int remotePort)
                                                   throws FTPException,
                                                          java.io.IOException
Returns the safest explicit FTPS security mechanism supported by the server. If the server supports explicit FTPS using TLS then AUTH_TLS is returned. If the server supports explicit FTPS using SLL but not TLS then AUTH_SSL is returned. If explicit FTPS is not supported then the method returns null.

Parameters:
remoteHost - Host from which to retrieve a security mechanism.
remotePort - Port on which to connect to the server.
Returns:
AUTH_TLS, AUTH_SSL or null (see above).
Throws:
FTPException - Thrown if an FTP-related error occurred.
java.io.IOException - Thrown if a TCP/IP-related error occurred.

isImplicitFTPS

public boolean isImplicitFTPS()
Is implicit FTPS being used?

Returns:
true if implicit, false if not implicit

setImplicitFTPS

public void setImplicitFTPS(boolean implicitFTPS)
Set implicit FTPS on or off. By default explicit FTPS is used. Implicit FTPS is an older form of FTPS which connects on a different port (usually 990) from standard FTP. It is not recommended for deployment in new systems and is included in this library mainly for compatibility with legacy systems.

Implicit FTPS is not recommended because it is not compatible with FTP standards and not supported by as many systems. It is however, no less secure than explicit FTPS.

Parameters:
implicitFTPS - true if switching on, false if switching off

toString

public java.lang.String toString()
String representation

Overrides:
toString in class FTPClient