001/* 002 * Copyright 2007-2022 Ping Identity Corporation 003 * All Rights Reserved. 004 */ 005/* 006 * Copyright 2007-2022 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-2022 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 unhandledCallbackMessages.clear(); 340 341 final SaslClient saslClient; 342 343 try 344 { 345 final String[] mechanisms = { CRAMMD5_MECHANISM_NAME }; 346 saslClient = Sasl.createSaslClient(mechanisms, null, "ldap", 347 connection.getConnectedAddress(), null, 348 this); 349 } 350 catch (final Exception e) 351 { 352 Debug.debugException(e); 353 throw new LDAPException(ResultCode.LOCAL_ERROR, 354 ERR_CRAMMD5_CANNOT_CREATE_SASL_CLIENT.get( 355 StaticUtils.getExceptionMessage(e)), 356 e); 357 } 358 359 final SASLClientBindHandler bindHandler = new SASLClientBindHandler(this, 360 connection, CRAMMD5_MECHANISM_NAME, saslClient, getControls(), 361 getResponseTimeoutMillis(connection), unhandledCallbackMessages); 362 363 try 364 { 365 return bindHandler.processSASLBind(); 366 } 367 finally 368 { 369 messageID = bindHandler.getMessageID(); 370 } 371 } 372 373 374 375 /** 376 * {@inheritDoc} 377 */ 378 @Override() 379 @NotNull() 380 public CRAMMD5BindRequest getRebindRequest(@NotNull final String host, 381 final int port) 382 { 383 return new CRAMMD5BindRequest(authenticationID, password, getControls()); 384 } 385 386 387 388 /** 389 * Handles any necessary callbacks required for SASL authentication. 390 * 391 * @param callbacks The set of callbacks to be handled. 392 */ 393 @InternalUseOnly() 394 @Override() 395 public void handle(@NotNull final Callback[] callbacks) 396 { 397 for (final Callback callback : callbacks) 398 { 399 if (callback instanceof NameCallback) 400 { 401 ((NameCallback) callback).setName(authenticationID); 402 } 403 else if (callback instanceof PasswordCallback) 404 { 405 ((PasswordCallback) callback).setPassword( 406 password.stringValue().toCharArray()); 407 } 408 else 409 { 410 // This is an unexpected callback. 411 if (Debug.debugEnabled(DebugType.LDAP)) 412 { 413 Debug.debug(Level.WARNING, DebugType.LDAP, 414 "Unexpected CRAM-MD5 SASL callback of type " + 415 callback.getClass().getName()); 416 } 417 418 unhandledCallbackMessages.add(ERR_CRAMMD5_UNEXPECTED_CALLBACK.get( 419 callback.getClass().getName())); 420 } 421 } 422 } 423 424 425 426 /** 427 * {@inheritDoc} 428 */ 429 @Override() 430 public int getLastMessageID() 431 { 432 return messageID; 433 } 434 435 436 437 /** 438 * {@inheritDoc} 439 */ 440 @Override() 441 @NotNull() 442 public CRAMMD5BindRequest duplicate() 443 { 444 return duplicate(getControls()); 445 } 446 447 448 449 /** 450 * {@inheritDoc} 451 */ 452 @Override() 453 @NotNull() 454 public CRAMMD5BindRequest duplicate(@Nullable final Control[] controls) 455 { 456 final CRAMMD5BindRequest bindRequest = 457 new CRAMMD5BindRequest(authenticationID, password, controls); 458 bindRequest.setResponseTimeoutMillis(getResponseTimeoutMillis(null)); 459 return bindRequest; 460 } 461 462 463 464 /** 465 * {@inheritDoc} 466 */ 467 @Override() 468 public void toString(@NotNull final StringBuilder buffer) 469 { 470 buffer.append("CRAMMD5BindRequest(authenticationID='"); 471 buffer.append(authenticationID); 472 buffer.append('\''); 473 474 final Control[] controls = getControls(); 475 if (controls.length > 0) 476 { 477 buffer.append(", controls={"); 478 for (int i=0; i < controls.length; i++) 479 { 480 if (i > 0) 481 { 482 buffer.append(", "); 483 } 484 485 buffer.append(controls[i]); 486 } 487 buffer.append('}'); 488 } 489 490 buffer.append(')'); 491 } 492 493 494 495 /** 496 * {@inheritDoc} 497 */ 498 @Override() 499 public void toCode(@NotNull final List<String> lineList, 500 @NotNull final String requestID, 501 final int indentSpaces, final boolean includeProcessing) 502 { 503 // Create the request variable. 504 final ArrayList<ToCodeArgHelper> constructorArgs = new ArrayList<>(3); 505 constructorArgs.add(ToCodeArgHelper.createString(authenticationID, 506 "Authentication ID")); 507 constructorArgs.add(ToCodeArgHelper.createString("---redacted-password---", 508 "Bind Password")); 509 510 final Control[] controls = getControls(); 511 if (controls.length > 0) 512 { 513 constructorArgs.add(ToCodeArgHelper.createControlArray(controls, 514 "Bind Controls")); 515 } 516 517 ToCodeHelper.generateMethodCall(lineList, indentSpaces, 518 "CRAMMD5BindRequest", requestID + "Request", 519 "new CRAMMD5BindRequest", constructorArgs); 520 521 522 // Add lines for processing the request and obtaining the result. 523 if (includeProcessing) 524 { 525 // Generate a string with the appropriate indent. 526 final StringBuilder buffer = new StringBuilder(); 527 for (int i=0; i < indentSpaces; i++) 528 { 529 buffer.append(' '); 530 } 531 final String indent = buffer.toString(); 532 533 lineList.add(""); 534 lineList.add(indent + "try"); 535 lineList.add(indent + '{'); 536 lineList.add(indent + " BindResult " + requestID + 537 "Result = connection.bind(" + requestID + "Request);"); 538 lineList.add(indent + " // The bind was processed successfully."); 539 lineList.add(indent + '}'); 540 lineList.add(indent + "catch (LDAPException e)"); 541 lineList.add(indent + '{'); 542 lineList.add(indent + " // The bind failed. Maybe the following will " + 543 "help explain why."); 544 lineList.add(indent + " // Note that the connection is now likely in " + 545 "an unauthenticated state."); 546 lineList.add(indent + " ResultCode resultCode = e.getResultCode();"); 547 lineList.add(indent + " String message = e.getMessage();"); 548 lineList.add(indent + " String matchedDN = e.getMatchedDN();"); 549 lineList.add(indent + " String[] referralURLs = e.getReferralURLs();"); 550 lineList.add(indent + " Control[] responseControls = " + 551 "e.getResponseControls();"); 552 lineList.add(indent + '}'); 553 } 554 } 555}