-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
SASLAuthentication.java
758 lines (680 loc) · 34.4 KB
/
SASLAuthentication.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
/*
* Copyright (C) 2005-2008 Jive Software, 2022-2023 Ignite Realtime Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.net;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.XMPPServerInfo;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.auth.AuthToken;
import org.jivesoftware.openfire.keystore.CertificateStoreManager;
import org.jivesoftware.openfire.keystore.TrustStore;
import org.jivesoftware.openfire.lockout.LockOutManager;
import org.jivesoftware.openfire.sasl.AnonymousSaslServer;
import org.jivesoftware.openfire.sasl.Failure;
import org.jivesoftware.openfire.sasl.JiveSharedSecretSaslServer;
import org.jivesoftware.openfire.sasl.SaslFailureException;
import org.jivesoftware.openfire.session.*;
import org.jivesoftware.openfire.spi.ConnectionType;
import org.jivesoftware.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Pattern;
/**
* SASLAuthentication is responsible for returning the available SASL mechanisms to use and for
* actually performing the SASL authentication.<p>
*
* The list of available SASL mechanisms is determined by:
* <ol>
* <li>The type of {@link org.jivesoftware.openfire.user.UserProvider} being used since
* some SASL mechanisms require the server to be able to retrieve user passwords</li>
* <li>Whether anonymous logins are enabled or not.</li>
* <li>Whether shared secret authentication is enabled or not.</li>
* <li>Whether the underlying connection has been secured or not.</li>
* </ol>
*
* @author Hao Chen
* @author Gaston Dombiak
*/
public class SASLAuthentication {
private static final Logger Log = LoggerFactory.getLogger(SASLAuthentication.class);
// TODO how is this different from a singular entry in APPROVED_REALMS? Should these two properties be folded into eachother?
public static final SystemProperty<String> REALM = SystemProperty.Builder.ofType(String.class)
.setKey("sasl.realm")
.setDynamic(true)
.setDefaultValue(null)
.build();
public static final SystemProperty<List<String>> APPROVED_REALMS = SystemProperty.Builder.ofType(List.class)
.setKey("sasl.approvedRealms")
.setDefaultValue(Collections.emptyList())
.setDynamic(true)
.buildList(String.class);
public static final SystemProperty<Boolean> PROXY_AUTH = SystemProperty.Builder.ofType(Boolean.class)
.setKey("sasl.proxyAuth")
.setDynamic(true)
.setDefaultValue(false)
.build();
public static final SystemProperty<Boolean> SKIP_PEER_CERT_REVALIDATION_CLIENT = SystemProperty.Builder.ofType(Boolean.class)
.setKey("xmpp.auth.external.client.skip-cert-revalidation")
.setDynamic(true)
.setDefaultValue(false)
.build();
/**
* Require the peer to provide an authorization identity through SASL (typically in the Initial Response) when authenticating
* an inbound S2S connection that uses the EXTERNAL SASL mechanism.
*
* This is not required by the XMPP protocol specification, but it was required by Openfire versions prior to release 4.8.0.
* This configuration option is added to allow for backwards compatibility.
*/
public static final SystemProperty<Boolean> EXTERNAL_S2S_REQUIRE_AUTHZID = SystemProperty.Builder.ofType(Boolean.class)
.setKey("xmpp.auth.external.server.require-authzid")
.setDynamic(true)
.setDefaultValue(false)
.build();
/**
* Send an authorization identity in the Initial Response when attempting to authenticate using the SASL EXTERNAL
* mechanism with a remote XMPP domain. Sending the authzid in this manner is not required by the XMPP protocol
* specification, but is recommended in XEP-0178 for compatibility with older server implementations.
*
* @see <a href="https://xmpp.org/extensions/xep-0178.html">XEP-0178: Best Practices for Use of SASL EXTERNAL with Certificates</a>
*/
public static final SystemProperty<Boolean> EXTERNAL_S2S_SKIP_SENDING_AUTHZID = SystemProperty.Builder.ofType(Boolean.class)
.setKey("xmpp.auth.external.server.skip-sending-authzid")
.setDynamic(true)
.setDefaultValue(false)
.build();
// http://stackoverflow.com/questions/8571501/how-to-check-whether-the-string-is-base64-encoded-or-not
// plus an extra regex alternative to catch a single equals sign ('=', see RFC 6120 6.4.2)
private static final Pattern BASE64_ENCODED = Pattern.compile("^(=|([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==))$");
private static final String SASL_NAMESPACE = "urn:ietf:params:xml:ns:xmpp-sasl";
/**
* Java's SaslServer does not allow for null values. This makes it hard to distinguish between an empty (initial)
* responses (represented in XMPP as a single equals sign character '=', as per RFC-6120 section 6.4.2), and a
* missing/absent response. This can be problematic when a SASL mechanism implemention is to act differently on each
* scenario (like the EXTERNAL mechanism, that is to challenge for an authzid when no initial response is provided,
* but which is to use the stream's 'from' attribute value when the initial response is empty). To work around this
* shortcoming in Java's SASL implementation, this class will add a session attribute using a key that has the name
* of this constant's value when it detects a Sasl response that is present, but empty.
*
* @see <a href="https://igniterealtime.atlassian.net/jira/software/c/projects/OF/issues/OF-2514">OF-2514: Differentiate between missing and empty initial SASL response</a>
*/
public static final String SASL_LAST_RESPONSE_WAS_PROVIDED_BUT_EMPTY = "Sasl.last-response-was-provided-but-empty";
private static Set<String> mechanisms = new HashSet<>();
static
{
// Add (proprietary) Providers of SASL implementation to the Java security context.
Security.addProvider( new org.jivesoftware.openfire.sasl.SaslProvider() );
// Convert XML based provider setup to Database based
JiveGlobals.migrateProperty("sasl.mechs");
JiveGlobals.migrateProperty("sasl.gssapi.debug");
JiveGlobals.migrateProperty("sasl.gssapi.config");
JiveGlobals.migrateProperty("sasl.gssapi.useSubjectCredsOnly");
initMechanisms();
org.jivesoftware.util.PropertyEventDispatcher.addListener( new PropertyEventListener()
{
@Override
public void propertySet( String property, Map<String, Object> params )
{
if ("sasl.mechs".equals( property ) )
{
initMechanisms();
}
}
@Override
public void propertyDeleted( String property, Map<String, Object> params )
{
if ("sasl.mechs".equals( property ) )
{
initMechanisms();
}
}
@Override
public void xmlPropertySet( String property, Map<String, Object> params )
{}
@Override
public void xmlPropertyDeleted( String property, Map<String, Object> params )
{}
} );
}
public enum ElementType
{
ABORT,
AUTH,
RESPONSE,
CHALLENGE,
FAILURE,
UNDEF;
public static ElementType valueOfCaseInsensitive( String name )
{
if ( name == null || name.isEmpty() ) {
return UNDEF;
}
try
{
return ElementType.valueOf( name.toUpperCase() );
}
catch ( Throwable t )
{
return UNDEF;
}
}
}
public enum Status
{
/**
* Entity needs to respond last challenge. Session is still negotiatingSASL authentication.
*/
needResponse,
/**
* SASL negotiation has failed. The entity may retry a few times before the connection is closed.
*/
failed,
/**
* SASL negotiation has been successful.
*/
authenticated
}
/**
* Returns an XML element with the valid SASL mechanisms available for the specified session. If
* the session's connection is not secured then only include the SASL mechanisms that don't
* require TLS.
*
* @param session The current session
*
* @return The valid SASL mechanisms available for the specified session.
*/
public static Element getSASLMechanisms( LocalSession session )
{
if ( session instanceof ClientSession )
{
return getSASLMechanismsElement( (ClientSession) session );
}
else if ( session instanceof LocalIncomingServerSession )
{
return getSASLMechanismsElement( (LocalIncomingServerSession) session );
}
else
{
Log.debug( "Unable to determine SASL mechanisms that are applicable to session '{}'. Unrecognized session type.", session );
return null;
}
}
public static Element getSASLMechanismsElement( ClientSession session )
{
final Element result = DocumentHelper.createElement( new QName( "mechanisms", new Namespace( "", SASL_NAMESPACE ) ) );
for (String mech : getSupportedMechanisms()) {
if (mech.equals("EXTERNAL")) {
boolean trustedCert = false;
if (session.isEncrypted()) {
final Connection connection = ( (LocalClientSession) session ).getConnection();
assert connection != null; // While the client is performing a SASL negotiation, the connection can't be null.
if ( SKIP_PEER_CERT_REVALIDATION_CLIENT.getValue() ) {
// Trust that the peer certificate has been validated when TLS got established.
trustedCert = connection.getPeerCertificates() != null && connection.getPeerCertificates().length > 0;
} else {
// Re-evaluate the validity of the peer certificate.
final TrustStore trustStore = connection.getConfiguration().getTrustStore();
trustedCert = trustStore.isTrusted( connection.getPeerCertificates() );
}
}
if ( !trustedCert ) {
continue; // Do not offer EXTERNAL.
}
}
final Element mechanism = result.addElement("mechanism");
mechanism.setText(mech);
}
// OF-2072: Return null instead of an empty element, if so configured.
if ( JiveGlobals.getBooleanProperty("sasl.client.suppressEmpty", false) && result.elements().isEmpty() ) {
return null;
}
return result;
}
public static Element getSASLMechanismsElement( LocalIncomingServerSession session )
{
final Element result = DocumentHelper.createElement( new QName( "mechanisms", new Namespace( "", SASL_NAMESPACE ) ) );
if (session.isEncrypted()) {
final Connection connection = session.getConnection();
final TrustStore trustStore = connection.getConfiguration().getTrustStore();
final X509Certificate trusted = trustStore.getEndEntityCertificate( session.getConnection().getPeerCertificates() );
boolean haveTrustedCertificate = trusted != null;
if (trusted != null && session.getDefaultIdentity() != null) {
haveTrustedCertificate = verifyCertificate(trusted, session.getDefaultIdentity());
}
if (haveTrustedCertificate) {
// Offer SASL EXTERNAL only if TLS has already been negotiated and the peer has a trusted cert.
final Element mechanism = result.addElement("mechanism");
mechanism.setText("EXTERNAL");
}
}
// OF-2072: Return null instead of an empty element, if so configured.
if ( JiveGlobals.getBooleanProperty("sasl.server.suppressEmpty", false) && result.elements().isEmpty() ) {
return null;
}
return result;
}
/**
* Handles the SASL authentication packet. The entity may be sending an initial
* authentication request or a response to a challenge made by the server. The returned
* value indicates whether the authentication has finished either successfully or not or
* if the entity is expected to send a response to a challenge.
*
* @param session the session that is authenticating with the server.
* @param doc the stanza sent by the authenticating entity.
* @return value that indicates whether the authentication has finished either successfully
* or not or if the entity is expected to send a response to a challenge.
*/
public static Status handle(LocalSession session, Element doc)
{
try
{
if ( !doc.getNamespaceURI().equals( SASL_NAMESPACE ) )
{
throw new IllegalStateException( "Unexpected data received while negotiating SASL authentication. Name of the offending root element: " + doc.getName() + " Namespace: " + doc.getNamespaceURI() );
}
switch ( ElementType.valueOfCaseInsensitive( doc.getName() ) )
{
case ABORT:
throw new SaslFailureException( Failure.ABORTED );
case AUTH:
if ( doc.attributeValue( "mechanism" ) == null )
{
throw new SaslFailureException( Failure.INVALID_MECHANISM, "Peer did not specify a mechanism." );
}
final String mechanismName = doc.attributeValue( "mechanism" ).toUpperCase();
// See if the mechanism is supported by configuration as well as by implementation.
if ( !mechanisms.contains( mechanismName ) )
{
throw new SaslFailureException( Failure.INVALID_MECHANISM, "The configuration of Openfire does not contain or allow the mechanism." );
}
// OF-477: The SASL implementation requires the fully qualified host name (not the domain name!) of this server,
// yet, most of the XMPP implemenations of DIGEST-MD5 will actually use the domain name. To account for that,
// here, we'll use the host name, unless DIGEST-MD5 is being negotiated!
final XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo();
final String serverName = ( mechanismName.equals( "DIGEST-MD5" ) ? serverInfo.getXMPPDomain() : serverInfo.getHostname() );
// Construct the configuration properties
final Map<String, Object> props = new HashMap<>();
props.put( LocalSession.class.getCanonicalName(), session );
props.put(Sasl.POLICY_NOANONYMOUS, Boolean.toString(!AnonymousSaslServer.ENABLED.getValue()));
props.put( "com.sun.security.sasl.digest.realm", serverInfo.getXMPPDomain() );
SaslServer saslServer = Sasl.createSaslServer( mechanismName, "xmpp", serverName, props, new XMPPCallbackHandler() );
if ( saslServer == null )
{
throw new SaslFailureException( Failure.INVALID_MECHANISM, "There is no provider that can provide a SASL server for the desired mechanism and properties." );
}
session.setSessionData( "SaslServer", saslServer );
if ( mechanismName.equals( "DIGEST-MD5" ) )
{
// RFC2831 (DIGEST-MD5) says the client MAY provide data in the initial response. Java SASL does
// not (currently) support this and throws an exception. For XMPP, such data violates
// the RFC, so we just strip any initial token.
doc.setText( "" );
}
// intended fall-through
case RESPONSE:
saslServer = (SaslServer) session.getSessionData( "SaslServer" );
if ( saslServer == null )
{
// Client sends response without a preceding auth?
throw new IllegalStateException( "A SaslServer instance was not initialized and/or stored on the session." );
}
// Decode any data that is provided in the client response.
final String encoded = doc.getTextTrim();
final byte[] decoded;
// OF-2514: Java SaslServer cannot handle a null, but some SASL mechanisms need to differentiate
// between having received no initial response, and an empty response.
if ( encoded == null || encoded.isEmpty() )
{
session.removeSessionData(SASL_LAST_RESPONSE_WAS_PROVIDED_BUT_EMPTY);
decoded = new byte[ 0 ];
}
else if (encoded.equals("="))
{
session.setSessionData(SASL_LAST_RESPONSE_WAS_PROVIDED_BUT_EMPTY, true);
decoded = new byte[ 0 ];
}
else
{
session.removeSessionData(SASL_LAST_RESPONSE_WAS_PROVIDED_BUT_EMPTY);
// TODO: OF-2515 We shouldn't depend on regex-based validation. Instead, use a proper decoder implementation and handle any exceptions that it throws.
if ( !BASE64_ENCODED.matcher( encoded ).matches() )
{
throw new SaslFailureException( Failure.INCORRECT_ENCODING );
}
decoded = StringUtils.decodeBase64( encoded );
}
// Process client response.
final byte[] challenge = saslServer.evaluateResponse( decoded ); // Either a challenge or success data.
if ( !saslServer.isComplete() )
{
// Not complete: client is challenged for additional steps.
sendChallenge( session, challenge );
return Status.needResponse;
}
// Success!
if ( session instanceof LocalIncomingServerSession )
{
final LocalIncomingServerSession incomingServerSession = (LocalIncomingServerSession) session;
// Flag that indicates if certificates of the remote server should be validated.
final boolean verify = JiveGlobals.getBooleanProperty( ConnectionSettings.Server.TLS_CERTIFICATE_VERIFY, true );
if ( verify )
{
if ( verifyCertificates( incomingServerSession.getConnection().getPeerCertificates(), saslServer.getAuthorizationID(), true ) )
{
( (LocalIncomingServerSession) session ).setAuthenticationMethod(ServerSession.AuthenticationMethod.SASL_EXTERNAL);
}
else
{
throw new SaslFailureException( Failure.NOT_AUTHORIZED, "Server-to-Server certificate verification failed." );
}
}
}
authenticationSuccessful( session, saslServer.getAuthorizationID(), challenge );
session.removeSessionData( "SaslServer" );
session.setSessionData("SaslMechanism", saslServer.getMechanismName());
return Status.authenticated;
default:
throw new IllegalStateException( "Unexpected data received while negotiating SASL authentication. Name of the offending root element: " + doc.getName() + " Namespace: " + doc.getNamespaceURI() );
}
}
catch ( SaslException ex )
{
Log.debug( "SASL negotiation failed for session: {}", session, ex );
final Failure failure;
if ( ex instanceof SaslFailureException && ((SaslFailureException) ex).getFailure() != null )
{
failure = ((SaslFailureException) ex).getFailure();
}
else
{
failure = Failure.NOT_AUTHORIZED;
}
authenticationFailed( session, failure );
session.removeSessionData( "SaslServer" );
return Status.failed;
}
catch( Exception ex )
{
Log.warn( "An unexpected exception occurred during SASL negotiation. Affected session: {}", session, ex );
authenticationFailed( session, Failure.NOT_AUTHORIZED );
session.removeSessionData( "SaslServer" );
return Status.failed;
}
}
public static boolean verifyCertificate(X509Certificate trustedCert, String hostname) {
for (String identity : CertificateManager.getServerIdentities(trustedCert)) {
// Verify that either the identity is the same as the hostname, or for wildcarded
// identities that the hostname ends with .domainspecified or -is- domainspecified.
if ((identity.startsWith("*.")
&& (hostname.endsWith(identity.replace("*.", "."))
|| hostname.equals(identity.replace("*.", ""))))
|| hostname.equals(identity)) {
return true;
}
}
return false;
}
public static boolean verifyCertificates(Certificate[] chain, String hostname, boolean isS2S) {
final CertificateStoreManager certificateStoreManager = XMPPServer.getInstance().getCertificateStoreManager();
final ConnectionType connectionType = isS2S ? ConnectionType.SOCKET_S2S : ConnectionType.SOCKET_C2S;
final TrustStore trustStore = certificateStoreManager.getTrustStore( connectionType );
final X509Certificate trusted = trustStore.getEndEntityCertificate( chain );
if (trusted != null) {
return verifyCertificate(trusted, hostname);
}
return false;
}
private static void sendElement(Session session, String element, byte[] data) {
final Element reply = DocumentHelper.createElement(QName.get(element, "urn:ietf:params:xml:ns:xmpp-sasl"));
if (data != null) {
String data_b64 = StringUtils.encodeBase64(data).trim();
if (data_b64.isEmpty()) {
data_b64 = "=";
}
reply.addText(data_b64);
}
session.deliverRawText(reply.asXML());
}
private static void sendChallenge(Session session, byte[] challenge) {
sendElement(session, "challenge", challenge);
}
private static void authenticationSuccessful(LocalSession session, String username,
byte[] successData) {
if (username != null && LockOutManager.getInstance().isAccountDisabled(username)) {
// Interception! This person is locked out, fail instead!
LockOutManager.getInstance().recordFailedLogin(username);
authenticationFailed(session, Failure.ACCOUNT_DISABLED);
return;
}
sendElement(session, "success", successData);
// We only support SASL for c2s
if (session instanceof ClientSession) {
final AuthToken authToken;
if (username == null) {
// AuthzId is null, which indicates that authentication was anonymous.
authToken = AuthToken.generateAnonymousToken();
} else {
authToken = AuthToken.generateUserToken(username);
}
((LocalClientSession) session).setAuthToken(authToken);
}
else if (session instanceof IncomingServerSession) {
String hostname = username;
// Add the validated domain as a valid domain. The remote server can
// now send packets from this address
((LocalIncomingServerSession) session).addValidatedDomain(hostname);
((LocalIncomingServerSession) session).setAuthenticationMethod(ServerSession.AuthenticationMethod.SASL_EXTERNAL);
Log.info("Inbound Server {} authenticated (via TLS)", username);
}
}
private static void authenticationFailed(LocalSession session, Failure failure) {
final Element reply = DocumentHelper.createElement(QName.get("failure", "urn:ietf:params:xml:ns:xmpp-sasl"));
reply.addElement(failure.toString());
session.deliverRawText(reply.asXML());
// Give a number of retries before closing the connection
Integer retries = (Integer) session.getSessionData("authRetries");
if (retries == null) {
retries = 1;
}
else {
retries = retries + 1;
}
session.setSessionData("authRetries", retries);
if (retries >= JiveGlobals.getIntProperty("xmpp.auth.retries", 3) ) {
// Close the connection
Log.debug( "Closing session that failed to authenticate {} times: {}", retries, session );
session.close();
}
}
/**
* Adds a new SASL mechanism to the list of supported SASL mechanisms by the server. The
* new mechanism will be offered to clients and connection managers as stream features.<p>
*
* Note: this method simply registers the SASL mechanism to be advertised as a supported
* mechanism by Openfire. Actual SASL handling is done by Java itself, so you must add
* the provider to Java.
*
* @param mechanismName the name of the new SASL mechanism (cannot be null or an empty String).
*/
public static void addSupportedMechanism(String mechanismName) {
if ( mechanismName == null || mechanismName.isEmpty() ) {
throw new IllegalArgumentException( "Argument 'mechanism' must cannot be null or an empty string." );
}
mechanisms.add( mechanismName.toUpperCase() );
Log.info( "Support added for the '{}' SASL mechanism.", mechanismName.toUpperCase() );
}
/**
* Removes a SASL mechanism from the list of supported SASL mechanisms by the server.
*
* @param mechanismName the name of the SASL mechanism to remove (cannot be null or empty, not case sensitive).
*/
public static void removeSupportedMechanism(String mechanismName) {
if ( mechanismName == null || mechanismName.isEmpty() ) {
throw new IllegalArgumentException( "Argument 'mechanism' must cannot be null or an empty string." );
}
if ( mechanisms.remove( mechanismName.toUpperCase() ) )
{
Log.info( "Support removed for the '{}' SASL mechanism.", mechanismName.toUpperCase() );
}
}
/**
* Returns the list of supported SASL mechanisms by the server. Note that Java may have
* support for more mechanisms but some of them may not be returned since a special setup
* is required that might be missing. Use {@link #addSupportedMechanism(String)} to add
* new SASL mechanisms.
*
* @return the list of supported SASL mechanisms by the server.
*/
public static Set<String> getSupportedMechanisms()
{
// List all mechanism names for which there's an implementation.
final Set<String> implementedMechanisms = getImplementedMechanisms();
// Start off with all mechanisms that we intend to support.
final Set<String> answer = new HashSet<>( mechanisms );
// Clean up not-available mechanisms.
for ( final Iterator<String> it = answer.iterator(); it.hasNext(); )
{
final String mechanism = it.next();
if ( !implementedMechanisms.contains( mechanism ) )
{
Log.trace( "Cannot support '{}' as there's no implementation available.", mechanism );
it.remove();
continue;
}
switch ( mechanism )
{
case "CRAM-MD5": // intended fall-through
case "DIGEST-MD5":
// Check if the user provider in use supports passwords retrieval. Access to the users passwords will be required by the CallbackHandler.
if ( !AuthFactory.supportsPasswordRetrieval() )
{
Log.trace( "Cannot support '{}' as the AuthFactory that's in use does not support password retrieval.", mechanism );
it.remove();
}
break;
case "SCRAM-SHA-1":
if ( !AuthFactory.supportsScram() )
{
Log.trace( "Cannot support '{}' as the AuthFactory that's in use does not support SCRAM.", mechanism );
it.remove();
}
break;
case "ANONYMOUS":
if (!AnonymousSaslServer.ENABLED.getValue()) {
Log.trace( "Cannot support '{}' as it has been disabled by configuration.", mechanism );
it.remove();
}
break;
case "JIVE-SHAREDSECRET":
if ( !JiveSharedSecretSaslServer.isSharedSecretAllowed() )
{
Log.trace( "Cannot support '{}' as it has been disabled by configuration.", mechanism );
it.remove();
}
break;
case "GSSAPI":
final String gssapiConfig = JiveGlobals.getProperty( "sasl.gssapi.config" );
if ( gssapiConfig != null )
{
System.setProperty( "java.security.krb5.debug", JiveGlobals.getProperty( "sasl.gssapi.debug", "false" ) );
System.setProperty( "java.security.auth.login.config", gssapiConfig );
System.setProperty( "javax.security.auth.useSubjectCredsOnly", JiveGlobals.getProperty( "sasl.gssapi.useSubjectCredsOnly", "false" ) );
}
else
{
Log.trace( "Cannot support '{}' as the 'sasl.gssapi.config' property has not been defined.", mechanism );
it.remove();
}
break;
}
}
return answer;
}
/**
* Returns a collection of mechanism names for which the JVM has an implementation available.
* <p>
* Note that this need not (and likely will not) correspond with the list of mechanisms that is offered to XMPP
* peer entities, which is provided by #getSupportedMechanisms.
*
* @return a collection of SASL mechanism names (never null, possibly empty)
*/
public static Set<String> getImplementedMechanisms()
{
final Set<String> result = new HashSet<>();
final Enumeration<SaslServerFactory> saslServerFactories = Sasl.getSaslServerFactories();
while ( saslServerFactories.hasMoreElements() )
{
final SaslServerFactory saslServerFactory = saslServerFactories.nextElement();
Collections.addAll( result, saslServerFactory.getMechanismNames( null ) );
}
return result;
}
/**
* Returns a collection of SASL mechanism names that forms the source pool from which the mechanisms that are
* eventually being offered to peers are obtained.
**
* When a mechanism is not returned by this method, it will never be offered, but when a mechanism is returned
* by this method, there is no guarantee that it will be offered.
*
* Apart from being returned in this method, an implementation must be available (see {@link #getImplementedMechanisms()}
* and configuration or other characteristics of this server must not prevent a particular mechanism from being
* used (see @{link {@link #getSupportedMechanisms()}}.
*
* @return A collection of mechanisms that are considered for use in this instance of Openfire.
*/
public static List<String> getEnabledMechanisms()
{
return JiveGlobals.getListProperty("sasl.mechs", Arrays.asList( "ANONYMOUS","PLAIN","DIGEST-MD5","CRAM-MD5","SCRAM-SHA-1","JIVE-SHAREDSECRET","GSSAPI","EXTERNAL" ) );
}
/**
* Sets the collection of mechanism names that the system administrator allows to be used.
*
* @param mechanisms A collection of mechanisms that are considered for use in this instance of Openfire. Null to reset the default setting.
* @see #getEnabledMechanisms()
*/
public static void setEnabledMechanisms( List<String> mechanisms )
{
JiveGlobals.setProperty( "sasl.mechs", mechanisms );
initMechanisms();
}
private static void initMechanisms()
{
final List<String> propertyValues = getEnabledMechanisms();
mechanisms = new HashSet<>();
for ( final String propertyValue : propertyValues )
{
try
{
addSupportedMechanism( propertyValue );
}
catch ( Exception ex )
{
Log.warn( "An exception occurred while trying to add support for SASL Mechanism '{}':", propertyValue, ex );
}
}
}
}