001/* 002 * Copyright 2010-2019 Ping Identity Corporation 003 * All Rights Reserved. 004 */ 005/* 006 * Copyright (C) 2010-2019 Ping Identity Corporation 007 * 008 * This program is free software; you can redistribute it and/or modify 009 * it under the terms of the GNU General Public License (GPLv2 only) 010 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only) 011 * as published by the Free Software Foundation. 012 * 013 * This program is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU General Public License for more details. 017 * 018 * You should have received a copy of the GNU General Public License 019 * along with this program; if not, see <http://www.gnu.org/licenses>. 020 */ 021package com.unboundid.ldap.sdk.examples; 022 023 024 025import java.io.File; 026import java.io.IOException; 027import java.io.OutputStream; 028import java.io.Serializable; 029import java.util.LinkedHashMap; 030import java.util.logging.ConsoleHandler; 031import java.util.logging.FileHandler; 032import java.util.logging.Handler; 033import java.util.logging.Level; 034 035import com.unboundid.ldap.listener.LDAPDebuggerRequestHandler; 036import com.unboundid.ldap.listener.LDAPListenerRequestHandler; 037import com.unboundid.ldap.listener.LDAPListener; 038import com.unboundid.ldap.listener.LDAPListenerConfig; 039import com.unboundid.ldap.listener.ProxyRequestHandler; 040import com.unboundid.ldap.listener.SelfSignedCertificateGenerator; 041import com.unboundid.ldap.listener.ToCodeRequestHandler; 042import com.unboundid.ldap.sdk.LDAPConnectionOptions; 043import com.unboundid.ldap.sdk.LDAPException; 044import com.unboundid.ldap.sdk.ResultCode; 045import com.unboundid.ldap.sdk.Version; 046import com.unboundid.util.Debug; 047import com.unboundid.util.LDAPCommandLineTool; 048import com.unboundid.util.MinimalLogFormatter; 049import com.unboundid.util.ObjectPair; 050import com.unboundid.util.StaticUtils; 051import com.unboundid.util.ThreadSafety; 052import com.unboundid.util.ThreadSafetyLevel; 053import com.unboundid.util.args.Argument; 054import com.unboundid.util.args.ArgumentException; 055import com.unboundid.util.args.ArgumentParser; 056import com.unboundid.util.args.BooleanArgument; 057import com.unboundid.util.args.FileArgument; 058import com.unboundid.util.args.IntegerArgument; 059import com.unboundid.util.args.StringArgument; 060import com.unboundid.util.ssl.KeyStoreKeyManager; 061import com.unboundid.util.ssl.SSLUtil; 062import com.unboundid.util.ssl.TrustAllTrustManager; 063 064 065 066/** 067 * This class provides a tool that can be used to create a simple listener that 068 * may be used to intercept and decode LDAP requests before forwarding them to 069 * another directory server, and then intercept and decode responses before 070 * returning them to the client. Some of the APIs demonstrated by this example 071 * include: 072 * <UL> 073 * <LI>Argument Parsing (from the {@code com.unboundid.util.args} 074 * package)</LI> 075 * <LI>LDAP Command-Line Tool (from the {@code com.unboundid.util} 076 * package)</LI> 077 * <LI>LDAP Listener API (from the {@code com.unboundid.ldap.listener} 078 * package)</LI> 079 * </UL> 080 * <BR><BR> 081 * All of the necessary information is provided using 082 * command line arguments. Supported arguments include those allowed by the 083 * {@link LDAPCommandLineTool} class, as well as the following additional 084 * arguments: 085 * <UL> 086 * <LI>"-a {address}" or "--listenAddress {address}" -- Specifies the address 087 * on which to listen for requests from clients.</LI> 088 * <LI>"-L {port}" or "--listenPort {port}" -- Specifies the port on which to 089 * listen for requests from clients.</LI> 090 * <LI>"-S" or "--listenUsingSSL" -- Indicates that the listener should 091 * accept connections from SSL-based clients rather than those using 092 * unencrypted LDAP.</LI> 093 * <LI>"-f {path}" or "--outputFile {path}" -- Specifies the path to the 094 * output file to be written. If this is not provided, then the output 095 * will be written to standard output.</LI> 096 * <LI>"-c {path}" or "--codeLogFile {path}" -- Specifies the path to a file 097 * to be written with generated code that corresponds to requests received 098 * from clients. If this is not provided, then no code log will be 099 * generated.</LI> 100 * </UL> 101 */ 102@ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE) 103public final class LDAPDebugger 104 extends LDAPCommandLineTool 105 implements Serializable 106{ 107 /** 108 * The serial version UID for this serializable class. 109 */ 110 private static final long serialVersionUID = -8942937427428190983L; 111 112 113 114 // The argument parser for this tool. 115 private ArgumentParser parser; 116 117 // The argument used to specify the output file for the decoded content. 118 private BooleanArgument listenUsingSSL; 119 120 // The argument used to indicate that the listener should generate a 121 // self-signed certificate instead of using an existing keystore. 122 private BooleanArgument generateSelfSignedCertificate; 123 124 // The argument used to specify the code log file to use, if any. 125 private FileArgument codeLogFile; 126 127 // The argument used to specify the output file for the decoded content. 128 private FileArgument outputFile; 129 130 // The argument used to specify the port on which to listen for client 131 // connections. 132 private IntegerArgument listenPort; 133 134 // The shutdown hook that will be used to stop the listener when the JVM 135 // exits. 136 private LDAPDebuggerShutdownListener shutdownListener; 137 138 // The listener used to intercept and decode the client communication. 139 private LDAPListener listener; 140 141 // The argument used to specify the address on which to listen for client 142 // connections. 143 private StringArgument listenAddress; 144 145 146 147 /** 148 * Parse the provided command line arguments and make the appropriate set of 149 * changes. 150 * 151 * @param args The command line arguments provided to this program. 152 */ 153 public static void main(final String[] args) 154 { 155 final ResultCode resultCode = main(args, System.out, System.err); 156 if (resultCode != ResultCode.SUCCESS) 157 { 158 System.exit(resultCode.intValue()); 159 } 160 } 161 162 163 164 /** 165 * Parse the provided command line arguments and make the appropriate set of 166 * changes. 167 * 168 * @param args The command line arguments provided to this program. 169 * @param outStream The output stream to which standard out should be 170 * written. It may be {@code null} if output should be 171 * suppressed. 172 * @param errStream The output stream to which standard error should be 173 * written. It may be {@code null} if error messages 174 * should be suppressed. 175 * 176 * @return A result code indicating whether the processing was successful. 177 */ 178 public static ResultCode main(final String[] args, 179 final OutputStream outStream, 180 final OutputStream errStream) 181 { 182 final LDAPDebugger ldapDebugger = new LDAPDebugger(outStream, errStream); 183 return ldapDebugger.runTool(args); 184 } 185 186 187 188 /** 189 * Creates a new instance of this tool. 190 * 191 * @param outStream The output stream to which standard out should be 192 * written. It may be {@code null} if output should be 193 * suppressed. 194 * @param errStream The output stream to which standard error should be 195 * written. It may be {@code null} if error messages 196 * should be suppressed. 197 */ 198 public LDAPDebugger(final OutputStream outStream, 199 final OutputStream errStream) 200 { 201 super(outStream, errStream); 202 } 203 204 205 206 /** 207 * Retrieves the name for this tool. 208 * 209 * @return The name for this tool. 210 */ 211 @Override() 212 public String getToolName() 213 { 214 return "ldap-debugger"; 215 } 216 217 218 219 /** 220 * Retrieves the description for this tool. 221 * 222 * @return The description for this tool. 223 */ 224 @Override() 225 public String getToolDescription() 226 { 227 return "Intercept and decode LDAP communication."; 228 } 229 230 231 232 /** 233 * Retrieves the version string for this tool. 234 * 235 * @return The version string for this tool. 236 */ 237 @Override() 238 public String getToolVersion() 239 { 240 return Version.NUMERIC_VERSION_STRING; 241 } 242 243 244 245 /** 246 * Indicates whether this tool should provide support for an interactive mode, 247 * in which the tool offers a mode in which the arguments can be provided in 248 * a text-driven menu rather than requiring them to be given on the command 249 * line. If interactive mode is supported, it may be invoked using the 250 * "--interactive" argument. Alternately, if interactive mode is supported 251 * and {@link #defaultsToInteractiveMode()} returns {@code true}, then 252 * interactive mode may be invoked by simply launching the tool without any 253 * arguments. 254 * 255 * @return {@code true} if this tool supports interactive mode, or 256 * {@code false} if not. 257 */ 258 @Override() 259 public boolean supportsInteractiveMode() 260 { 261 return true; 262 } 263 264 265 266 /** 267 * Indicates whether this tool defaults to launching in interactive mode if 268 * the tool is invoked without any command-line arguments. This will only be 269 * used if {@link #supportsInteractiveMode()} returns {@code true}. 270 * 271 * @return {@code true} if this tool defaults to using interactive mode if 272 * launched without any command-line arguments, or {@code false} if 273 * not. 274 */ 275 @Override() 276 public boolean defaultsToInteractiveMode() 277 { 278 return true; 279 } 280 281 282 283 /** 284 * Indicates whether this tool should default to interactively prompting for 285 * the bind password if a password is required but no argument was provided 286 * to indicate how to get the password. 287 * 288 * @return {@code true} if this tool should default to interactively 289 * prompting for the bind password, or {@code false} if not. 290 */ 291 @Override() 292 protected boolean defaultToPromptForBindPassword() 293 { 294 return true; 295 } 296 297 298 299 /** 300 * Indicates whether this tool supports the use of a properties file for 301 * specifying default values for arguments that aren't specified on the 302 * command line. 303 * 304 * @return {@code true} if this tool supports the use of a properties file 305 * for specifying default values for arguments that aren't specified 306 * on the command line, or {@code false} if not. 307 */ 308 @Override() 309 public boolean supportsPropertiesFile() 310 { 311 return true; 312 } 313 314 315 316 /** 317 * Indicates whether the LDAP-specific arguments should include alternate 318 * versions of all long identifiers that consist of multiple words so that 319 * they are available in both camelCase and dash-separated versions. 320 * 321 * @return {@code true} if this tool should provide multiple versions of 322 * long identifiers for LDAP-specific arguments, or {@code false} if 323 * not. 324 */ 325 @Override() 326 protected boolean includeAlternateLongIdentifiers() 327 { 328 return true; 329 } 330 331 332 333 /** 334 * Adds the arguments used by this program that aren't already provided by the 335 * generic {@code LDAPCommandLineTool} framework. 336 * 337 * @param parser The argument parser to which the arguments should be added. 338 * 339 * @throws ArgumentException If a problem occurs while adding the arguments. 340 */ 341 @Override() 342 public void addNonLDAPArguments(final ArgumentParser parser) 343 throws ArgumentException 344 { 345 this.parser = parser; 346 347 String description = "The address on which to listen for client " + 348 "connections. If this is not provided, then it will listen on " + 349 "all interfaces."; 350 listenAddress = new StringArgument('a', "listenAddress", false, 1, 351 "{address}", description); 352 listenAddress.addLongIdentifier("listen-address", true); 353 parser.addArgument(listenAddress); 354 355 356 description = "The port on which to listen for client connections. If " + 357 "no value is provided, then a free port will be automatically " + 358 "selected."; 359 listenPort = new IntegerArgument('L', "listenPort", true, 1, "{port}", 360 description, 0, 65_535, 0); 361 listenPort.addLongIdentifier("listen-port", true); 362 parser.addArgument(listenPort); 363 364 365 description = "Use SSL when accepting client connections. This is " + 366 "independent of the '--useSSL' option, which applies only to " + 367 "communication between the LDAP debugger and the backend server. " + 368 "If this argument is provided, then either the --keyStorePath or " + 369 "the --generateSelfSignedCertificate argument must also be provided."; 370 listenUsingSSL = new BooleanArgument('S', "listenUsingSSL", 1, 371 description); 372 listenUsingSSL.addLongIdentifier("listen-using-ssl", true); 373 parser.addArgument(listenUsingSSL); 374 375 376 description = "Generate a self-signed certificate to present to clients " + 377 "when the --listenUsingSSL argument is provided. This argument " + 378 "cannot be used in conjunction with the --keyStorePath argument."; 379 generateSelfSignedCertificate = new BooleanArgument(null, 380 "generateSelfSignedCertificate", 1, description); 381 generateSelfSignedCertificate.addLongIdentifier( 382 "generate-self-signed-certificate", true); 383 parser.addArgument(generateSelfSignedCertificate); 384 385 386 description = "The path to the output file to be written. If no value " + 387 "is provided, then the output will be written to standard output."; 388 outputFile = new FileArgument('f', "outputFile", false, 1, "{path}", 389 description, false, true, true, false); 390 outputFile.addLongIdentifier("output-file", true); 391 parser.addArgument(outputFile); 392 393 394 description = "The path to the a code log file to be written. If a " + 395 "value is provided, then the tool will generate sample code that " + 396 "corresponds to the requests received from clients. If no value is " + 397 "provided, then no code log will be generated."; 398 codeLogFile = new FileArgument('c', "codeLogFile", false, 1, "{path}", 399 description, false, true, true, false); 400 codeLogFile.addLongIdentifier("code-log-file", true); 401 parser.addArgument(codeLogFile); 402 403 404 // If --listenUsingSSL is provided, then either the --keyStorePath argument 405 // or the --generateSelfSignedCertificate argument must also be provided. 406 final Argument keyStorePathArgument = 407 parser.getNamedArgument("keyStorePath"); 408 parser.addDependentArgumentSet(listenUsingSSL, keyStorePathArgument, 409 generateSelfSignedCertificate); 410 411 412 // The --generateSelfSignedCertificate argument cannot be used with any of 413 // the arguments pertaining to a key store path. 414 final Argument keyStorePasswordArgument = 415 parser.getNamedArgument("keyStorePassword"); 416 final Argument keyStorePasswordFileArgument = 417 parser.getNamedArgument("keyStorePasswordFile"); 418 final Argument promptForKeyStorePasswordArgument = 419 parser.getNamedArgument("promptForKeyStorePassword"); 420 parser.addExclusiveArgumentSet(generateSelfSignedCertificate, 421 keyStorePathArgument); 422 parser.addExclusiveArgumentSet(generateSelfSignedCertificate, 423 keyStorePasswordArgument); 424 parser.addExclusiveArgumentSet(generateSelfSignedCertificate, 425 keyStorePasswordFileArgument); 426 parser.addExclusiveArgumentSet(generateSelfSignedCertificate, 427 promptForKeyStorePasswordArgument); 428 } 429 430 431 432 /** 433 * Performs the actual processing for this tool. In this case, it gets a 434 * connection to the directory server and uses it to perform the requested 435 * search. 436 * 437 * @return The result code for the processing that was performed. 438 */ 439 @Override() 440 public ResultCode doToolProcessing() 441 { 442 // Create the proxy request handler that will be used to forward requests to 443 // a remote directory. 444 final ProxyRequestHandler proxyHandler; 445 try 446 { 447 proxyHandler = new ProxyRequestHandler(createServerSet()); 448 } 449 catch (final LDAPException le) 450 { 451 err("Unable to prepare to connect to the target server: ", 452 le.getMessage()); 453 return le.getResultCode(); 454 } 455 456 457 // Create the log handler to use for the output. 458 final Handler logHandler; 459 if (outputFile.isPresent()) 460 { 461 try 462 { 463 logHandler = new FileHandler(outputFile.getValue().getAbsolutePath()); 464 } 465 catch (final IOException ioe) 466 { 467 err("Unable to open the output file for writing: ", 468 StaticUtils.getExceptionMessage(ioe)); 469 return ResultCode.LOCAL_ERROR; 470 } 471 } 472 else 473 { 474 logHandler = new ConsoleHandler(); 475 } 476 logHandler.setLevel(Level.INFO); 477 logHandler.setFormatter(new MinimalLogFormatter( 478 MinimalLogFormatter.DEFAULT_TIMESTAMP_FORMAT, false, false, true)); 479 480 481 // Create the debugger request handler that will be used to write the 482 // debug output. 483 LDAPListenerRequestHandler requestHandler = 484 new LDAPDebuggerRequestHandler(logHandler, proxyHandler); 485 486 487 // If a code log file was specified, then create the appropriate request 488 // handler to accomplish that. 489 if (codeLogFile.isPresent()) 490 { 491 try 492 { 493 requestHandler = new ToCodeRequestHandler(codeLogFile.getValue(), true, 494 requestHandler); 495 } 496 catch (final Exception e) 497 { 498 err("Unable to open code log file '", 499 codeLogFile.getValue().getAbsolutePath(), "' for writing: ", 500 StaticUtils.getExceptionMessage(e)); 501 return ResultCode.LOCAL_ERROR; 502 } 503 } 504 505 506 // Create and start the LDAP listener. 507 final LDAPListenerConfig config = 508 new LDAPListenerConfig(listenPort.getValue(), requestHandler); 509 if (listenAddress.isPresent()) 510 { 511 try 512 { 513 config.setListenAddress(LDAPConnectionOptions.DEFAULT_NAME_RESOLVER. 514 getByName(listenAddress.getValue())); 515 } 516 catch (final Exception e) 517 { 518 err("Unable to resolve '", listenAddress.getValue(), 519 "' as a valid address: ", StaticUtils.getExceptionMessage(e)); 520 return ResultCode.PARAM_ERROR; 521 } 522 } 523 524 if (listenUsingSSL.isPresent()) 525 { 526 try 527 { 528 final SSLUtil sslUtil; 529 if (generateSelfSignedCertificate.isPresent()) 530 { 531 final ObjectPair<File,char[]> keyStoreInfo = 532 SelfSignedCertificateGenerator. 533 generateTemporarySelfSignedCertificate(getToolName(), 534 "JKS"); 535 536 sslUtil = new SSLUtil( 537 new KeyStoreKeyManager(keyStoreInfo.getFirst(), 538 keyStoreInfo.getSecond(), "JKS", null), 539 new TrustAllTrustManager(false)); 540 } 541 else 542 { 543 sslUtil = createSSLUtil(true); 544 } 545 546 config.setServerSocketFactory(sslUtil.createSSLServerSocketFactory()); 547 } 548 catch (final Exception e) 549 { 550 err("Unable to create a server socket factory to accept SSL-based " + 551 "client connections: ", StaticUtils.getExceptionMessage(e)); 552 return ResultCode.LOCAL_ERROR; 553 } 554 } 555 556 listener = new LDAPListener(config); 557 558 try 559 { 560 listener.startListening(); 561 } 562 catch (final Exception e) 563 { 564 err("Unable to start listening for client connections: ", 565 StaticUtils.getExceptionMessage(e)); 566 return ResultCode.LOCAL_ERROR; 567 } 568 569 570 // Display a message with information about the port on which it is 571 // listening for connections. 572 int port = listener.getListenPort(); 573 while (port <= 0) 574 { 575 try 576 { 577 Thread.sleep(1L); 578 } 579 catch (final Exception e) 580 { 581 Debug.debugException(e); 582 583 if (e instanceof InterruptedException) 584 { 585 Thread.currentThread().interrupt(); 586 } 587 } 588 589 port = listener.getListenPort(); 590 } 591 592 if (listenUsingSSL.isPresent()) 593 { 594 out("Listening for SSL-based LDAP client connections on port ", port); 595 } 596 else 597 { 598 out("Listening for LDAP client connections on port ", port); 599 } 600 601 // Note that at this point, the listener will continue running in a 602 // separate thread, so we can return from this thread without exiting the 603 // program. However, we'll want to register a shutdown hook so that we can 604 // close the logger. 605 shutdownListener = new LDAPDebuggerShutdownListener(listener, logHandler); 606 Runtime.getRuntime().addShutdownHook(shutdownListener); 607 608 return ResultCode.SUCCESS; 609 } 610 611 612 613 /** 614 * {@inheritDoc} 615 */ 616 @Override() 617 public LinkedHashMap<String[],String> getExampleUsages() 618 { 619 final LinkedHashMap<String[],String> examples = 620 new LinkedHashMap<>(StaticUtils.computeMapCapacity(1)); 621 622 final String[] args = 623 { 624 "--hostname", "server.example.com", 625 "--port", "389", 626 "--listenPort", "1389", 627 "--outputFile", "/tmp/ldap-debugger.log" 628 }; 629 final String description = 630 "Listen for client connections on port 1389 on all interfaces and " + 631 "forward any traffic received to server.example.com:389. The " + 632 "decoded LDAP communication will be written to the " + 633 "/tmp/ldap-debugger.log log file."; 634 examples.put(args, description); 635 636 return examples; 637 } 638 639 640 641 /** 642 * Retrieves the LDAP listener used to decode the communication. 643 * 644 * @return The LDAP listener used to decode the communication, or 645 * {@code null} if the tool is not running. 646 */ 647 public LDAPListener getListener() 648 { 649 return listener; 650 } 651 652 653 654 /** 655 * Indicates that the associated listener should shut down. 656 */ 657 public void shutDown() 658 { 659 Runtime.getRuntime().removeShutdownHook(shutdownListener); 660 shutdownListener.run(); 661 } 662}