mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Matthew Swift
30.25.2013 ad636a8035cc19f5a412b6b97b3f95ba37d0fe9a
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2010 Sun Microsystems, Inc.
 *      Portions copyright 2011-2013 ForgeRock AS
 */
 
package org.forgerock.opendj.ldap.requests;
 
import static com.forgerock.opendj.util.StaticUtils.copyOfBytes;
import static com.forgerock.opendj.util.StaticUtils.getExceptionMessage;
import static com.forgerock.opendj.util.StaticUtils.joinCollection;
import static org.forgerock.opendj.ldap.CoreMessages.ERR_SASL_PROTOCOL_ERROR;
import static org.forgerock.opendj.ldap.ErrorResultException.newErrorResult;
 
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
 
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ConnectionSecurityLayer;
import org.forgerock.opendj.ldap.ErrorResultException;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.responses.BindResult;
 
import com.forgerock.opendj.util.StaticUtils;
import com.forgerock.opendj.util.Validator;
 
/**
 * Digest-MD5 SASL bind request implementation.
 */
final class DigestMD5SASLBindRequestImpl extends AbstractSASLBindRequest<DigestMD5SASLBindRequest>
        implements DigestMD5SASLBindRequest {
    private final static class Client extends SASLBindClientImpl {
        private final String authenticationID;
        private final ByteString password;
        private final String realm;
        private final SaslClient saslClient;
 
        private Client(final DigestMD5SASLBindRequestImpl initialBindRequest,
                final String serverName) throws ErrorResultException {
            super(initialBindRequest);
 
            this.authenticationID = initialBindRequest.getAuthenticationID();
            this.password = ByteString.wrap(initialBindRequest.getPassword());
            this.realm = initialBindRequest.getRealm();
 
            // Create property map containing all the parameters.
            final Map<String, String> props = new HashMap<String, String>();
 
            final List<String> qopValues = initialBindRequest.getQOPs();
            if (!qopValues.isEmpty()) {
                props.put(Sasl.QOP, joinCollection(qopValues, ","));
            }
 
            final String cipher = initialBindRequest.getCipher();
            if (cipher != null) {
                if (cipher.equalsIgnoreCase(CIPHER_LOW)) {
                    props.put(Sasl.STRENGTH, "high,medium,low");
                } else if (cipher.equalsIgnoreCase(CIPHER_MEDIUM)) {
                    props.put(Sasl.STRENGTH, "high,medium");
                } else if (cipher.equalsIgnoreCase(CIPHER_HIGH)) {
                    props.put(Sasl.STRENGTH, "high");
                } else {
                    /*
                     * Default strength allows all ciphers, so specifying a
                     * single cipher cannot be incompatible with the strength.
                     */
                    props.put("com.sun.security.sasl.digest.cipher", cipher);
                }
            }
 
            final Boolean serverAuth = initialBindRequest.isServerAuth();
            if (serverAuth != null) {
                props.put(Sasl.SERVER_AUTH, String.valueOf(serverAuth));
            }
 
            Integer size = initialBindRequest.getMaxReceiveBufferSize();
            if (size != null) {
                props.put(Sasl.MAX_BUFFER, String.valueOf(size));
            }
 
            size = initialBindRequest.getMaxSendBufferSize();
            if (size != null) {
                props.put("javax.security.sasl.sendmaxbuffer", String.valueOf(size));
            }
 
            for (final Map.Entry<String, String> e : initialBindRequest.getAdditionalAuthParams()
                    .entrySet()) {
                props.put(e.getKey(), e.getValue());
            }
 
            // Now create the client.
            try {
                saslClient =
                        Sasl.createSaslClient(new String[] { SASL_MECHANISM_NAME },
                                initialBindRequest.getAuthorizationID(), SASL_DEFAULT_PROTOCOL,
                                serverName, props, this);
                if (saslClient.hasInitialResponse()) {
                    setNextSASLCredentials(saslClient.evaluateChallenge(new byte[0]));
                } else {
                    setNextSASLCredentials((ByteString) null);
                }
            } catch (final SaslException e) {
                throw newErrorResult(ResultCode.CLIENT_SIDE_LOCAL_ERROR, e);
            }
        }
 
        @Override
        public void dispose() {
            try {
                saslClient.dispose();
            } catch (final SaslException ignored) {
                // Ignore the SASL exception.
            }
        }
 
        @Override
        public boolean evaluateResult(final BindResult result) throws ErrorResultException {
            if (saslClient.isComplete()) {
                return true;
            }
 
            try {
                setNextSASLCredentials(saslClient.evaluateChallenge(result
                        .getServerSASLCredentials() == null ? new byte[0] : result
                        .getServerSASLCredentials().toByteArray()));
                return saslClient.isComplete();
            } catch (final SaslException e) {
                // FIXME: I18N need to have a better error message.
                // FIXME: Is this the best result code?
                throw newErrorResult(ResultCode.CLIENT_SIDE_LOCAL_ERROR,
                        "An error occurred during multi-stage authentication", e);
            }
        }
 
        @Override
        public ConnectionSecurityLayer getConnectionSecurityLayer() {
            final String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
            if (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf")) {
                return this;
            } else {
                return null;
            }
        }
 
        @Override
        public byte[] unwrap(final byte[] incoming, final int offset, final int len)
                throws ErrorResultException {
            try {
                return saslClient.unwrap(incoming, offset, len);
            } catch (final SaslException e) {
                final LocalizableMessage msg =
                        ERR_SASL_PROTOCOL_ERROR.get(SASL_MECHANISM_NAME, getExceptionMessage(e));
                throw newErrorResult(ResultCode.CLIENT_SIDE_DECODING_ERROR, msg.toString(), e);
            }
        }
 
        @Override
        public byte[] wrap(final byte[] outgoing, final int offset, final int len)
                throws ErrorResultException {
            try {
                return saslClient.wrap(outgoing, offset, len);
            } catch (final SaslException e) {
                final LocalizableMessage msg =
                        ERR_SASL_PROTOCOL_ERROR.get(SASL_MECHANISM_NAME, getExceptionMessage(e));
                throw newErrorResult(ResultCode.CLIENT_SIDE_ENCODING_ERROR, msg.toString(), e);
            }
        }
 
        @Override
        void handle(final NameCallback callback) throws UnsupportedCallbackException {
            callback.setName(authenticationID);
        }
 
        @Override
        void handle(final PasswordCallback callback) throws UnsupportedCallbackException {
            callback.setPassword(password.toString().toCharArray());
        }
 
        @Override
        void handle(final RealmCallback callback) throws UnsupportedCallbackException {
            if (realm == null) {
                callback.setText(callback.getDefaultText());
            } else {
                callback.setText(realm);
            }
        }
 
    }
 
    private final Map<String, String> additionalAuthParams = new LinkedHashMap<String, String>();
    private String authenticationID;
    private String authorizationID = null;
 
    private String cipher = null;
    private Integer maxReceiveBufferSize = null;
    private Integer maxSendBufferSize = null;
    private byte[] password;
    private final List<String> qopValues = new LinkedList<String>();
    private String realm = null;
    /*
     * Don't use primitives for these so that we can distinguish between default
     * settings (null) and values set by the caller.
     */
    private Boolean serverAuth = null;
 
    DigestMD5SASLBindRequestImpl(final DigestMD5SASLBindRequest digestMD5SASLBindRequest) {
        super(digestMD5SASLBindRequest);
        this.additionalAuthParams.putAll(digestMD5SASLBindRequest.getAdditionalAuthParams());
        this.qopValues.addAll(digestMD5SASLBindRequest.getQOPs());
        this.cipher = digestMD5SASLBindRequest.getCipher();
 
        this.serverAuth = digestMD5SASLBindRequest.isServerAuth();
        this.maxReceiveBufferSize = digestMD5SASLBindRequest.getMaxReceiveBufferSize();
        this.maxSendBufferSize = digestMD5SASLBindRequest.getMaxSendBufferSize();
 
        this.authenticationID = digestMD5SASLBindRequest.getAuthenticationID();
        this.authorizationID = digestMD5SASLBindRequest.getAuthorizationID();
        this.password = copyOfBytes(digestMD5SASLBindRequest.getPassword());
        this.realm = digestMD5SASLBindRequest.getRealm();
    }
 
    DigestMD5SASLBindRequestImpl(final String authenticationID, final byte[] password) {
        Validator.ensureNotNull(authenticationID, password);
        this.authenticationID = authenticationID;
        this.password = password;
    }
 
    @Override
    public DigestMD5SASLBindRequest addAdditionalAuthParam(final String name, final String value) {
        Validator.ensureNotNull(name, value);
        additionalAuthParams.put(name, value);
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest addQOP(final String... qopValues) {
        for (final String qopValue : qopValues) {
            this.qopValues.add(Validator.ensureNotNull(qopValue));
        }
        return this;
    }
 
    @Override
    public BindClient createBindClient(final String serverName) throws ErrorResultException {
        return new Client(this, serverName);
    }
 
    @Override
    public Map<String, String> getAdditionalAuthParams() {
        return additionalAuthParams;
    }
 
    @Override
    public String getAuthenticationID() {
        return authenticationID;
    }
 
    @Override
    public String getAuthorizationID() {
        return authorizationID;
    }
 
    @Override
    public String getCipher() {
        return cipher;
    }
 
    @Override
    public int getMaxReceiveBufferSize() {
        return maxReceiveBufferSize == null ? 65536 : maxReceiveBufferSize;
    }
 
    @Override
    public int getMaxSendBufferSize() {
        return maxSendBufferSize == null ? 65536 : maxSendBufferSize;
    }
 
    @Override
    public byte[] getPassword() {
        return password;
    }
 
    @Override
    public List<String> getQOPs() {
        return qopValues;
    }
 
    @Override
    public String getRealm() {
        return realm;
    }
 
    @Override
    public String getSASLMechanism() {
        return SASL_MECHANISM_NAME;
    }
 
    @Override
    public boolean isServerAuth() {
        return serverAuth == null ? false : serverAuth;
    }
 
    @Override
    public DigestMD5SASLBindRequest setAuthenticationID(final String authenticationID) {
        Validator.ensureNotNull(authenticationID);
        this.authenticationID = authenticationID;
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setAuthorizationID(final String authorizationID) {
        this.authorizationID = authorizationID;
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setCipher(final String cipher) {
        this.cipher = cipher;
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setMaxReceiveBufferSize(final int size) {
        maxReceiveBufferSize = size;
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setMaxSendBufferSize(final int size) {
        maxSendBufferSize = size;
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setPassword(final byte[] password) {
        Validator.ensureNotNull(password);
        this.password = password;
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setPassword(final char[] password) {
        Validator.ensureNotNull(password);
        this.password = StaticUtils.getBytes(password);
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setRealm(final String realm) {
        this.realm = realm;
        return this;
    }
 
    @Override
    public DigestMD5SASLBindRequest setServerAuth(final boolean serverAuth) {
        this.serverAuth = serverAuth;
        return this;
    }
 
    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("DigestMD5SASLBindRequest(bindDN=");
        builder.append(getName());
        builder.append(", authentication=SASL");
        builder.append(", saslMechanism=");
        builder.append(getSASLMechanism());
        builder.append(", authenticationID=");
        builder.append(authenticationID);
        builder.append(", authorizationID=");
        builder.append(authorizationID);
        builder.append(", realm=");
        builder.append(realm);
        builder.append(", controls=");
        builder.append(getControls());
        builder.append(")");
        return builder.toString();
    }
}