Reputation: 331
I'm making a class in Java that downloads a specific file from a server. I have a method that can download directly from an FTP server and one from an SFTP server.
Without any assumptions being made on the hostname (without checking if it starts with ftp:// or sftp://, as sometimes the server may be local), is there any way to determine if a server is FTP or SFTP, and therefore which method to use?
Ideally, I'd like to determine programmatically, and not just to try the alternative if it fails. Thanks for any help in advance!
EDIT: For anyone interested, my very basic and definitely not perfect solution is somethign like this:
private int determineServerProtocol(String host, String port) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try (Socket socket = new Socket(host, Integer.parseInt(port))) {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
result = in.readLine();
out.close();
in.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
if (result.contains("SSH")) {
System.out.println("Server is SFTP");
// do things...
} else {
System.out.println("Server is FTP");
// do things...
}
}
Upvotes: 6
Views: 13262
Reputation: 202682
The protocol must be a part of your session settings along with hostname and credentials. Never try to autodetect between secure and insecure protocol. This is a terrible security flaw.
With such "autodetection", a possible MITM attacker can make your application use an unecrypted FTP protocol easily, even if the real server is actually using an SFTP protocol. This will make your application send your SFTP credentials straight to the attacker, unencrypted!
If you want to make your application forward compatible with a possible future switch to the SFTP, at least, make it never fall back to the FTP, once an SFTP connection ever succeeds.
Also I do not see a point of an explicit detection. Simply try to connect and authenticate with FTP and if that fails, try SFTP. You can never know how the transition will go. They can choose to keep FTP server running along with SFTP, but with login disabled or any other combination.
Upvotes: 0
Reputation: 601
You can do a telnet. Apache Commons provides a client side of many intenet protocols.
https://commons.apache.org/proper/commons-net/
And then analyze the answer.
As far as I know, all SSH servers answer something with SSH inside.
telnet demo.wftpserver.com 2222
Trying 199.71.215.197...
Connected to demo.wftpserver.com.
Escape character is '^]'.
SSH-2.0-WingFTPServer
Not SSH
telnet ftp.funet.fi 21
Trying 193.166.3.2...
Connected to ftp.funet.fi.
Escape character is '^]'.
220 FTP Welcome
Upvotes: 1