Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/LDAPSaslBind.java

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is mozilla.org code.
17 *
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 2001
21 * the Initial Developer. All Rights Reserved.
22 *
23 * Contributor(s):
24 *
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
36 *
37 * ***** END LICENSE BLOCK ***** */
38 package org.ietf.ldap;
39
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.OutputStream;
43 import java.io.Serializable;
44 import java.util.HashMap;
45 import java.util.Map;
46 import java.util.StringTokenizer;
47
48 import javax.security.auth.callback.CallbackHandler;
49 import javax.security.sasl.SaslClient;
50
51 import org.ietf.ldap.client.opers.JDAPBindRequest;
52 import org.ietf.ldap.client.opers.JDAPBindResponse;
53 import org.ietf.ldap.client.opers.JDAPProtocolOp;
54
55 /**
56 * Authenticates to a server using SASL
57 */
58 public class LDAPSaslBind implements LDAPBindHandler, Serializable {
59
60 static final long serialVersionUID = -7615315715163655443L;
61
62 /**
63 * Construct an object which can authenticate to an LDAP server
64 * using the specified name and a specified SASL mechanism.
65 *
66 * @param dn if non-null and non-empty, specifies that the connection and
67 * all operations through it should authenticate with dn as the
68 * distinguished name
69 * @param mechanisms array of mechanism names, e.g. { "GSSAPI", "SKEY" }
70 * @param props optional additional properties of the desired
71 * authentication mechanism, e.g. minimum security level
72 * @param cbh a class which may be called by the SASL framework to
73 * obtain additional required information
74 */
75 public LDAPSaslBind( String dn,
76 String[] mechanisms,
77 Map<String, String> props,
78 CallbackHandler cbh ) {
79 _dn = dn;
80 _mechanisms = mechanisms;
81 _props = props;
82 _cbh = cbh;
83 }
84
85 /**
86 * Authenticates to the LDAP server (that the object is currently
87 * connected to) using the parameters that were provided to the
88 * constructor. If the requested SASL mechanism is not
89 * available, an exception is thrown. If the object has been
90 * disconnected from an LDAP server, this method attempts to reconnect
91 * to the server. If the object had already authenticated, the old
92 * authentication is discarded.
93 *
94 * @param ldc an active connection to a server, which will have
95 * the new authentication state on return from the method
96 * @exception LDAPException Failed to authenticate to the LDAP server.
97 */
98 public void bind( LDAPConnection ldc ) throws LDAPException {
99 if ( _props == null ) {
100 _props = new HashMap<>();
101 }
102 String packageNames = _props.get( CLIENTPKGS );
103 if ( packageNames == null ) {
104 packageNames = System.getProperty( CLIENTPKGS );
105 }
106 if ( packageNames == null ) {
107 packageNames = LDAPConnection.DEFAULT_SASL_PACKAGE;
108 }
109 StringTokenizer st = new StringTokenizer( packageNames, "|" );
110 while( st.hasMoreTokens() ) {
111 String packageName = st.nextToken();
112 try {
113 _saslClient = getClient( ldc, packageName );
114 if ( _saslClient != null ) {
115 break;
116 }
117 } catch ( LDAPException e ) {
118 if ( !st.hasMoreTokens() ) {
119 throw e;
120 }
121 }
122 }
123 if ( _saslClient == null ) {
124 LDAPConnection.printDebug( "LDAPSaslBind.bind: getClient " +
125 "returned null" );
126 } else {
127 bind( ldc, true );
128 }
129 }
130
131 /**
132 * Authenticates to the LDAP server (that the object is currently
133 * connected to) using the parameters that were provided to the
134 * constructor. If the requested SASL mechanism is not
135 * available, an exception is thrown. If the object has been
136 * disconnected from an LDAP server, this method attempts to reconnect
137 * to the server. If the object had already authenticated, the old
138 * authentication is discarded.
139 *
140 * @param ldapurls urls which may be selected to connect and bind to
141 * @param ldc an active connection to a server, which will have
142 * the new authentication state on return from the method
143 * @exception LDAPReferralException Failed to authenticate to the LDAP
144 * server
145 */
146 @Override
147 public void bind( String[] ldapurls,
148 LDAPConnection conn ) throws LDAPReferralException {
149 try {
150 // ??? What to do with the URLs?
151 bind( conn );
152 } catch ( LDAPReferralException ex ) {
153 throw ex;
154 } catch ( LDAPException ex ) {
155 // ???
156 throw new LDAPReferralException( ex.getMessage(),
157 ex.getResultCode(),
158 ex.getLDAPErrorMessage() );
159 }
160 }
161
162 /**
163 * Get a SaslClient object from the Sasl framework
164 *
165 * @param ldc contains the host name
166 * @param packageName package containing a ClientFactory
167 * @return a SaslClient supporting one of the mechanisms
168 * of the member variable _mechanisms.
169 * @exception LDAPException on error producing a client
170 */
171 private Object getClient( LDAPConnection ldc, String packageName )
172 throws LDAPException {
173 try {
174 Object[] args = new Object[6];
175 args[0] = _mechanisms;
176 args[1] = _dn;
177 args[2] = "ldap";
178 args[3] = ldc.getHost();
179 args[4] = _props;
180 args[5] = _cbh;
181 String[] argNames = new String[6];
182 argNames[0] = "[Ljava.lang.String;";
183 argNames[1] = "java.lang.String";
184 argNames[2] = "java.lang.String";
185 argNames[3] = "java.lang.String";
186 argNames[4] = "java.util.Map";
187 argNames[5] = CALLBACK_HANDLER;
188
189 // Get a mechanism driver
190 return DynamicInvoker.invokeMethod( null,
191 "javax.security.sasl.Sasl",
192 "createSaslClient",
193 args, argNames );
194
195 } catch ( Exception e ) {
196 LDAPConnection.printDebug( "LDAPSaslBind.getClient: " +
197 packageName+".Sasl.createSaslClient: " +
198 e );
199 throw new LDAPException( e.toString(), LDAPException.OTHER );
200 }
201 }
202
203 void bind( LDAPConnection ldc, boolean rebind )
204 throws LDAPException {
205
206 if ( (ldc.isConnected() && rebind) ||
207 !ldc.isConnected() ) {
208 try {
209 String className = _saslClient.getClass().getName();
210 LDAPConnection.printDebug( "LDAPSaslBind.bind: calling " +
211 className+".hasInitialResponse" );
212 // Get initial response if any
213 byte[] outVals = null;
214 if ( hasInitialResponse() ) {
215 outVals = evaluateChallenge( new byte[0] );
216 }
217
218 String mechanismName = getMechanismName();
219 LDAPConnection.printDebug( "LDAPSaslBind.bind: mechanism " +
220 "name is " +
221 mechanismName );
222 boolean isExternal = isExternalMechanism( mechanismName );
223 LDAPConnection.printDebug( "LDAPSaslBind.bind: calling " +
224 "saslBind" );
225 JDAPBindResponse response =
226 saslBind( ldc, mechanismName, outVals );
227 int resultCode = response.getResultCode();
228 while (!checkForSASLBindCompletion(resultCode)) {
229 if ( isExternal ) {
230 continue;
231 }
232 byte[] b = response.getCredentials();
233 if ( b == null ) {
234 b = new byte[0];
235 }
236 outVals = evaluateChallenge( b );
237 LDAPConnection.printDebug( "SaslClient.evaluateChallenge returned [" +
238 ((outVals != null) ?
239 new String( outVals ) : "null") +
240 "] for [" + new String( b ) + "]" );
241
242 if ( resultCode == LDAPException.SUCCESS ) {
243 // we're done; don't expect to send another BIND
244 if ( outVals != null ) {
245 throw new LDAPException(
246 "Protocol error: attempting to send " +
247 "response after completion" );
248 }
249 break;
250 }
251 response = saslBind( ldc, mechanismName, outVals );
252 resultCode = response.getResultCode();
253 }
254
255 // Make sure authentication REALLY is complete
256 if ( !isComplete() ) {
257 // Authentication session hijacked!
258 throw new LDAPException( "The server indicates that " +
259 "authentication is successful" +
260 ", but the SASL driver " +
261 "indicates that authentication" +
262 " is not yet done.",
263 LDAPException.OTHER );
264 } else if ( resultCode == LDAPException.SUCCESS ) {
265 // Has a security layer been negotiated?
266 String qop = (String)getNegotiatedProperty( QOP );
267 if ( (qop != null) &&
268 (qop.equalsIgnoreCase("auth-int") ||
269 qop.equalsIgnoreCase("auth-conf")) ) {
270
271 // Use SaslClient.wrap() and SaslClient.unwrap() for
272 // future communication with server
273 ldc.setInputStream(
274 new SecureInputStream(ldc.getInputStream()));
275 ldc.setOutputStream(
276 new SecureOutputStream(ldc.getOutputStream()));
277 }
278 ldc.markConnAsBound();
279 }
280
281 } catch (LDAPException e) {
282 throw e;
283 } catch (Exception e) {
284 throw new LDAPException(e.toString(), LDAPException.OTHER);
285 }
286 }
287 }
288
289 boolean isExternalMechanism( String name ) {
290 return name.equalsIgnoreCase( LDAPConnection.EXTERNAL_MECHANISM );
291 }
292
293 // Wrapper functions for dynamically invoking methods of SaslClient
294 private boolean checkForSASLBindCompletion(int resultCode) throws LDAPException {
295
296 LDAPConnection.printDebug( "LDAPSaslBind.bind: saslBind " +
297 "returned " + resultCode );
298 if ( isComplete() ) {
299 if ( (resultCode == LDAPException.SUCCESS) ||
300 (resultCode == LDAPException.SASL_BIND_IN_PROGRESS) ) {
301 return true;
302 }
303 throw new LDAPException( "Authentication failed", resultCode );
304 }
305 return false;
306 }
307
308 private boolean hasInitialResponse()
309 throws LDAPException {
310 if ( _useReflection ) {
311 return ((Boolean)DynamicInvoker.invokeMethod(
312 _saslClient,
313 _saslClient.getClass().getName(),
314 "hasInitialResponse",
315 null,
316 null)).booleanValue();
317 }
318 return ((SaslClient)_saslClient).hasInitialResponse();
319 }
320
321 private String getMechanismName()
322 throws LDAPException {
323 if ( _useReflection ) {
324 return (String)DynamicInvoker.invokeMethod(
325 _saslClient,
326 _saslClient.getClass().getName(),
327 "getMechanismName",
328 null,
329 null );
330 }
331 return ((SaslClient)_saslClient).getMechanismName();
332 }
333
334 private boolean isComplete()
335 throws LDAPException {
336 if ( _useReflection ) {
337 return ((Boolean)DynamicInvoker.invokeMethod(
338 _saslClient,
339 _saslClient.getClass().getName(),
340 "isComplete",
341 null,
342 null)).booleanValue();
343 }
344 return ((SaslClient)_saslClient).isComplete();
345 }
346
347 private byte[] evaluateChallenge( byte[] b )
348 throws LDAPException {
349 try {
350 if ( _useReflection ) {
351 Object[] args = { b };
352 String[] argNames = { "[B" }; // class name for byte array
353 return (byte[])DynamicInvoker.invokeMethod(
354 _saslClient,
355 _saslClient.getClass().getName(),
356 "evaluateChallenge",
357 args,
358 argNames );
359 }
360 return ((SaslClient)_saslClient).evaluateChallenge( b );
361 } catch ( Exception e ) {
362 throw new LDAPException( "",
363 LDAPException.PARAM_ERROR,
364 e );
365 }
366 }
367
368 private Object getNegotiatedProperty( String propName )
369 throws LDAPException {
370 try {
371 if ( _useReflection ) {
372 Object[] args = { propName };
373 String[] argNames = { "String" };
374 return DynamicInvoker.invokeMethod(
375 _saslClient,
376 _saslClient.getClass().getName(),
377 "getNegotiatedProperty",
378 args,
379 argNames );
380 }
381 return ((SaslClient)_saslClient).getNegotiatedProperty(
382 propName );
383 } catch ( Exception e ) {
384 throw new LDAPException( "",
385 LDAPException.PARAM_ERROR,
386 e );
387 }
388 }
389
390 private JDAPBindResponse saslBind( LDAPConnection ldc,
391 String mechanismName,
392 byte[] credentials )
393 throws LDAPException {
394
395 LDAPResponseQueue myListener = ldc.getResponseListener();
396
397 try {
398 ldc.sendRequest( new JDAPBindRequest( 3,
399 _dn,
400 mechanismName,
401 credentials ),
402 myListener, ldc.getConstraints() );
403 LDAPMessage response = myListener.getResponse();
404
405 JDAPProtocolOp protocolOp = response.getProtocolOp();
406 if ( protocolOp instanceof JDAPBindResponse ) {
407 return (JDAPBindResponse)protocolOp;
408 }
409 throw new LDAPException( "Unknown response from the " +
410 "server during SASL bind",
411 LDAPException.OTHER );
412 } finally {
413 ldc.releaseResponseListener( myListener );
414 }
415 }
416
417 private static final String CALLBACK_HANDLER =
418 "javax.security.auth.callback.CallbackHandler";
419 static final String CLIENTPKGS =
420 "javax.security.sasl.client.pkgs";
421 private static final String QOP = "javax.security.sasl.qop";
422 private static final String REFLECTION_PROP =
423 "org.ietf.ldap.sasl.reflect";
424 private String _dn;
425 private String[] _mechanisms;
426 private Map<String, String> _props = null;
427 private CallbackHandler _cbh;
428 private Object _saslClient = null;
429 private static boolean _useReflection =
430 ( System.getProperty(REFLECTION_PROP) != null );
431
432 // ??? Security layer support not implemented
433 class SecureInputStream extends InputStream {
434 public SecureInputStream(InputStream is) {
435 _input = is;
436 }
437 @Override
438 public int read() throws IOException {
439 return _input.read();
440 }
441 private InputStream _input;
442 }
443
444 class SecureOutputStream extends OutputStream {
445 public SecureOutputStream( OutputStream os) {
446 _output = os;
447 }
448 @Override
449 public void write( int b ) throws IOException {
450 _output.write( b );
451 }
452 private OutputStream _output;
453 }
454 }