From d87c4875480b0f691332a72d4bee19ed2e64dff9 Mon Sep 17 00:00:00 2001 From: Inf1mum Date: Thu, 5 Nov 2026 02:24:50 +0300 Subject: [PATCH] Fix NET-746: add char[]-based login and sendCommand/pass overloads for FTP FTPClient.login(String, char[]) sends the password as a char array and clears the array once it has been transmitted to the server. The command is built and written to the control connection as char[] end-to-end so that sensitive data is never materialized into a String; command listeners receive a masked ProtocolCommandEvent. FTPSClient gets a symmetric sendCommand(String, char[]) override so the CCC transition is preserved for the new overload. Signed-off-by: Inf1mum --- src/changes/changes.xml | 1 + .../java/org/apache/commons/net/ftp/FTP.java | 124 +++++++++- .../org/apache/commons/net/ftp/FTPClient.java | 36 +++ .../apache/commons/net/ftp/FTPSClient.java | 25 +- .../ftp/FTPClientLoginCharPasswordTest.java | 223 ++++++++++++++++++ .../org/apache/commons/net/ftp/FTPTest.java | 15 ++ 6 files changed, 420 insertions(+), 4 deletions(-) create mode 100644 src/test/java/org/apache/commons/net/ftp/FTPClientLoginCharPasswordTest.java diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 611cd0b87..12174024e 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -72,6 +72,7 @@ The type attribute can be add,update,fix,remove. Force Gregorian calendar in FTP listing timestamp parsers (##406). TFTPRequestPacket now throws TFTPPacketException instead of ArrayIndexOutOfBoundsException (#407). + Add FTPClient.login(String, char[]) so passwords are sent as char arrays and cleared after transmission; add FTP.pass(char[]) and FTP.sendCommand(String, char[]) / FTP.sendCommand(FTPCmd, char[]) overloads. Add and use FTPFile.setUserPermission(int, boolean). Bump org.apache.commons:commons-parent from 97 to 107. diff --git a/src/main/java/org/apache/commons/net/ftp/FTP.java b/src/main/java/org/apache/commons/net/ftp/FTP.java index 17b354240..dd5d08679 100644 --- a/src/main/java/org/apache/commons/net/ftp/FTP.java +++ b/src/main/java/org/apache/commons/net/ftp/FTP.java @@ -191,6 +191,12 @@ public class FTP extends SocketClient { private static final String MODES = "AEILNTCFRPSBCZ"; + /** + * Placeholder used in command-sent events fired for {@link #sendCommand(String, char[])} so that sensitive arguments are never materialized into a + * {@link String}. + */ + private static final String MASKED_ARGS = "******"; + private static void checkCRLF(final String command, final String args) { if (command != null && (command.indexOf('\r') >= 0 || command.indexOf('\n') >= 0) || args != null && (args.indexOf('\r') >= 0 || args.indexOf('\n') >= 0)) { @@ -198,6 +204,19 @@ private static void checkCRLF(final String command, final String args) { } } + private static void checkCRLF(final String command, final char[] args) { + if (command != null && (command.indexOf('\r') >= 0 || command.indexOf('\n') >= 0)) { + throw new IllegalArgumentException("Commands and arguments cannot contain CR or LF characters"); + } + if (args != null) { + for (final char c : args) { + if (c == '\r' || c == '\n') { + throw new IllegalArgumentException("Commands and arguments cannot contain CR or LF characters"); + } + } + } + } + /** * The last FTP reply code. */ @@ -282,7 +301,7 @@ protected void __getReplyNoReport() throws IOException { * @since 3.0 */ protected void __noop() throws IOException { - final String msg = buildMessage(FTPCmd.NOOP.getCommand(), null); + final String msg = buildMessage(FTPCmd.NOOP.getCommand(), (String) null); send(msg); __getReplyNoReport(); // This may time out } @@ -444,6 +463,23 @@ private String buildMessage(final String command, final String args) { return builder.toString(); } + private char[] buildMessage(final String command, final char[] args) { + final int commandLen = command.length(); + final int eolLen = NETASCII_EOL.length(); + final boolean hasArgs = args != null; + final char[] message = new char[commandLen + (hasArgs ? args.length + 1 : 0) + eolLen]; + int pos = 0; + command.getChars(0, commandLen, message, pos); + pos += commandLen; + if (hasArgs) { + message[pos++] = SP; + System.arraycopy(args, 0, message, pos, args.length); + pos += args.length; + } + NETASCII_EOL.getChars(0, eolLen, message, pos); + return message; + } + /** * Sends the FTP {@code CDUP} command to the server, receive the reply, and return the reply code. * @@ -1048,6 +1084,25 @@ public int pass(final String password) throws IOException { return sendCommand(FTPCmd.PASS, password); } + /** + * Sends the FTP {@code PASS} command to the server, receive the reply, and return the reply code. + *

+ * The password is provided as a {@code char} array so that it is never materialized into a {@link String}, which cannot be reliably wiped. Callers are + * responsible for clearing the array afterwards, see {@link FTPClient#login(String, char[])}. + *

+ * + * @param password The plain text password of the user being logged into. + * @return The reply code received from the server. + * @throws FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason + * causing the server to send FTP reply code 421. This exception may be caught either as an IOException or + * independently as itself. + * @throws IOException If an I/O error occurs while either sending the command or receiving the server reply. + * @since 3.13.1 + */ + public int pass(final char[] password) throws IOException { + return sendCommand(FTPCmd.PASS, password); + } + /** * Sends the FTP {@code PASV} command to the server, receive the reply, and return the reply code. Remember, it's up to you to interpret the * reply string containing the host/port information. @@ -1209,6 +1264,18 @@ private void send(final String message) throws IOException, FTPConnectionClosedE } } + private void send(final char[] message) throws IOException, FTPConnectionClosedException, SocketException { + try { + _controlOutput_.write(message); + _controlOutput_.flush(); + } catch (final SocketException e) { + if (!isConnected()) { + throw new FTPConnectionClosedException("Connection unexpectedly closed."); + } + throw e; + } + } + /** * Sends an FTP command to the server, waits for a reply and returns the numerical response code. After invocation, for more detailed information, the * actual reply text can be accessed by calling {@link #getReplyString getReplyString} or {@link #getReplyStrings getReplyStrings}. @@ -1222,7 +1289,7 @@ private void send(final String message) throws IOException, FTPConnectionClosedE * @since 3.3 */ public int sendCommand(final FTPCmd command) throws IOException { - return sendCommand(command, null); + return sendCommand(command, (String) null); } /** @@ -1242,6 +1309,28 @@ public int sendCommand(final FTPCmd command, final String args) throws IOExcepti return sendCommand(command.getCommand(), args); } + /** + * Sends an FTP command to the server, waits for a reply and returns the numerical response code. After invocation, for more detailed information, the + * actual reply text can be accessed by calling {@link #getReplyString getReplyString} or {@link #getReplyStrings getReplyStrings}. + *

+ * The arguments are provided as a {@code char} array so that sensitive data (like passwords) is never materialized into a {@link String}, which cannot + * be reliably wiped. Unlike {@link #sendCommand(FTPCmd, String)}, the {@code ProtocolCommandEvent} fired to command listeners does not contain the + * command arguments, they are reported as masked. + *

+ * + * @param command The FTPCmd enum corresponding to the FTP command to send. + * @param args The arguments to the FTP command. If this parameter is set to null, then the command is sent with no argument. + * @return The integer value of the FTP reply code returned by the server in response to the command. + * @throws FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason + * causing the server to send FTP reply code 421. This exception may be caught either as an IOException or + * independently as itself. + * @throws IOException If an I/O error occurs while either sending the command or receiving the server reply. + * @since 3.13.1 + */ + public int sendCommand(final FTPCmd command, final char[] args) throws IOException { + return sendCommand(command.getCommand(), args); + } + /** * Sends an FTP command with no arguments to the server, waits for a reply and returns the numerical response code. After invocation, for more detailed * information, the actual reply text can be accessed by calling {@link #getReplyString getReplyString} or {@link #getReplyStrings getReplyStrings}. @@ -1287,7 +1376,7 @@ public int sendCommand(final int command, final String args) throws IOException * @throws IOException If an I/O error occurs while either sending the command or receiving the server reply. */ public int sendCommand(final String command) throws IOException { - return sendCommand(command, null); + return sendCommand(command, (String) null); } /** @@ -1313,6 +1402,35 @@ public int sendCommand(final String command, final String args) throws IOExcepti return getReply(); } + /** + * Sends an FTP command to the server, waits for a reply and returns the numerical response code. After invocation, for more detailed information, the + * actual reply text can be accessed by calling {@link #getReplyString getReplyString} or {@link #getReplyStrings getReplyStrings}. + *

+ * The arguments are provided as a {@code char} array so that sensitive data (like passwords) is never materialized into a {@link String}, which cannot + * be reliably wiped: the command is built and written to the control connection as {@code char} arrays only. Unlike + * {@link #sendCommand(String, String)}, the {@code ProtocolCommandEvent} fired to command listeners does not contain the command arguments, they are + * reported as masked. + *

+ * + * @param command The text representation of the FTP command to send. + * @param args The arguments to the FTP command. If this parameter is set to null, then the command is sent with no argument. + * @return The integer value of the FTP reply code returned by the server in response to the command. + * @throws FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason + * causing the server to send FTP reply code 421. This exception may be caught either as an IOException or + * independently as itself. + * @throws IOException If an I/O error occurs while either sending the command or receiving the server reply. + * @since 3.13.1 + */ + public int sendCommand(final String command, final char[] args) throws IOException { + checkCRLF(command, args); + if (_controlOutput_ == null) { + throw new IOException("Connection is not open"); + } + send(buildMessage(command, args)); + fireCommandSent(command, buildMessage(command, args != null ? MASKED_ARGS : null)); + return getReply(); + } + /** * Sets the character encoding to be used by the FTP control connection. Some FTP servers require that commands be issued in a non-ASCII encoding like * UTF-8 so that file names with multi-byte character representations (e.g, Big 8) can be specified. diff --git a/src/main/java/org/apache/commons/net/ftp/FTPClient.java b/src/main/java/org/apache/commons/net/ftp/FTPClient.java index efe740fc2..5f1009a74 100644 --- a/src/main/java/org/apache/commons/net/ftp/FTPClient.java +++ b/src/main/java/org/apache/commons/net/ftp/FTPClient.java @@ -38,6 +38,7 @@ import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; @@ -2435,6 +2436,41 @@ public boolean login(final String user, final String password) throws IOExceptio return FTPReply.isPositiveCompletion(pass(password)); } + /** + * Login to the FTP server using the provided user and password. + *

+ * The password is provided as a {@code char} array so that it is never materialized into a {@link String}, which cannot be reliably wiped. Once the + * password has been transmitted to the server, the array is cleared with {@link Arrays#fill(char[], char)}; note that this happens even if the server + * rejects the password, so the same array cannot be reused for a second login attempt. + *

+ * + * @param user The user name to login under. + * @param password The password to use. It is cleared after being sent to the server. + * @return True if successfully completed, false if not. + * @throws FTPConnectionClosedException If the FTP server prematurely closes the connection as a result of the client being idle or some other reason + * causing the server to send FTP reply code 421. This exception may be caught either as an IOException or + * independently as itself. + * @throws IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server. + * @since 3.13.1 + */ + public boolean login(final String user, final char[] password) throws IOException { + user(user); + if (FTPReply.isPositiveCompletion(_replyCode)) { + return true; + } + // If we get here, we either have an error code, or an intermediate + // reply requesting password. + if (!FTPReply.isPositiveIntermediate(_replyCode)) { + return false; + } + try { + return FTPReply.isPositiveCompletion(pass(password)); + } finally { + // The password has been handed to the control connection: wipe it. + Arrays.fill(password, (char) 0); + } + } + /** * Login to the FTP server using the provided username, password, and account. If no account is required by the server, only the username and password, the * account information is not used. diff --git a/src/main/java/org/apache/commons/net/ftp/FTPSClient.java b/src/main/java/org/apache/commons/net/ftp/FTPSClient.java index b6e931b1f..9f67c9c34 100644 --- a/src/main/java/org/apache/commons/net/ftp/FTPSClient.java +++ b/src/main/java/org/apache/commons/net/ftp/FTPSClient.java @@ -959,7 +959,30 @@ public long parsePBSZ(final long pbsz) throws SSLException, IOException { // Would like to remove this method, but that will break any existing clients that are using CCC @Override public int sendCommand(final String command, final String args) throws IOException { - final int repCode = super.sendCommand(command, args); + return postSendCCC(super.sendCommand(command, args), command); + } + + /** + * Send an FTP command with sensitive arguments. A successful CCC (Clear Command Channel) command causes the underlying {@link SSLSocket} instance to be + * assigned to a plain {@link Socket} + * + * @param command The FTP command. + * @param args The arguments to the FTP command as a {@code char} array, for sensitive data. + * @return server reply. + * @throws IOException If an I/O error occurs while sending the command. + * @throws SSLException Thrown if a CCC command fails + * @see org.apache.commons.net.ftp.FTP#sendCommand(String, char[]) + * @since 3.13.1 + */ + @Override + public int sendCommand(final String command, final char[] args) throws IOException { + return postSendCCC(super.sendCommand(command, args), command); + } + + /** + * Handles the clear command channel transition after a {@code CCC} command was sent. + */ + private int postSendCCC(final int repCode, final String command) throws IOException { /* If CCC is issued, restore socket i/o streams to unsecured versions */ if (CMD_CCC.equals(command)) { if (FTPReply.COMMAND_OK != repCode) { diff --git a/src/test/java/org/apache/commons/net/ftp/FTPClientLoginCharPasswordTest.java b/src/test/java/org/apache/commons/net/ftp/FTPClientLoginCharPasswordTest.java new file mode 100644 index 000000000..916a2876b --- /dev/null +++ b/src/test/java/org/apache/commons/net/ftp/FTPClientLoginCharPasswordTest.java @@ -0,0 +1,223 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * https://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 org.apache.commons.net.ftp; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.net.ProtocolCommandEvent; +import org.apache.commons.net.ProtocolCommandListener; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Tests {@link FTPClient#login(String, char[])} (NET-746): the password is sent as a {@code char} array, never materialized into a {@link String}, and the + * array is cleared once the password has been transmitted. + */ +class FTPClientLoginCharPasswordTest { + + /** + * A minimal scripted FTP server running on a local port. + */ + private static final class FakeFtpServer implements AutoCloseable { + + private final ServerSocket serverSocket; + private final StringBuffer received = new StringBuffer(); + private final String userReply; + private final String passwordReply; + + FakeFtpServer(final String userReply, final String passwordReply) throws IOException { + this.serverSocket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + this.userReply = userReply; + this.passwordReply = passwordReply; + } + + int getPort() { + return serverSocket.getLocalPort(); + } + + String getReceived() { + synchronized (received) { + return received.toString(); + } + } + + void start() { + final Thread thread = new Thread(this::run, "fake-ftp-server"); + thread.setDaemon(true); + thread.start(); + } + + private void run() { + try (Socket socket = serverSocket.accept(); OutputStream out = socket.getOutputStream()) { + out.write("220 fake\r\n".getBytes(StandardCharsets.ISO_8859_1)); + out.flush(); + try (BufferedReader in = new BufferedReader( + new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1))) { + String line; + while ((line = in.readLine()) != null) { + synchronized (received) { + received.append(line).append("\r\n"); + } + if (line.startsWith("USER")) { + out.write((userReply + "\r\n").getBytes(StandardCharsets.ISO_8859_1)); + } else if (line.startsWith("PASS")) { + out.write((passwordReply + "\r\n").getBytes(StandardCharsets.ISO_8859_1)); + } else { + out.write("200 ok\r\n".getBytes(StandardCharsets.ISO_8859_1)); + } + out.flush(); + } + } + } catch (final IOException e) { + // Expected when the client disconnects. + } + } + + @Override + public void close() throws IOException { + serverSocket.close(); + } + } + + private static final class SentCommandRecorder implements ProtocolCommandListener { + + private final List sentMessages = new ArrayList<>(); + + @Override + public void protocolCommandSent(final ProtocolCommandEvent event) { + sentMessages.add(event.getMessage()); + } + + @Override + public void protocolReplyReceived(final ProtocolCommandEvent event) { + // not relevant here + } + } + + private static final String SECRET = "s3cr3t"; + + private FakeFtpServer server; + + private FTPClient newConnectedClient() throws IOException { + final FTPClient client = new FTPClient(); + client.connect("localhost", server.getPort()); + return client; + } + + @AfterEach + void tearDown() throws IOException { + if (server != null) { + server.close(); + } + } + + private void startServer(final String userReply, final String passwordReply) throws IOException { + server = new FakeFtpServer(userReply, passwordReply); + server.start(); + } + + @Test + void testLoginWithCharArrayClearsPasswordAfterSend() throws IOException { + startServer("331 need password", "230 logged in"); + final char[] password = SECRET.toCharArray(); + final FTPClient client = newConnectedClient(); + try { + assertTrue(client.login("user", password)); + // The password reached the server... + assertTrue(server.getReceived().contains("PASS " + SECRET + "\r\n")); + // ...and the array was cleared afterwards. + assertArrayEquals(new char[SECRET.length()], password); + } finally { + client.disconnect(); + } + } + + @Test + void testLoginWithCharArrayDoesNotLeakToCommandListeners() throws IOException { + startServer("331 need password", "230 logged in"); + final SentCommandRecorder recorder = new SentCommandRecorder(); + final FTPClient client = newConnectedClient(); + client.addProtocolCommandListener(recorder); + try { + assertTrue(client.login("user", SECRET.toCharArray())); + assertTrue(server.getReceived().contains("PASS " + SECRET + "\r\n")); + for (final String message : recorder.sentMessages) { + assertFalse(message.contains(SECRET), () -> "Password leaked to listener: " + message); + } + // The listener still gets a useful, masked command event. + assertTrue(recorder.sentMessages.stream().anyMatch(m -> m.contains("PASS ******"))); + } finally { + client.disconnect(); + } + } + + @Test + void testLoginWithCharArrayRejectedStillClearsPassword() throws IOException { + startServer("331 need password", "530 login incorrect"); + final char[] password = SECRET.toCharArray(); + final FTPClient client = newConnectedClient(); + try { + assertFalse(client.login("user", password)); + assertArrayEquals(new char[SECRET.length()], password); + } finally { + client.disconnect(); + } + } + + @Test + void testLoginWithCharArrayKeepsPasswordWhenNotRequested() throws IOException { + startServer("230 logged in", "230 logged in"); + final char[] password = SECRET.toCharArray(); + final FTPClient client = newConnectedClient(); + try { + // The server accepts the user without asking for a password, so the array is untouched. + assertTrue(client.login("user", password)); + assertArrayEquals(SECRET.toCharArray(), password); + assertFalse(server.getReceived().contains("PASS")); + } finally { + client.disconnect(); + } + } + + @Test + void testPassWithCharArray() throws IOException { + startServer("331 need password", "230 logged in"); + final FTPClient client = newConnectedClient(); + try { + assertEquals(FTPReply.NEED_PASSWORD, client.user("user")); + assertEquals(FTPReply.USER_LOGGED_IN, client.pass(SECRET.toCharArray())); + assertTrue(server.getReceived().contains("PASS " + SECRET + "\r\n")); + } finally { + client.disconnect(); + } + } +} diff --git a/src/test/java/org/apache/commons/net/ftp/FTPTest.java b/src/test/java/org/apache/commons/net/ftp/FTPTest.java index 07ecf4e39..22b564ca1 100644 --- a/src/test/java/org/apache/commons/net/ftp/FTPTest.java +++ b/src/test/java/org/apache/commons/net/ftp/FTPTest.java @@ -42,4 +42,19 @@ void testRejectLFInArgs() { void testRejectLFInCommand() { assertThrows(IllegalArgumentException.class, () -> new FTP().sendCommand("NOOP\nDELE secret")); } + + @Test + void testRejectCRInCharArgs() { + assertThrows(IllegalArgumentException.class, () -> new FTP().sendCommand("RETR", "file\rDELE secret".toCharArray())); + } + + @Test + void testRejectCRLFInCharArgs() { + assertThrows(IllegalArgumentException.class, () -> new FTP().sendCommand("RETR", "file\r\nDELE secret".toCharArray())); + } + + @Test + void testRejectLFInCharArgs() { + assertThrows(IllegalArgumentException.class, () -> new FTP().sendCommand("RETR", "file\nDELE secret".toCharArray())); + } }