001/** 002 * 003 * Copyright 2003-2007 Jive Software, 2017-2024 Florian Schmaus. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.jivesoftware.smack; 019 020import java.io.ByteArrayInputStream; 021import java.io.FileInputStream; 022import java.io.IOException; 023import java.io.InputStream; 024import java.lang.reflect.Constructor; 025import java.lang.reflect.InvocationTargetException; 026import java.net.InetAddress; 027import java.net.UnknownHostException; 028import java.nio.charset.StandardCharsets; 029import java.security.KeyManagementException; 030import java.security.KeyStore; 031import java.security.KeyStoreException; 032import java.security.NoSuchAlgorithmException; 033import java.security.NoSuchProviderException; 034import java.security.Provider; 035import java.security.SecureRandom; 036import java.security.Security; 037import java.security.UnrecoverableKeyException; 038import java.security.cert.CertificateException; 039import java.util.Arrays; 040import java.util.Collection; 041import java.util.Collections; 042import java.util.HashSet; 043import java.util.Locale; 044import java.util.Set; 045import java.util.logging.Level; 046import java.util.logging.Logger; 047 048import javax.net.SocketFactory; 049import javax.net.ssl.HostnameVerifier; 050import javax.net.ssl.KeyManager; 051import javax.net.ssl.KeyManagerFactory; 052import javax.net.ssl.SSLContext; 053import javax.net.ssl.TrustManager; 054import javax.net.ssl.X509TrustManager; 055import javax.security.auth.callback.Callback; 056import javax.security.auth.callback.CallbackHandler; 057import javax.security.auth.callback.PasswordCallback; 058import javax.security.auth.callback.UnsupportedCallbackException; 059 060import org.jivesoftware.smack.datatypes.UInt16; 061import org.jivesoftware.smack.debugger.SmackDebuggerFactory; 062import org.jivesoftware.smack.internal.SmackTlsContext; 063import org.jivesoftware.smack.packet.id.StandardStanzaIdSource; 064import org.jivesoftware.smack.packet.id.StanzaIdSource; 065import org.jivesoftware.smack.packet.id.StanzaIdSourceFactory; 066import org.jivesoftware.smack.proxy.ProxyInfo; 067import org.jivesoftware.smack.sasl.SASLMechanism; 068import org.jivesoftware.smack.sasl.core.SASLAnonymous; 069import org.jivesoftware.smack.util.CloseableUtil; 070import org.jivesoftware.smack.util.CollectionUtil; 071import org.jivesoftware.smack.util.DNSUtil; 072import org.jivesoftware.smack.util.Objects; 073import org.jivesoftware.smack.util.SslContextFactory; 074import org.jivesoftware.smack.util.StringUtils; 075import org.jivesoftware.smack.util.TLSUtils; 076import org.jivesoftware.smack.util.dns.SmackDaneProvider; 077import org.jivesoftware.smack.util.dns.SmackDaneVerifier; 078 079import org.jxmpp.jid.DomainBareJid; 080import org.jxmpp.jid.EntityBareJid; 081import org.jxmpp.jid.impl.JidCreate; 082import org.jxmpp.jid.parts.Resourcepart; 083import org.jxmpp.stringprep.XmppStringprepException; 084import org.minidns.dnsname.DnsName; 085import org.minidns.dnsname.InvalidDnsNameException; 086import org.minidns.util.InetAddressUtil; 087 088/** 089 * The connection configuration used for XMPP client-to-server connections. A well configured XMPP service will 090 * typically only require you to provide two parameters: The XMPP address, also known as the JID, of the user and the 091 * password. All other configuration parameters could ideally be determined automatically by Smack. Hence, it is often 092 * enough to call {@link Builder#setXmppAddressAndPassword(CharSequence, String)}. 093 * <p> 094 * Technically there are typically at least two parameters required: Some kind of credentials for authentication. And 095 * the XMPP service domain. The credentials often consists of a username and password use for the SASL authentication. 096 * But there are also other authentication mechanisms, like client side certificates, which do not require a particular 097 * username and password. 098 * </p> 099 * <p> 100 * There are some misconceptions about XMPP client-to-server parameters: The first is that the username used for 101 * authentication will be equal to the localpart of the bound XMPP address after authentication. While this is usually 102 * true, it is not required. Technically the username used for authentication and the resulting XMPP address are 103 * completely independent from each other. The second common misconception steers from the terms "XMPP host" and "XMPP 104 * service domain": An XMPP service host is a system which hosts one or multiple XMPP domains. The "XMPP service domain" 105 * will be usually the domainpart of the bound JID. This domain is used to verify the remote endpoint, typically using 106 * TLS. This third misconception is that the XMPP service domain is required to become the domainpart of the bound JID. 107 * Again, while this is very common to be true, it is not strictly required. 108 * </p> 109 * 110 * @author Gaston Dombiak 111 * @author Florian Schmaus 112 */ 113public abstract class ConnectionConfiguration { 114 115 static { 116 Smack.ensureInitialized(); 117 } 118 119 private static final Logger LOGGER = Logger.getLogger(ConnectionConfiguration.class.getName()); 120 121 /** 122 * The XMPP domain of the XMPP Service. Usually servers use the same service name as the name 123 * of the server. However, there are some servers like google where host would be 124 * talk.google.com and the serviceName would be gmail.com. 125 */ 126 protected final DomainBareJid xmppServiceDomain; 127 128 protected final DnsName xmppServiceDomainDnsName; 129 130 protected final InetAddress hostAddress; 131 protected final DnsName host; 132 protected final UInt16 port; 133 134 /** 135 * Used to get information from the user 136 */ 137 private final CallbackHandler callbackHandler; 138 139 private final SmackDebuggerFactory debuggerFactory; 140 141 // Holds the socket factory that is used to generate the socket in the connection 142 private final SocketFactory socketFactory; 143 144 private final CharSequence username; 145 private final String password; 146 private final Resourcepart resource; 147 148 private final Locale language; 149 150 /** 151 * The optional SASL authorization identity (see RFC 6120 § 6.3.8). 152 */ 153 private final EntityBareJid authzid; 154 155 /** 156 * Initial presence as of RFC 6121 § 4.2 157 * @see <a href="http://xmpp.org/rfcs/rfc6121.html#presence-initial">RFC 6121 § 4.2 Initial Presence</a> 158 */ 159 private final boolean sendPresence; 160 161 private final SecurityMode securityMode; 162 163 final SmackTlsContext smackTlsContext; 164 165 private final DnssecMode dnssecMode; 166 167 /** 168 * 169 */ 170 private final String[] enabledSSLProtocols; 171 172 /** 173 * 174 */ 175 private final String[] enabledSSLCiphers; 176 177 private final HostnameVerifier hostnameVerifier; 178 179 // Holds the proxy information (such as proxyhost, proxyport, username, password etc) 180 protected final ProxyInfo proxy; 181 182 protected final boolean allowNullOrEmptyUsername; 183 184 private final Set<String> enabledSaslMechanisms; 185 186 private final boolean compressionEnabled; 187 188 private final StanzaIdSourceFactory stanzaIdSourceFactory; 189 190 protected ConnectionConfiguration(Builder<?, ?> builder) { 191 try { 192 smackTlsContext = getSmackTlsContext(builder.dnssecMode, builder.sslContextFactory, 193 builder.customX509TrustManager, builder.keyManagers, builder.sslContextSecureRandom, builder.keystoreType, builder.keystorePath, 194 builder.callbackHandler, builder.pkcs11Library); 195 } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | CertificateException 196 | KeyStoreException | NoSuchProviderException | IOException | NoSuchMethodException 197 | SecurityException | ClassNotFoundException | InstantiationException | IllegalAccessException 198 | IllegalArgumentException | InvocationTargetException | UnsupportedCallbackException e) { 199 throw new IllegalArgumentException(e); 200 } 201 202 authzid = builder.authzid; 203 username = builder.username; 204 password = builder.password; 205 callbackHandler = builder.callbackHandler; 206 207 // Resource can be null, this means that the server must provide one 208 resource = builder.resource; 209 210 language = builder.language; 211 212 xmppServiceDomain = builder.xmppServiceDomain; 213 if (xmppServiceDomain == null) { 214 throw new IllegalArgumentException("Must define the XMPP domain"); 215 } 216 217 DnsName xmppServiceDomainDnsName; 218 try { 219 xmppServiceDomainDnsName = DnsName.from(xmppServiceDomain); 220 } catch (InvalidDnsNameException e) { 221 LOGGER.log(Level.INFO, 222 "Could not transform XMPP service domain '" + xmppServiceDomain 223 + "' to a DNS name. TLS X.509 certificate validiation may not be possible.", 224 e); 225 xmppServiceDomainDnsName = null; 226 } 227 this.xmppServiceDomainDnsName = xmppServiceDomainDnsName; 228 229 hostAddress = builder.hostAddress; 230 host = builder.host; 231 port = builder.port; 232 233 proxy = builder.proxy; 234 socketFactory = builder.socketFactory; 235 236 dnssecMode = builder.dnssecMode; 237 238 securityMode = builder.securityMode; 239 enabledSSLProtocols = builder.enabledSSLProtocols; 240 enabledSSLCiphers = builder.enabledSSLCiphers; 241 hostnameVerifier = builder.hostnameVerifier; 242 sendPresence = builder.sendPresence; 243 debuggerFactory = builder.debuggerFactory; 244 allowNullOrEmptyUsername = builder.allowEmptyOrNullUsername; 245 enabledSaslMechanisms = builder.enabledSaslMechanisms; 246 247 compressionEnabled = builder.compressionEnabled; 248 249 stanzaIdSourceFactory = builder.stanzaIdSourceFactory; 250 251 // If the enabledSaslMechanisms are set, then they must not be empty 252 assert enabledSaslMechanisms == null || !enabledSaslMechanisms.isEmpty(); 253 } 254 255 private static SmackTlsContext getSmackTlsContext(DnssecMode dnssecMode, SslContextFactory sslContextFactory, 256 X509TrustManager trustManager, KeyManager[] keyManagers, SecureRandom secureRandom, String keystoreType, String keystorePath, 257 CallbackHandler callbackHandler, String pkcs11Library) throws NoSuchAlgorithmException, 258 CertificateException, IOException, KeyStoreException, NoSuchProviderException, 259 UnrecoverableKeyException, KeyManagementException, UnsupportedCallbackException, 260 NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, 261 IllegalAccessException, IllegalArgumentException, InvocationTargetException { 262 final SSLContext context; 263 if (sslContextFactory != null) { 264 context = sslContextFactory.createSslContext(); 265 } else { 266 // If the user didn't specify a SslContextFactory, use the default one 267 context = SSLContext.getInstance("TLS"); 268 } 269 270 // TODO: Remove the block below once we removed setKeystorePath(), setKeystoreType(), setCallbackHandler() and 271 // setPKCS11Library() in the builder, and all related fields and the parameters of this function. 272 if (keyManagers == null) { 273 keyManagers = Builder.getKeyManagersFrom(keystoreType, keystorePath, callbackHandler, pkcs11Library); 274 } 275 276 SmackDaneVerifier daneVerifier = null; 277 if (dnssecMode == DnssecMode.needsDnssecAndDane) { 278 SmackDaneProvider daneProvider = DNSUtil.getDaneProvider(); 279 if (daneProvider == null) { 280 throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured"); 281 } 282 daneVerifier = daneProvider.newInstance(); 283 if (daneVerifier == null) { 284 throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier"); 285 } 286 287 // User requested DANE verification. 288 daneVerifier.init(context, keyManagers, trustManager, secureRandom); 289 } else { 290 final TrustManager[] trustManagers; 291 if (trustManager != null) { 292 trustManagers = new TrustManager[] { trustManager }; 293 } else { 294 // Ensure trustManagers is null in case there was no explicit trust manager provided, so that the 295 // default one is used. 296 trustManagers = null; 297 } 298 299 context.init(keyManagers, trustManagers, secureRandom); 300 } 301 302 return new SmackTlsContext(context, daneVerifier); 303 } 304 305 public String getHostString() { 306 if (hostAddress != null) { 307 return hostAddress.toString(); 308 } 309 if (host != null) { 310 return host.toString(); 311 } 312 return xmppServiceDomain.toString(); 313 } 314 315 public DnsName getHost() { 316 return host; 317 } 318 319 public InetAddress getHostAddress() { 320 return hostAddress; 321 } 322 323 public UInt16 getPort() { 324 return port; 325 } 326 327 /** 328 * Returns the server name of the target server. 329 * 330 * @return the server name of the target server. 331 * @deprecated use {@link #getXMPPServiceDomain()} instead. 332 */ 333 @Deprecated 334 public DomainBareJid getServiceName() { 335 return xmppServiceDomain; 336 } 337 338 /** 339 * Returns the XMPP domain used by this configuration. 340 * 341 * @return the XMPP domain. 342 */ 343 public DomainBareJid getXMPPServiceDomain() { 344 return xmppServiceDomain; 345 } 346 347 /** 348 * Returns the XMPP service domain as DNS name if possible. Note that since not every XMPP address domainpart is a 349 * valid DNS name, this method may return <code>null</code>. 350 * 351 * @return the XMPP service domain as DNS name or <code>null</code>. 352 * @since 4.3.4 353 */ 354 public DnsName getXmppServiceDomainAsDnsNameIfPossible() { 355 return xmppServiceDomainDnsName; 356 } 357 358 /** 359 * Returns the TLS security mode used when making the connection. By default, 360 * the mode is {@link SecurityMode#required}. 361 * 362 * @return the security mode. 363 */ 364 public SecurityMode getSecurityMode() { 365 return securityMode; 366 } 367 368 public DnssecMode getDnssecMode() { 369 return dnssecMode; 370 } 371 372 /** 373 * Return the enabled SSL/TLS protocols. 374 * 375 * @return the enabled SSL/TLS protocols 376 */ 377 public String[] getEnabledSSLProtocols() { 378 return enabledSSLProtocols; 379 } 380 381 /** 382 * Return the enabled SSL/TLS ciphers. 383 * 384 * @return the enabled SSL/TLS ciphers 385 */ 386 public String[] getEnabledSSLCiphers() { 387 return enabledSSLCiphers; 388 } 389 390 /** 391 * Returns the configured HostnameVerifier of this ConnectionConfiguration or the Smack default 392 * HostnameVerifier configured with 393 * {@link SmackConfiguration#setDefaultHostnameVerifier(HostnameVerifier)}. 394 * 395 * @return a configured HostnameVerifier or <code>null</code> 396 */ 397 public HostnameVerifier getHostnameVerifier() { 398 if (hostnameVerifier != null) 399 return hostnameVerifier; 400 return SmackConfiguration.getDefaultHostnameVerifier(); 401 } 402 403 /** 404 * Returns the Smack debugger factory. 405 * 406 * @return the Smack debugger factory or <code>null</code> 407 */ 408 public SmackDebuggerFactory getDebuggerFactory() { 409 return debuggerFactory; 410 } 411 412 /** 413 * Returns a CallbackHandler to obtain information, such as the password or 414 * principal information during the SASL authentication. A CallbackHandler 415 * will be used <b>ONLY</b> if no password was specified during the login while 416 * using SASL authentication. 417 * 418 * @return a CallbackHandler to obtain information, such as the password or 419 * principal information during the SASL authentication. 420 */ 421 public CallbackHandler getCallbackHandler() { 422 return callbackHandler; 423 } 424 425 /** 426 * Returns the socket factory used to create new xmppConnection sockets. 427 * This is useful when connecting through SOCKS5 proxies. 428 * 429 * @return socketFactory used to create new sockets. 430 */ 431 public SocketFactory getSocketFactory() { 432 return this.socketFactory; 433 } 434 435 /** 436 * Get the configured proxy information (if any). 437 * 438 * @return the configured proxy information or <code>null</code>. 439 */ 440 public ProxyInfo getProxyInfo() { 441 return proxy; 442 } 443 444 /** 445 * An enumeration for TLS security modes that are available when making a connection 446 * to the XMPP server. 447 */ 448 public enum SecurityMode { 449 450 /** 451 * Security via TLS encryption is required in order to connect. If the server 452 * does not offer TLS or if the TLS negotiation fails, the connection to the server 453 * will fail. 454 */ 455 required, 456 457 /** 458 * Security via TLS encryption is used whenever it's available. This is the 459 * default setting. 460 * <p> 461 * <b>Do not use this setting</b> unless you can't use {@link #required}. An attacker could easily perform a 462 * Man-in-the-middle attack and prevent TLS from being used, leaving you with an unencrypted (and 463 * unauthenticated) connection. 464 * </p> 465 */ 466 ifpossible, 467 468 /** 469 * Security via TLS encryption is disabled and only un-encrypted connections will 470 * be used. If only TLS encryption is available from the server, the connection 471 * will fail. 472 */ 473 disabled 474 } 475 476 /** 477 * Determines the requested DNSSEC security mode. 478 * <b>Note that Smack's support for DNSSEC/DANE is experimental!</b> 479 * <p> 480 * The default '{@link #disabled}' means that neither DNSSEC nor DANE verification will be performed. When 481 * '{@link #needsDnssec}' is used, then the connection will not be established if the resource records used to connect 482 * to the XMPP service are not authenticated by DNSSEC. Additionally, if '{@link #needsDnssecAndDane}' is used, then 483 * the XMPP service's TLS certificate is verified using DANE. 484 * 485 */ 486 public enum DnssecMode { 487 488 /** 489 * Do not perform any DNSSEC authentication or DANE verification. 490 */ 491 disabled, 492 493 /** 494 * <b>Experimental!</b> 495 * Require all DNS information to be authenticated by DNSSEC. 496 */ 497 needsDnssec, 498 499 /** 500 * <b>Experimental!</b> 501 * Require all DNS information to be authenticated by DNSSEC and require the XMPP service's TLS certificate to be verified using DANE. 502 */ 503 needsDnssecAndDane, 504 505 } 506 507 /** 508 * Returns the username to use when trying to reconnect to the server. 509 * 510 * @return the username to use when trying to reconnect to the server. 511 */ 512 public CharSequence getUsername() { 513 return this.username; 514 } 515 516 /** 517 * Returns the password to use when trying to reconnect to the server. 518 * 519 * @return the password to use when trying to reconnect to the server. 520 */ 521 public String getPassword() { 522 return this.password; 523 } 524 525 /** 526 * Returns the resource to use when trying to reconnect to the server. 527 * 528 * @return the resource to use when trying to reconnect to the server. 529 */ 530 public Resourcepart getResource() { 531 return resource; 532 } 533 534 /** 535 * Returns the stream language to use when connecting to the server. 536 * 537 * @return the stream language to use when connecting to the server or <code>null</code>. 538 */ 539 public Locale getLanguage() { 540 return language; 541 } 542 543 /** 544 * Returns the xml:lang string of the stream language to use when connecting to the server. 545 * 546 * <p>If the developer sets the language to null, this will also return null, leading to 547 * the removal of the xml:lang tag from the stream.</p> 548 * 549 * @return the stream language to use when connecting to the server or <code>null</code>. 550 */ 551 public String getXmlLang() { 552 if (language == null) { 553 return null; 554 } 555 556 String languageTag = language.toLanguageTag(); 557 if (languageTag.equals("und")) { 558 return null; 559 } 560 561 return languageTag; 562 } 563 564 /** 565 * Returns the optional XMPP address to be requested as the SASL authorization identity. 566 * 567 * @return the authorization identifier. 568 * @see <a href="http://tools.ietf.org/html/rfc6120#section-6.3.8">RFC 6120 § 6.3.8. Authorization Identity</a> 569 * @since 4.2 570 */ 571 public EntityBareJid getAuthzid() { 572 return authzid; 573 } 574 575 /** 576 * Returns true if an available presence should be sent when logging in while reconnecting. 577 * 578 * @return true if an available presence should be sent when logging in while reconnecting 579 */ 580 public boolean isSendPresence() { 581 return sendPresence; 582 } 583 584 /** 585 * Returns true if the connection is going to use stream compression. Stream compression 586 * will be requested after TLS was established (if TLS was enabled) and only if the server 587 * offered stream compression. With stream compression network traffic can be reduced 588 * up to 90%. By default,compression is disabled. 589 * 590 * @return true if the connection is going to use stream compression. 591 */ 592 public boolean isCompressionEnabled() { 593 return compressionEnabled; 594 } 595 596 /** 597 * Check if the given SASL mechanism is enabled in this connection configuration. 598 * 599 * @param saslMechanism TODO javadoc me please 600 * @return true if the given SASL mechanism is enabled, false otherwise. 601 */ 602 public boolean isEnabledSaslMechanism(String saslMechanism) { 603 // If enabledSaslMechanisms is not set, then all mechanisms which are not blacklisted are enabled per default. 604 if (enabledSaslMechanisms == null) { 605 return !SASLAuthentication.getBlacklistedSASLMechanisms().contains(saslMechanism); 606 } 607 return enabledSaslMechanisms.contains(saslMechanism); 608 } 609 610 /** 611 * Return the explicitly enabled SASL mechanisms. May return <code>null</code> if no SASL mechanisms where 612 * explicitly enabled, i.e. all SASL mechanisms supported and announced by the service will be considered. 613 * 614 * @return the enabled SASL mechanisms or <code>null</code>. 615 */ 616 public Set<String> getEnabledSaslMechanisms() { 617 if (enabledSaslMechanisms == null) { 618 return null; 619 } 620 return Collections.unmodifiableSet(enabledSaslMechanisms); 621 } 622 623 StanzaIdSource constructStanzaIdSource() { 624 return stanzaIdSourceFactory.constructStanzaIdSource(); 625 } 626 627 /** 628 * A builder for XMPP connection configurations. 629 * <p> 630 * This is an abstract class that uses the builder design pattern and the "getThis() trick" to recover the type of 631 * the builder in a class hierarchies with a self-referential generic supertype. Otherwise chaining of build 632 * instructions from the superclasses followed by build instructions of a subclass would not be possible, because 633 * the superclass build instructions would return the builder of the superclass and not the one of the subclass. You 634 * can read more about it a Angelika Langer's Generics FAQ, especially the entry <a 635 * href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206">What is the 636 * "getThis()" trick?</a>. 637 * </p> 638 * 639 * @param <B> the builder type parameter. 640 * @param <C> the resulting connection configuration type parameter. 641 */ 642 public abstract static class Builder<B extends Builder<B, C>, C extends ConnectionConfiguration> { 643 private SecurityMode securityMode = SecurityMode.required; 644 private DnssecMode dnssecMode = DnssecMode.disabled; 645 private KeyManager[] keyManagers; 646 private SecureRandom sslContextSecureRandom; 647 private String keystorePath; 648 private String keystoreType; 649 private String pkcs11Library = "pkcs11.config"; 650 private SslContextFactory sslContextFactory; 651 private String[] enabledSSLProtocols; 652 private String[] enabledSSLCiphers; 653 private HostnameVerifier hostnameVerifier; 654 private EntityBareJid authzid; 655 private CharSequence username; 656 private String password; 657 private Resourcepart resource; 658 private Locale language = Locale.getDefault(); 659 private boolean sendPresence = true; 660 private ProxyInfo proxy; 661 private CallbackHandler callbackHandler; 662 private SmackDebuggerFactory debuggerFactory; 663 private SocketFactory socketFactory; 664 private DomainBareJid xmppServiceDomain; 665 private InetAddress hostAddress; 666 private DnsName host; 667 private UInt16 port = UInt16.from(5222); 668 private boolean allowEmptyOrNullUsername = false; 669 private boolean saslMechanismsSealed; 670 private Set<String> enabledSaslMechanisms; 671 private X509TrustManager customX509TrustManager; 672 private boolean compressionEnabled = false; 673 private StanzaIdSourceFactory stanzaIdSourceFactory = new StandardStanzaIdSource.Factory(); 674 675 protected Builder() { 676 if (SmackConfiguration.DEBUG) { 677 enableDefaultDebugger(); 678 } 679 } 680 681 /** 682 * Convenience method to configure the username, password and XMPP service domain. 683 * 684 * @param jid the XMPP address of the user. 685 * @param password the password of the user. 686 * @return a reference to this builder. 687 * @throws XmppStringprepException in case the XMPP address is not valid. 688 * @see #setXmppAddressAndPassword(EntityBareJid, String) 689 * @since 4.4.0 690 */ 691 public B setXmppAddressAndPassword(CharSequence jid, String password) throws XmppStringprepException { 692 return setXmppAddressAndPassword(JidCreate.entityBareFrom(jid), password); 693 } 694 695 /** 696 * Convenience method to configure the username, password and XMPP service domain. The localpart of the provided 697 * JID is used as username and the domanipart is used as XMPP service domain. 698 * <p> 699 * Please note that this does and can not configure the client XMPP address. XMPP services are not required to 700 * assign bound JIDs where the localpart matches the username and the domainpart matches the verified domainpart. 701 * Although most services will follow that pattern. 702 * </p> 703 * 704 * @param jid TODO javadoc me please 705 * @param password TODO javadoc me please 706 * @return a reference to this builder. 707 * @since 4.4.0 708 */ 709 public B setXmppAddressAndPassword(EntityBareJid jid, String password) { 710 setUsernameAndPassword(jid.getLocalpart(), password); 711 return setXmppDomain(jid.asDomainBareJid()); 712 } 713 714 /** 715 * Set the XMPP entities username and password. 716 * <p> 717 * The username is usually the localpart of the clients JID. But some SASL mechanisms or services may require a different 718 * format (e.g. the full JID) as used authorization identity. 719 * </p> 720 * 721 * @param username the username or authorization identity 722 * @param password the password or token used to authenticate 723 * @return a reference to this builder. 724 */ 725 public B setUsernameAndPassword(CharSequence username, String password) { 726 this.username = username; 727 this.password = password; 728 return getThis(); 729 } 730 731 /** 732 * Set the XMPP domain. The XMPP domain is what follows after the '@' sign in XMPP addresses (JIDs). 733 * 734 * @param serviceName the service name 735 * @return a reference to this builder. 736 * @deprecated use {@link #setXmppDomain(DomainBareJid)} instead. 737 */ 738 @Deprecated 739 public B setServiceName(DomainBareJid serviceName) { 740 return setXmppDomain(serviceName); 741 } 742 743 /** 744 * Set the XMPP domain. The XMPP domain is what follows after the '@' sign in XMPP addresses (JIDs). 745 * 746 * @param xmppDomain the XMPP domain. 747 * @return a reference to this builder. 748 */ 749 public B setXmppDomain(DomainBareJid xmppDomain) { 750 this.xmppServiceDomain = xmppDomain; 751 return getThis(); 752 } 753 754 /** 755 * Set the XMPP domain. The XMPP domain is what follows after the '@' sign in XMPP addresses (JIDs). 756 * 757 * @param xmppServiceDomain the XMPP domain. 758 * @return a reference to this builder. 759 * @throws XmppStringprepException if the given string is not a domain bare JID. 760 */ 761 public B setXmppDomain(String xmppServiceDomain) throws XmppStringprepException { 762 this.xmppServiceDomain = JidCreate.domainBareFrom(xmppServiceDomain); 763 return getThis(); 764 } 765 766 /** 767 * Set the resource we are requesting from the server. 768 * <p> 769 * If <code>resource</code> is <code>null</code>, the default, then the server will automatically create a 770 * resource for the client. Note that XMPP clients only suggest this resource to the server. XMPP servers are 771 * allowed to ignore the client suggested resource and instead assign a completely different 772 * resource (see RFC 6120 § 7.7.1). 773 * </p> 774 * 775 * @param resource the resource to use. 776 * @return a reference to this builder. 777 * @see <a href="https://tools.ietf.org/html/rfc6120#section-7.7.1">RFC 6120 § 7.7.1</a> 778 */ 779 public B setResource(Resourcepart resource) { 780 this.resource = resource; 781 return getThis(); 782 } 783 784 /** 785 * Set the stream language. 786 * 787 * @param language the language to use. 788 * @return a reference to this builder. 789 * @see <a href="https://tools.ietf.org/html/rfc6120#section-4.7.4">RFC 6120 § 4.7.4</a> 790 * @see <a href="https://www.w3.org/TR/xml/#sec-lang-tag">XML 1.0 § 2.12 Language Identification</a> 791 */ 792 public B setLanguage(Locale language) { 793 this.language = language; 794 return getThis(); 795 } 796 797 /** 798 * Set the resource we are requesting from the server. 799 * 800 * @param resource the non-null CharSequence to use a resource. 801 * @return a reference ot this builder. 802 * @throws XmppStringprepException if the CharSequence is not a valid resourcepart. 803 * @see #setResource(Resourcepart) 804 */ 805 public B setResource(CharSequence resource) throws XmppStringprepException { 806 Objects.requireNonNull(resource, "resource must not be null"); 807 return setResource(Resourcepart.from(resource.toString())); 808 } 809 810 /** 811 * Set the Internet address of the host providing the XMPP service. If set, then this will overwrite anything 812 * set via {@link #setHost(CharSequence)}. 813 * 814 * @param address the Internet address of the host providing the XMPP service. 815 * @return a reference to this builder. 816 * @since 4.2 817 */ 818 public B setHostAddress(InetAddress address) { 819 this.hostAddress = address; 820 return getThis(); 821 } 822 823 /** 824 * Set the name of the host providing the XMPP service. This method takes DNS names and 825 * IP addresses. 826 * 827 * @param host the DNS name of the host providing the XMPP service. 828 * @return a reference to this builder. 829 */ 830 public B setHost(CharSequence host) { 831 String fqdnOrIpString = host.toString(); 832 if (InetAddressUtil.isIpAddress(fqdnOrIpString)) { 833 InetAddress hostInetAddress; 834 try { 835 hostInetAddress = InetAddress.getByName(fqdnOrIpString); 836 } 837 catch (UnknownHostException e) { 838 // Should never happen. 839 throw new AssertionError(e); 840 } 841 setHostAddress(hostInetAddress); 842 } else { 843 DnsName dnsName = DnsName.from(fqdnOrIpString); 844 setHost(dnsName); 845 } 846 return getThis(); 847 } 848 849 /** 850 * Set the name of the host providing the XMPP service. Note that this method does only allow DNS names and not 851 * IP addresses. Use {@link #setHostAddress(InetAddress)} if you want to explicitly set the Internet address of 852 * the host providing the XMPP service. 853 * 854 * @param host the DNS name of the host providing the XMPP service. 855 * @return a reference to this builder. 856 */ 857 public B setHost(DnsName host) { 858 this.host = host; 859 return getThis(); 860 } 861 862 public B setPort(int port) { 863 if (port < 0 || port > 65535) { 864 throw new IllegalArgumentException( 865 "Port must be a 16-bit unsigned integer (i.e. between 0-65535. Port was: " + port); 866 } 867 UInt16 portUint16 = UInt16.from(port); 868 return setPort(portUint16); 869 } 870 871 public B setPort(UInt16 port) { 872 this.port = Objects.requireNonNull(port); 873 return getThis(); 874 } 875 876 /** 877 * Sets a CallbackHandler to obtain information, such as the password or 878 * principal information during the SASL authentication. A CallbackHandler 879 * will be used <b>ONLY</b> if no password was specified during the login while 880 * using SASL authentication. 881 * 882 * @param callbackHandler to obtain information, such as the password or 883 * principal information during the SASL authentication. 884 * @return a reference to this builder. 885 * @deprecated set a callback-handler aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or 886 * {@link #setKeyManagers(KeyManager[])}, created by 887 * {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead. 888 */ 889 // TODO: Remove in Smack 4.6. 890 @Deprecated 891 public B setCallbackHandler(CallbackHandler callbackHandler) { 892 this.callbackHandler = callbackHandler; 893 return getThis(); 894 } 895 896 public B setDnssecMode(DnssecMode dnssecMode) { 897 this.dnssecMode = Objects.requireNonNull(dnssecMode, "DNSSEC mode must not be null"); 898 return getThis(); 899 } 900 901 public B setCustomX509TrustManager(X509TrustManager x509TrustManager) { 902 this.customX509TrustManager = x509TrustManager; 903 return getThis(); 904 } 905 906 /** 907 * Sets the TLS security mode used when making the connection. By default, 908 * the mode is {@link SecurityMode#required}. 909 * 910 * @param securityMode the security mode. 911 * @return a reference to this builder. 912 */ 913 public B setSecurityMode(SecurityMode securityMode) { 914 this.securityMode = securityMode; 915 return getThis(); 916 } 917 918 /** 919 * Set the {@link KeyManager}s to initialize the {@link SSLContext} used by Smack to establish the XMPP connection. 920 * 921 * @param keyManagers an array of {@link KeyManager}s to initialize the {@link SSLContext} with. 922 * @return a reference to this builder. 923 * @since 4.4.5 924 */ 925 public B setKeyManagers(KeyManager[] keyManagers) { 926 this.keyManagers = keyManagers; 927 return getThis(); 928 } 929 930 /** 931 * Set the {@link KeyManager}s to initialize the {@link SSLContext} used by Smack to establish the XMPP connection. 932 * 933 * @param keyManager the {@link KeyManager}s to initialize the {@link SSLContext} with. 934 * @return a reference to this builder. 935 * @see #setKeyManagers(KeyManager[]) 936 * @since 4.4.5 937 */ 938 public B setKeyManager(KeyManager keyManager) { 939 KeyManager[] keyManagers = new KeyManager[] { keyManager }; 940 return setKeyManagers(keyManagers); 941 } 942 943 /** 944 * Set the {@link SecureRandom} used to initialize the {@link SSLContext} used by Smack to establish the XMPP 945 * connection. Note that you usually do not need (nor want) to set this. Because if the {@link SecureRandom} is 946 * not explicitly set, Smack will initialize the {@link SSLContext} with <code>null</code> as 947 * {@link SecureRandom} argument. And all sane {@link SSLContext} implementations will then select a safe secure 948 * random source by default. 949 * 950 * @param secureRandom the {@link SecureRandom} to initialize the {@link SSLContext} with. 951 * @return a reference to this builder. 952 * @since 4.4.5 953 */ 954 public B setSslContextSecureRandom(SecureRandom secureRandom) { 955 this.sslContextSecureRandom = secureRandom; 956 return getThis(); 957 } 958 959 /** 960 * Sets the path to the keystore file. The key store file contains the 961 * certificates that may be used to authenticate the client to the server, 962 * in the event the server requests or requires it. 963 * 964 * @param keystorePath the path to the keystore file. 965 * @return a reference to this builder. 966 * @deprecated set a keystore-path aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or 967 * {@link #setKeyManagers(KeyManager[])}, created by 968 * {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead. 969 */ 970 // TODO: Remove in Smack 4.6. 971 @Deprecated 972 public B setKeystorePath(String keystorePath) { 973 this.keystorePath = keystorePath; 974 return getThis(); 975 } 976 977 /** 978 * Sets the keystore type. 979 * 980 * @param keystoreType the keystore type. 981 * @return a reference to this builder. 982 * @deprecated set a key-type aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or 983 * {@link #setKeyManagers(KeyManager[])}, created by 984 * {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead. 985 */ 986 // TODO: Remove in Smack 4.6. 987 @Deprecated 988 public B setKeystoreType(String keystoreType) { 989 this.keystoreType = keystoreType; 990 return getThis(); 991 } 992 993 /** 994 * Sets the PKCS11 library file location, needed when the 995 * Keystore type is PKCS11. 996 * 997 * @param pkcs11Library the path to the PKCS11 library file. 998 * @return a reference to this builder. 999 * @deprecated set a PKCS11-library aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or 1000 * {@link #setKeyManagers(KeyManager[])}, created by 1001 * {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead. 1002 */ 1003 // TODO: Remove in Smack 4.6. 1004 @Deprecated 1005 public B setPKCS11Library(String pkcs11Library) { 1006 this.pkcs11Library = pkcs11Library; 1007 return getThis(); 1008 } 1009 1010 /** 1011 * Sets a custom SSLContext for creating SSL sockets. 1012 * <p> 1013 * For more information on how to create a SSLContext see <a href= 1014 * "http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#X509TrustManager" 1015 * >Java Secure Socket Extension (JSEE) Reference Guide: Creating Your Own X509TrustManager</a> 1016 * 1017 * @param sslContextFactory the custom SSLContext for new sockets. 1018 * @return a reference to this builder. 1019 */ 1020 public B setSslContextFactory(SslContextFactory sslContextFactory) { 1021 this.sslContextFactory = Objects.requireNonNull(sslContextFactory, "The provided SslContextFactory must not be null"); 1022 return getThis(); 1023 } 1024 1025 /** 1026 * Set the enabled SSL/TLS protocols. 1027 * 1028 * @param enabledSSLProtocols TODO javadoc me please 1029 * @return a reference to this builder. 1030 */ 1031 public B setEnabledSSLProtocols(String[] enabledSSLProtocols) { 1032 this.enabledSSLProtocols = enabledSSLProtocols; 1033 return getThis(); 1034 } 1035 1036 /** 1037 * Set the enabled SSL/TLS ciphers. 1038 * 1039 * @param enabledSSLCiphers the enabled SSL/TLS ciphers 1040 * @return a reference to this builder. 1041 */ 1042 public B setEnabledSSLCiphers(String[] enabledSSLCiphers) { 1043 this.enabledSSLCiphers = enabledSSLCiphers; 1044 return getThis(); 1045 } 1046 1047 /** 1048 * Set the HostnameVerifier used to verify the hostname of SSLSockets used by XMPP connections 1049 * created with this ConnectionConfiguration. 1050 * 1051 * @param verifier TODO javadoc me please 1052 * @return a reference to this builder. 1053 */ 1054 public B setHostnameVerifier(HostnameVerifier verifier) { 1055 hostnameVerifier = verifier; 1056 return getThis(); 1057 } 1058 1059 /** 1060 * Sets if an initial available presence will be sent to the server. By default, * an available presence will be sent to the server indicating that this presence 1061 * is not online and available to receive messages. If you want to log in without 1062 * being 'noticed' then pass a <code>false</code> value. 1063 * 1064 * @param sendPresence true if an initial available presence will be sent while logging in. 1065 * @return a reference to this builder. 1066 */ 1067 public B setSendPresence(boolean sendPresence) { 1068 this.sendPresence = sendPresence; 1069 return getThis(); 1070 } 1071 1072 public B enableDefaultDebugger() { 1073 this.debuggerFactory = SmackConfiguration.getDefaultSmackDebuggerFactory(); 1074 assert this.debuggerFactory != null; 1075 return getThis(); 1076 } 1077 1078 /** 1079 * Set the Smack debugger factory used to construct Smack debuggers. 1080 * 1081 * @param debuggerFactory the Smack debugger factory. 1082 * @return a reference to this builder. 1083 */ 1084 public B setDebuggerFactory(SmackDebuggerFactory debuggerFactory) { 1085 this.debuggerFactory = debuggerFactory; 1086 return getThis(); 1087 } 1088 1089 /** 1090 * Sets the socket factory used to create new xmppConnection sockets. 1091 * This is useful when connecting through SOCKS5 proxies. 1092 * 1093 * @param socketFactory used to create new sockets. 1094 * @return a reference to this builder. 1095 */ 1096 public B setSocketFactory(SocketFactory socketFactory) { 1097 this.socketFactory = socketFactory; 1098 return getThis(); 1099 } 1100 1101 /** 1102 * Set the information about the Proxy used for the connection. 1103 * 1104 * @param proxyInfo the Proxy information. 1105 * @return a reference to this builder. 1106 */ 1107 public B setProxyInfo(ProxyInfo proxyInfo) { 1108 this.proxy = proxyInfo; 1109 return getThis(); 1110 } 1111 1112 /** 1113 * Allow <code>null</code> or the empty String as username. 1114 * 1115 * Some SASL mechanisms (e.g. SASL External) may also signal the username (as "authorization identity"), in 1116 * which case Smack should not throw an IllegalArgumentException when the username is not set. 1117 * 1118 * @return a reference to this builder. 1119 */ 1120 public B allowEmptyOrNullUsernames() { 1121 allowEmptyOrNullUsername = true; 1122 return getThis(); 1123 } 1124 1125 /** 1126 * Perform anonymous authentication using SASL ANONYMOUS. Your XMPP service must support this authentication 1127 * mechanism. This method also calls {@link #addEnabledSaslMechanism(String)} with "ANONYMOUS" as argument. 1128 * 1129 * @return a reference to this builder. 1130 */ 1131 public B performSaslAnonymousAuthentication() { 1132 if (!SASLAuthentication.isSaslMechanismRegistered(SASLAnonymous.NAME)) { 1133 throw new IllegalArgumentException("SASL " + SASLAnonymous.NAME + " is not registered"); 1134 } 1135 throwIfEnabledSaslMechanismsSet(); 1136 1137 allowEmptyOrNullUsernames(); 1138 addEnabledSaslMechanism(SASLAnonymous.NAME); 1139 saslMechanismsSealed = true; 1140 return getThis(); 1141 } 1142 1143 /** 1144 * Perform authentication using SASL EXTERNAL. Your XMPP service must support this 1145 * authentication mechanism. This method also calls {@link #addEnabledSaslMechanism(String)} with "EXTERNAL" as 1146 * argument. It also calls {@link #allowEmptyOrNullUsernames()} and {@link #setSecurityMode(ConnectionConfiguration.SecurityMode)} to 1147 * {@link SecurityMode#required}. 1148 * 1149 * @param sslContext custom SSLContext to be used. 1150 * @return a reference to this builder. 1151 */ 1152 public B performSaslExternalAuthentication(SSLContext sslContext) { 1153 if (!SASLAuthentication.isSaslMechanismRegistered(SASLMechanism.EXTERNAL)) { 1154 throw new IllegalArgumentException("SASL " + SASLMechanism.EXTERNAL + " is not registered"); 1155 } 1156 setSslContextFactory(() -> { 1157 return sslContext; 1158 }); 1159 throwIfEnabledSaslMechanismsSet(); 1160 1161 allowEmptyOrNullUsernames(); 1162 setSecurityMode(SecurityMode.required); 1163 addEnabledSaslMechanism(SASLMechanism.EXTERNAL); 1164 saslMechanismsSealed = true; 1165 return getThis(); 1166 } 1167 1168 private void throwIfEnabledSaslMechanismsSet() { 1169 if (enabledSaslMechanisms != null) { 1170 throw new IllegalStateException("Enabled SASL mechanisms found"); 1171 } 1172 } 1173 1174 /** 1175 * Add the given mechanism to the enabled ones. See {@link #addEnabledSaslMechanism(Collection)} for a discussion about enabled SASL mechanisms. 1176 * 1177 * @param saslMechanism the name of the mechanism to enable. 1178 * @return a reference to this builder. 1179 */ 1180 public B addEnabledSaslMechanism(String saslMechanism) { 1181 return addEnabledSaslMechanism(Arrays.asList(StringUtils.requireNotNullNorEmpty(saslMechanism, 1182 "saslMechanism must not be null nor empty"))); 1183 } 1184 1185 /** 1186 * Enable the given SASL mechanisms. If you never add a mechanism to the set of enabled ones, <b>all mechanisms 1187 * known to Smack</b> will be enabled. Only explicitly enable particular SASL mechanisms if you want to limit 1188 * the used mechanisms to the enabled ones. 1189 * 1190 * @param saslMechanisms a collection of names of mechanisms to enable. 1191 * @return a reference to this builder. 1192 */ 1193 public B addEnabledSaslMechanism(Collection<String> saslMechanisms) { 1194 if (saslMechanismsSealed) { 1195 throw new IllegalStateException("The enabled SASL mechanisms are sealed, you can not add new ones"); 1196 } 1197 CollectionUtil.requireNotEmpty(saslMechanisms, "saslMechanisms"); 1198 Set<String> blacklistedMechanisms = SASLAuthentication.getBlacklistedSASLMechanisms(); 1199 for (String mechanism : saslMechanisms) { 1200 if (!SASLAuthentication.isSaslMechanismRegistered(mechanism)) { 1201 throw new IllegalArgumentException("SASL " + mechanism + " is not available. Consider registering it with Smack"); 1202 } 1203 if (blacklistedMechanisms.contains(mechanism)) { 1204 throw new IllegalArgumentException("SALS " + mechanism + " is blacklisted."); 1205 } 1206 } 1207 if (enabledSaslMechanisms == null) { 1208 enabledSaslMechanisms = new HashSet<>(saslMechanisms.size()); 1209 } 1210 enabledSaslMechanisms.addAll(saslMechanisms); 1211 return getThis(); 1212 } 1213 1214 /** 1215 * Set the XMPP address to be used as authorization identity. 1216 * <p> 1217 * In XMPP, authorization identities are bare jids. In general, callers should allow the server to select the 1218 * authorization identifier automatically, and not call this. Note that setting the authzid does not set the XMPP 1219 * service domain, which should typically match. 1220 * Calling this will also SASL CRAM, since this mechanism does not support authzid. 1221 * </p> 1222 * 1223 * @param authzid The BareJid to be requested as the authorization identifier. 1224 * @return a reference to this builder. 1225 * @see <a href="http://tools.ietf.org/html/rfc6120#section-6.3.8">RFC 6120 § 6.3.8. Authorization Identity</a> 1226 * @since 4.2 1227 */ 1228 public B setAuthzid(EntityBareJid authzid) { 1229 this.authzid = authzid; 1230 return getThis(); 1231 } 1232 1233 /** 1234 * Sets if the connection is going to use compression (default false). 1235 * 1236 * Compression is only activated if the server offers compression. With compression network 1237 * traffic can be reduced up to 90%. By default,compression is disabled. 1238 * 1239 * @param compressionEnabled if the connection is going to use compression on the HTTP level. 1240 * @return a reference to this object. 1241 */ 1242 public B setCompressionEnabled(boolean compressionEnabled) { 1243 this.compressionEnabled = compressionEnabled; 1244 return getThis(); 1245 } 1246 1247 /** 1248 * Set the factory for stanza ID sources to use. 1249 * 1250 * @param stanzaIdSourceFactory the factory for stanza ID sources to use. 1251 * @return a reference to this builder. 1252 * @since 4.4 1253 */ 1254 public B setStanzaIdSourceFactory(StanzaIdSourceFactory stanzaIdSourceFactory) { 1255 this.stanzaIdSourceFactory = Objects.requireNonNull(stanzaIdSourceFactory); 1256 return getThis(); 1257 } 1258 1259 public abstract C build(); 1260 1261 protected abstract B getThis(); 1262 1263 public static KeyManager[] getKeyManagersFrom(String keystoreType, String keystorePath, 1264 CallbackHandler callbackHandler, String pkcs11Library) 1265 throws NoSuchMethodException, SecurityException, ClassNotFoundException, KeyStoreException, 1266 NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, UnsupportedCallbackException, UnrecoverableKeyException { 1267 KeyManager[] keyManagers = null; 1268 KeyStore ks = null; 1269 PasswordCallback pcb = null; 1270 1271 if ("PKCS11".equals(keystoreType)) { 1272 Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class); 1273 String pkcs11Config = "name = SmartCard\nlibrary = " + pkcs11Library; 1274 ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StandardCharsets.UTF_8)); 1275 Provider p = (Provider) c.newInstance(config); 1276 Security.addProvider(p); 1277 ks = KeyStore.getInstance("PKCS11", p); 1278 pcb = new PasswordCallback("PKCS11 Password: ", false); 1279 callbackHandler.handle(new Callback[] { pcb }); 1280 ks.load(null, pcb.getPassword()); 1281 } else if ("Apple".equals(keystoreType)) { 1282 ks = KeyStore.getInstance("KeychainStore", "Apple"); 1283 ks.load(null, null); 1284 // pcb = new PasswordCallback("Apple Keychain",false); 1285 // pcb.setPassword(null); 1286 } else if (keystoreType != null) { 1287 ks = KeyStore.getInstance(keystoreType); 1288 if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) { 1289 pcb = new PasswordCallback("Keystore Password: ", false); 1290 callbackHandler.handle(new Callback[] { pcb }); 1291 ks.load(new FileInputStream(keystorePath), pcb.getPassword()); 1292 } else { 1293 InputStream stream = TLSUtils.getDefaultTruststoreStreamIfPossible(); 1294 try { 1295 // Note that PKCS12 keystores need a password one some Java platforms. Hence, we try the famous 1296 // 'changeit' here. See https://bugs.openjdk.java.net/browse/JDK-8194702 1297 char[] password = "changeit".toCharArray(); 1298 try { 1299 ks.load(stream, password); 1300 } finally { 1301 CloseableUtil.maybeClose(stream); 1302 } 1303 } catch (IOException e) { 1304 LOGGER.log(Level.FINE, "KeyStore load() threw, attempting 'jks' fallback", e); 1305 1306 ks = KeyStore.getInstance("jks"); 1307 // Open the stream again, so that we read it from the beginning. 1308 stream = TLSUtils.getDefaultTruststoreStreamIfPossible(); 1309 try { 1310 ks.load(stream, null); 1311 } finally { 1312 CloseableUtil.maybeClose(stream); 1313 } 1314 } 1315 } 1316 } 1317 1318 if (ks != null) { 1319 String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); 1320 KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm); 1321 if (kmf != null) { 1322 if (pcb == null) { 1323 kmf.init(ks, null); 1324 } else { 1325 kmf.init(ks, pcb.getPassword()); 1326 pcb.clearPassword(); 1327 } 1328 keyManagers = kmf.getKeyManagers(); 1329 } 1330 } 1331 1332 return keyManagers; 1333 } 1334 } 1335}