001/*
002 * Copyright 2007-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2007-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) 2007-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.ldap.sdk;
037
038
039
040import java.util.ArrayList;
041import java.util.List;
042import java.util.logging.Level;
043import javax.security.auth.callback.Callback;
044import javax.security.auth.callback.CallbackHandler;
045import javax.security.auth.callback.NameCallback;
046import javax.security.auth.callback.PasswordCallback;
047import javax.security.sasl.Sasl;
048import javax.security.sasl.SaslClient;
049
050import com.unboundid.asn1.ASN1OctetString;
051import com.unboundid.util.Debug;
052import com.unboundid.util.DebugType;
053import com.unboundid.util.InternalUseOnly;
054import com.unboundid.util.NotMutable;
055import com.unboundid.util.NotNull;
056import com.unboundid.util.Nullable;
057import com.unboundid.util.StaticUtils;
058import com.unboundid.util.ThreadSafety;
059import com.unboundid.util.ThreadSafetyLevel;
060import com.unboundid.util.Validator;
061
062import static com.unboundid.ldap.sdk.LDAPMessages.*;
063
064
065
066/**
067 * This class provides a SASL CRAM-MD5 bind request implementation as described
068 * in draft-ietf-sasl-crammd5.  The CRAM-MD5 mechanism can be used to
069 * authenticate over an insecure channel without exposing the credentials
070 * (although it requires that the server have access to the clear-text
071 * password).    It is similar to DIGEST-MD5, but does not provide as many
072 * options, and provides slightly weaker protection because the client does not
073 * contribute any of the random data used during bind processing.
074 * <BR><BR>
075 * Elements included in a CRAM-MD5 bind request include:
076 * <UL>
077 *   <LI>Authentication ID -- A string which identifies the user that is
078 *       attempting to authenticate.  It should be an "authzId" value as
079 *       described in section 5.2.1.8 of
080 *       <A HREF="http://www.ietf.org/rfc/rfc4513.txt">RFC 4513</A>.  That is,
081 *       it should be either "dn:" followed by the distinguished name of the
082 *       target user, or "u:" followed by the username.  If the "u:" form is
083 *       used, then the mechanism used to resolve the provided username to an
084 *       entry may vary from server to server.</LI>
085 *   <LI>Password -- The clear-text password for the target user.</LI>
086 * </UL>
087 * <H2>Example</H2>
088 * The following example demonstrates the process for performing a CRAM-MD5
089 * bind against a directory server with a username of "john.doe" and a password
090 * of "password":
091 * <PRE>
092 * CRAMMD5BindRequest bindRequest =
093 *      new CRAMMD5BindRequest("u:john.doe", "password");
094 * BindResult bindResult;
095 * try
096 * {
097 *   bindResult = connection.bind(bindRequest);
098 *   // If we get here, then the bind was successful.
099 * }
100 * catch (LDAPException le)
101 * {
102 *   // The bind failed for some reason.
103 *   bindResult = new BindResult(le.toLDAPResult());
104 *   ResultCode resultCode = le.getResultCode();
105 *   String errorMessageFromServer = le.getDiagnosticMessage();
106 * }
107 * </PRE>
108 */
109@NotMutable()
110@ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE)
111public final class CRAMMD5BindRequest
112       extends SASLBindRequest
113       implements CallbackHandler
114{
115  /**
116   * The name for the CRAM-MD5 SASL mechanism.
117   */
118  @NotNull public static final String CRAMMD5_MECHANISM_NAME = "CRAM-MD5";
119
120
121
122  /**
123   * The serial version UID for this serializable class.
124   */
125  private static final long serialVersionUID = -4556570436768136483L;
126
127
128
129  // The password for this bind request.
130  @NotNull private final ASN1OctetString password;
131
132  // The message ID from the last LDAP message sent from this request.
133  private int messageID = -1;
134
135  // A list that will be updated with messages about any unhandled callbacks
136  // encountered during processing.
137  @NotNull private final List<String> unhandledCallbackMessages;
138
139  // The authentication ID string for this bind request.
140  @NotNull private final String authenticationID;
141
142
143
144  /**
145   * Creates a new SASL CRAM-MD5 bind request with the provided authentication
146   * ID and password.  It will not include any controls.
147   *
148   * @param  authenticationID  The authentication ID for this bind request.  It
149   *                           must not be {@code null}.
150   * @param  password          The password for this bind request.  It must not
151   *                           be {@code null}.
152   */
153  public CRAMMD5BindRequest(@NotNull final String authenticationID,
154                            @NotNull final String password)
155  {
156    this(authenticationID, new ASN1OctetString(password), NO_CONTROLS);
157
158    Validator.ensureNotNull(password);
159  }
160
161
162
163  /**
164   * Creates a new SASL CRAM-MD5 bind request with the provided authentication
165   * ID and password.  It will not include any controls.
166   *
167   * @param  authenticationID  The authentication ID for this bind request.  It
168   *                           must not be {@code null}.
169   * @param  password          The password for this bind request.  It must not
170   *                           be {@code null}.
171   */
172  public CRAMMD5BindRequest(@NotNull final String authenticationID,
173                            @NotNull final byte[] password)
174  {
175    this(authenticationID, new ASN1OctetString(password), NO_CONTROLS);
176
177    Validator.ensureNotNull(password);
178  }
179
180
181
182  /**
183   * Creates a new SASL CRAM-MD5 bind request with the provided authentication
184   * ID and password.  It will not include any controls.
185   *
186   * @param  authenticationID  The authentication ID for this bind request.  It
187   *                           must not be {@code null}.
188   * @param  password          The password for this bind request.  It must not
189   *                           be {@code null}.
190   */
191  public CRAMMD5BindRequest(@NotNull final String authenticationID,
192                            @NotNull final ASN1OctetString password)
193  {
194    this(authenticationID, password, NO_CONTROLS);
195  }
196
197
198
199  /**
200   * Creates a new SASL CRAM-MD5 bind request with the provided authentication
201   * ID, password, and set of controls.
202   *
203   * @param  authenticationID  The authentication ID for this bind request.  It
204   *                           must not be {@code null}.
205   * @param  password          The password for this bind request.  It must not
206   *                           be {@code null}.
207   * @param  controls          The set of controls to include in the request.
208   */
209  public CRAMMD5BindRequest(@NotNull final String authenticationID,
210                            @NotNull final String password,
211                            @Nullable final Control... controls)
212  {
213    this(authenticationID, new ASN1OctetString(password), controls);
214
215    Validator.ensureNotNull(password);
216  }
217
218
219
220  /**
221   * Creates a new SASL CRAM-MD5 bind request with the provided authentication
222   * ID, password, and set of controls.
223   *
224   * @param  authenticationID  The authentication ID for this bind request.  It
225   *                           must not be {@code null}.
226   * @param  password          The password for this bind request.  It must not
227   *                           be {@code null}.
228   * @param  controls          The set of controls to include in the request.
229   */
230  public CRAMMD5BindRequest(@NotNull final String authenticationID,
231                            @NotNull final byte[] password,
232                            @Nullable final Control... controls)
233  {
234    this(authenticationID, new ASN1OctetString(password), controls);
235
236    Validator.ensureNotNull(password);
237  }
238
239
240
241  /**
242   * Creates a new SASL CRAM-MD5 bind request with the provided authentication
243   * ID, password, and set of controls.
244   *
245   * @param  authenticationID  The authentication ID for this bind request.  It
246   *                           must not be {@code null}.
247   * @param  password          The password for this bind request.  It must not
248   *                           be {@code null}.
249   * @param  controls          The set of controls to include in the request.
250   */
251  public CRAMMD5BindRequest(@NotNull final String authenticationID,
252                            @NotNull final ASN1OctetString password,
253                            @Nullable final Control... controls)
254  {
255    super(controls);
256
257    Validator.ensureNotNull(authenticationID, password);
258
259    this.authenticationID = authenticationID;
260    this.password         = password;
261
262    unhandledCallbackMessages = new ArrayList<>(5);
263  }
264
265
266
267  /**
268   * {@inheritDoc}
269   */
270  @Override()
271  @NotNull()
272  public String getSASLMechanismName()
273  {
274    return CRAMMD5_MECHANISM_NAME;
275  }
276
277
278
279  /**
280   * Retrieves the authentication ID for this bind request.
281   *
282   * @return  The authentication ID for this bind request.
283   */
284  @NotNull()
285  public String getAuthenticationID()
286  {
287    return authenticationID;
288  }
289
290
291
292  /**
293   * Retrieves the string representation of the password for this bind request.
294   *
295   * @return  The string representation of the password for this bind request.
296   */
297  @NotNull()
298  public String getPasswordString()
299  {
300    return password.stringValue();
301  }
302
303
304
305  /**
306   * Retrieves the bytes that comprise the the password for this bind request.
307   *
308   * @return  The bytes that comprise the password for this bind request.
309   */
310  @NotNull()
311  public byte[] getPasswordBytes()
312  {
313    return password.getValue();
314  }
315
316
317
318  /**
319   * Sends this bind request to the target server over the provided connection
320   * and returns the corresponding response.
321   *
322   * @param  connection  The connection to use to send this bind request to the
323   *                     server and read the associated response.
324   * @param  depth       The current referral depth for this request.  It should
325   *                     always be one for the initial request, and should only
326   *                     be incremented when following referrals.
327   *
328   * @return  The bind response read from the server.
329   *
330   * @throws  LDAPException  If a problem occurs while sending the request or
331   *                         reading the response.
332   */
333  @Override()
334  @NotNull ()
335  protected BindResult process(@NotNull final LDAPConnection connection,
336                               final int depth)
337            throws LDAPException
338  {
339    setReferralDepth(depth);
340
341    unhandledCallbackMessages.clear();
342
343    final SaslClient saslClient;
344
345    try
346    {
347      final String[] mechanisms = { CRAMMD5_MECHANISM_NAME };
348      saslClient = Sasl.createSaslClient(mechanisms, null, "ldap",
349                                         connection.getConnectedAddress(), null,
350                                         this);
351    }
352    catch (final Exception e)
353    {
354      Debug.debugException(e);
355      throw new LDAPException(ResultCode.LOCAL_ERROR,
356           ERR_CRAMMD5_CANNOT_CREATE_SASL_CLIENT.get(
357                StaticUtils.getExceptionMessage(e)),
358           e);
359    }
360
361    final SASLClientBindHandler bindHandler = new SASLClientBindHandler(this,
362         connection, CRAMMD5_MECHANISM_NAME, saslClient, getControls(),
363         getResponseTimeoutMillis(connection), unhandledCallbackMessages);
364
365    try
366    {
367      return bindHandler.processSASLBind();
368    }
369    finally
370    {
371      messageID = bindHandler.getMessageID();
372    }
373  }
374
375
376
377  /**
378   * {@inheritDoc}
379   */
380  @Override()
381  @NotNull()
382  public CRAMMD5BindRequest getRebindRequest(@NotNull final String host,
383                                             final int port)
384  {
385    return new CRAMMD5BindRequest(authenticationID, password, getControls());
386  }
387
388
389
390  /**
391   * Handles any necessary callbacks required for SASL authentication.
392   *
393   * @param  callbacks  The set of callbacks to be handled.
394   */
395  @InternalUseOnly()
396  @Override()
397  public void handle(@NotNull final Callback[] callbacks)
398  {
399    for (final Callback callback : callbacks)
400    {
401      if (callback instanceof NameCallback)
402      {
403        ((NameCallback) callback).setName(authenticationID);
404      }
405      else if (callback instanceof PasswordCallback)
406      {
407        ((PasswordCallback) callback).setPassword(
408             password.stringValue().toCharArray());
409      }
410      else
411      {
412        // This is an unexpected callback.
413        if (Debug.debugEnabled(DebugType.LDAP))
414        {
415          Debug.debug(Level.WARNING, DebugType.LDAP,
416               "Unexpected CRAM-MD5 SASL callback of type " +
417                    callback.getClass().getName());
418        }
419
420        unhandledCallbackMessages.add(ERR_CRAMMD5_UNEXPECTED_CALLBACK.get(
421             callback.getClass().getName()));
422      }
423    }
424  }
425
426
427
428  /**
429   * {@inheritDoc}
430   */
431  @Override()
432  public int getLastMessageID()
433  {
434    return messageID;
435  }
436
437
438
439  /**
440   * {@inheritDoc}
441   */
442  @Override()
443  @NotNull()
444  public CRAMMD5BindRequest duplicate()
445  {
446    return duplicate(getControls());
447  }
448
449
450
451  /**
452   * {@inheritDoc}
453   */
454  @Override()
455  @NotNull()
456  public CRAMMD5BindRequest duplicate(@Nullable final Control[] controls)
457  {
458    final CRAMMD5BindRequest bindRequest =
459         new CRAMMD5BindRequest(authenticationID, password, controls);
460    bindRequest.setResponseTimeoutMillis(getResponseTimeoutMillis(null));
461    bindRequest.setIntermediateResponseListener(
462         getIntermediateResponseListener());
463    bindRequest.setReferralDepth(getReferralDepth());
464    bindRequest.setReferralConnector(getReferralConnectorInternal());
465    return bindRequest;
466  }
467
468
469
470  /**
471   * {@inheritDoc}
472   */
473  @Override()
474  public void toString(@NotNull final StringBuilder buffer)
475  {
476    buffer.append("CRAMMD5BindRequest(authenticationID='");
477    buffer.append(authenticationID);
478    buffer.append('\'');
479
480    final Control[] controls = getControls();
481    if (controls.length > 0)
482    {
483      buffer.append(", controls={");
484      for (int i=0; i < controls.length; i++)
485      {
486        if (i > 0)
487        {
488          buffer.append(", ");
489        }
490
491        buffer.append(controls[i]);
492      }
493      buffer.append('}');
494    }
495
496    buffer.append(')');
497  }
498
499
500
501  /**
502   * {@inheritDoc}
503   */
504  @Override()
505  public void toCode(@NotNull final List<String> lineList,
506                     @NotNull final String requestID,
507                     final int indentSpaces, final boolean includeProcessing)
508  {
509    // Create the request variable.
510    final ArrayList<ToCodeArgHelper> constructorArgs = new ArrayList<>(3);
511    constructorArgs.add(ToCodeArgHelper.createString(authenticationID,
512         "Authentication ID"));
513    constructorArgs.add(ToCodeArgHelper.createString("---redacted-password---",
514         "Bind Password"));
515
516    final Control[] controls = getControls();
517    if (controls.length > 0)
518    {
519      constructorArgs.add(ToCodeArgHelper.createControlArray(controls,
520           "Bind Controls"));
521    }
522
523    ToCodeHelper.generateMethodCall(lineList, indentSpaces,
524         "CRAMMD5BindRequest", requestID + "Request",
525         "new CRAMMD5BindRequest", constructorArgs);
526
527
528    // Add lines for processing the request and obtaining the result.
529    if (includeProcessing)
530    {
531      // Generate a string with the appropriate indent.
532      final StringBuilder buffer = new StringBuilder();
533      for (int i=0; i < indentSpaces; i++)
534      {
535        buffer.append(' ');
536      }
537      final String indent = buffer.toString();
538
539      lineList.add("");
540      lineList.add(indent + "try");
541      lineList.add(indent + '{');
542      lineList.add(indent + "  BindResult " + requestID +
543           "Result = connection.bind(" + requestID + "Request);");
544      lineList.add(indent + "  // The bind was processed successfully.");
545      lineList.add(indent + '}');
546      lineList.add(indent + "catch (LDAPException e)");
547      lineList.add(indent + '{');
548      lineList.add(indent + "  // The bind failed.  Maybe the following will " +
549           "help explain why.");
550      lineList.add(indent + "  // Note that the connection is now likely in " +
551           "an unauthenticated state.");
552      lineList.add(indent + "  ResultCode resultCode = e.getResultCode();");
553      lineList.add(indent + "  String message = e.getMessage();");
554      lineList.add(indent + "  String matchedDN = e.getMatchedDN();");
555      lineList.add(indent + "  String[] referralURLs = e.getReferralURLs();");
556      lineList.add(indent + "  Control[] responseControls = " +
557           "e.getResponseControls();");
558      lineList.add(indent + '}');
559    }
560  }
561}