001/*
002 * Copyright 2013-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2013-2024 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2013-2024 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.util;
037
038
039
040import java.io.BufferedReader;
041import java.io.ByteArrayInputStream;
042import java.io.File;
043import java.io.InputStreamReader;
044import java.util.Arrays;
045
046import com.unboundid.ldap.sdk.LDAPException;
047import com.unboundid.ldap.sdk.ResultCode;
048
049import static com.unboundid.util.UtilityMessages.*;
050
051
052
053/**
054 * This class provides a mechanism for reading a password from the command line
055 * in a way that attempts to prevent it from being displayed.  If it is
056 * available (i.e., Java SE 6 or later), the
057 * {@code java.io.Console.readPassword} method will be used to accomplish this.
058 * For Java SE 5 clients, a more primitive approach must be taken, which
059 * requires flooding standard output with backspace characters using a
060 * high-priority thread.  This has only a limited effectiveness, but it is the
061 * best option available for older Java versions.
062 */
063@ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE)
064public final class PasswordReader
065{
066  /**
067   * The input stream from which to read the password.  This should only be set
068   * when running unit tests.
069   */
070  @Nullable private static volatile BufferedReader TEST_READER = null;
071
072
073
074  /**
075   * The default value to use for the environment variable.  This should only
076   * be set when running unit tests.
077   */
078  @Nullable private static volatile String DEFAULT_ENVIRONMENT_VARIABLE_VALUE =
079       null;
080
081
082
083  /**
084   * The name of an environment variable that can be used to specify the path
085   * to a file that contains the password to be read.  This is also
086   * predominantly intended for use when running unit tests, and may be
087   * necessary for tests running in a separate process that can't use the
088   * {@code TEST_READER}.
089   */
090  @NotNull private static final String PASSWORD_FILE_ENVIRONMENT_VARIABLE =
091       "LDAP_SDK_PASSWORD_READER_PASSWORD_FILE";
092
093
094
095  /**
096   * Creates a new instance of this password reader thread.
097   */
098  private PasswordReader()
099  {
100    // No implementation is required.
101  }
102
103
104
105  /**
106   * Reads a password from the console as a character array.
107   *
108   * @return  The characters that comprise the password that was read.
109   *
110   * @throws  LDAPException  If a problem is encountered while trying to read
111   *                         the password.
112   */
113  @NotNull()
114  public static char[] readPasswordChars()
115         throws LDAPException
116  {
117    // If an input stream is available, then read the password from it.
118    final BufferedReader testReader = TEST_READER;
119    if (testReader != null)
120    {
121      try
122      {
123        return testReader.readLine().toCharArray();
124      }
125      catch (final Exception e)
126      {
127        Debug.debugException(e);
128        throw new LDAPException(ResultCode.LOCAL_ERROR,
129             ERR_PW_READER_FAILURE.get(StaticUtils.getExceptionMessage(e)),
130             e);
131      }
132    }
133
134
135    // If a password input file environment variable has been set, then read
136    // the password from that file.
137    final String environmentVariableValue = StaticUtils.getEnvironmentVariable(
138         PASSWORD_FILE_ENVIRONMENT_VARIABLE,
139         DEFAULT_ENVIRONMENT_VARIABLE_VALUE);
140    if (environmentVariableValue != null)
141    {
142      try
143      {
144        final File f = new File(environmentVariableValue);
145        final PasswordFileReader r = new PasswordFileReader();
146        return r.readPassword(f);
147      }
148      catch (final Exception e)
149      {
150        Debug.debugException(e);
151        throw new LDAPException(ResultCode.LOCAL_ERROR,
152             ERR_PW_READER_FAILURE.get(StaticUtils.getExceptionMessage(e)),
153             e);
154      }
155    }
156
157
158    if (System.console() == null)
159    {
160      throw new LDAPException(ResultCode.LOCAL_ERROR,
161           ERR_PW_READER_CANNOT_READ_PW_WITH_NO_CONSOLE.get());
162    }
163
164    return System.console().readPassword();
165  }
166
167
168
169  /**
170   * Reads a password from the console as a byte array.
171   *
172   * @return  The characters that comprise the password that was read.
173   *
174   * @throws  LDAPException  If a problem is encountered while trying to read
175   *                         the password.
176   */
177  @NotNull()
178  public static byte[] readPassword()
179         throws LDAPException
180  {
181    // Get the characters that make up the password.
182    final char[] pwChars = readPasswordChars();
183
184    // Convert the password to bytes.
185    final ByteStringBuffer buffer = new ByteStringBuffer();
186    buffer.append(pwChars);
187    Arrays.fill(pwChars, '\u0000');
188    final byte[] pwBytes = buffer.toByteArray();
189    buffer.clear(true);
190    return pwBytes;
191  }
192
193
194
195  /**
196   * This is a legacy method that now does nothing.  It was required by a
197   * former version of this class when older versions of Java were still
198   * supported, and is retained only for the purpose of API backward
199   * compatibility.
200   *
201   * @deprecated  This method is no longer used.
202   */
203  @Deprecated()
204  public void run()
205  {
206    // No implementation is required.
207  }
208
209
210
211  /**
212   * Specifies the lines that should be used as input when reading the password.
213   * This should only be set when running unit tests, and the
214   * {@link #setTestReader(BufferedReader)} method should be called with a value
215   * of {@code null} before the end of the test to ensure that the password
216   * reader is reverted back to its normal behavior.
217   *
218   * @param  lines  The lines of input that should be provided to the password
219   *                reader instead of actually obtaining them interactively.
220   *                It must not be {@code null} but may be empty.
221   */
222  @InternalUseOnly()
223  public static void setTestReaderLines(@NotNull final String... lines)
224  {
225    final ByteStringBuffer buffer = new ByteStringBuffer();
226    for (final String line : lines)
227    {
228      buffer.append(line);
229      buffer.append(StaticUtils.EOL_BYTES);
230    }
231
232    TEST_READER = new BufferedReader(new InputStreamReader(
233         new ByteArrayInputStream(buffer.toByteArray())));
234  }
235
236
237
238  /**
239   * Specifies the input stream from which to read the password.  This should
240   * only be set when running unit tests, and this method should be called
241   * again with a value of {@code null} before the end of the test to ensure
242   * that the password reader is reverted back to its normal behavior.
243   *
244   * @param  reader  The input stream from which to read the password.  It may
245   *                 be {@code null} to obtain the password from the normal
246   *                 means.
247   */
248  @InternalUseOnly()
249  public static void setTestReader(@Nullable final BufferedReader reader)
250  {
251    TEST_READER = reader;
252  }
253
254
255
256  /**
257   * Sets the default value that should be used for the environment variable if
258   * it is not set.  This is only intended for use in testing purposes.
259   *
260   * @param  value  The default value that should be used for the environment
261   *                variable if it is not set.  It may be {@code null} if the
262   *                environment variable should be treated as unset.
263   */
264  @InternalUseOnly()
265  static void setDefaultEnvironmentVariableValue(@Nullable final String value)
266  {
267    DEFAULT_ENVIRONMENT_VARIABLE_VALUE = value;
268  }
269}