summaryrefslogtreecommitdiff
path: root/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractScramAuthenticationManager.java
blob: 152a9086ec5166a6dce488844be02c31129a75a2 (plain)
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
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.qpid.server.security.auth.manager;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.security.auth.login.AccountNotFoundException;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.xml.bind.DatatypeConverter;

import org.apache.qpid.server.configuration.updater.Task;
import org.apache.qpid.server.configuration.updater.VoidTaskWithException;
import org.apache.qpid.server.model.Broker;
import org.apache.qpid.server.model.ConfiguredObject;
import org.apache.qpid.server.model.PasswordCredentialManagingAuthenticationProvider;
import org.apache.qpid.server.model.User;
import org.apache.qpid.server.security.access.Operation;
import org.apache.qpid.server.security.auth.AuthenticationResult;
import org.apache.qpid.server.security.auth.UsernamePrincipal;
import org.apache.qpid.server.security.auth.sasl.plain.PlainAdapterSaslServer;
import org.apache.qpid.server.security.auth.sasl.scram.ScramSaslServer;

public abstract class AbstractScramAuthenticationManager<X extends AbstractScramAuthenticationManager<X>>
        extends AbstractAuthenticationManager<X>
        implements PasswordCredentialManagingAuthenticationProvider<X>
{

    static final Charset ASCII = Charset.forName("ASCII");
    public static final String PLAIN = "PLAIN";
    private final SecureRandom _random = new SecureRandom();

    private int _iterationCount = 4096;

    private Map<String, ScramAuthUser> _users = new ConcurrentHashMap<String, ScramAuthUser>();


    protected AbstractScramAuthenticationManager(final Map<String, Object> attributes, final Broker broker)
    {
        super(attributes, broker);
    }

    @Override
    public List<String> getMechanisms()
    {
        return Collections.unmodifiableList(Arrays.asList(getMechanismName(), PLAIN));
    }

    protected abstract String getMechanismName();

    @Override
    public SaslServer createSaslServer(final String mechanism,
                                       final String localFQDN,
                                       final Principal externalPrincipal)
            throws SaslException
    {
        if(getMechanismName().equals(mechanism))
        {
            return new ScramSaslServer(this, getMechanismName(), getHmacName(), getDigestName());
        }
        else if(PLAIN.equals(mechanism))
        {
            return new PlainAdapterSaslServer(this);
        }
        else
        {
            throw new SaslException("Unknown mechanism: " + mechanism);
        }
    }

    protected abstract String getDigestName();

    @Override
    public AuthenticationResult authenticate(final SaslServer server, final byte[] response)
    {
        try
        {
            // Process response from the client
            byte[] challenge = server.evaluateResponse(response != null ? response : new byte[0]);

            if (server.isComplete() && (challenge == null || challenge.length == 0))
            {
                final String userId = server.getAuthorizationID();
                return new AuthenticationResult(new UsernamePrincipal(userId));
            }
            else
            {
                return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
            }
        }
        catch (SaslException e)
        {
            return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
        }
    }

    @Override
    public AuthenticationResult authenticate(final String username, final String password)
    {
        ScramAuthUser user = getUser(username);
        if(user != null)
        {
            final String[] usernamePassword = user.getPassword().split(",");
            byte[] salt = DatatypeConverter.parseBase64Binary(usernamePassword[0]);
            try
            {
                if(Arrays.equals(DatatypeConverter.parseBase64Binary(usernamePassword[1]),
                                 createSaltedPassword(salt, password)))
                {
                    return new AuthenticationResult(new UsernamePrincipal(username));
                }
            }
            catch (SaslException e)
            {
                return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR,e);
            }

        }

        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR);


    }


    public int getIterationCount()
    {
        return _iterationCount;
    }

    public byte[] getSalt(final String username)
    {
        ScramAuthUser user = getUser(username);

        if(user == null)
        {
            // don't disclose that the user doesn't exist, just generate random data so the failure is indistinguishable
            // from the "wrong password" case

            byte[] salt = new byte[32];
            _random.nextBytes(salt);
            return salt;
        }
        else
        {
            return DatatypeConverter.parseBase64Binary(user.getPassword().split(",")[0]);
        }
    }

    private static final byte[] INT_1 = new byte[]{0, 0, 0, 1};

    public byte[] getSaltedPassword(final String username) throws SaslException
    {
        ScramAuthUser user = getUser(username);
        if(user == null)
        {
            throw new SaslException("Authentication Failed");
        }
        else
        {
            return DatatypeConverter.parseBase64Binary(user.getPassword().split(",")[1]);
        }
    }

    private ScramAuthUser getUser(final String username)
    {
        return _users.get(username);
    }

    private byte[] createSaltedPassword(byte[] salt, String password) throws SaslException
    {
        Mac mac = createSha1Hmac(password.getBytes(ASCII));

        mac.update(salt);
        mac.update(INT_1);
        byte[] result = mac.doFinal();

        byte[] previous = null;
        for(int i = 1; i < getIterationCount(); i++)
        {
            mac.update(previous != null? previous: result);
            previous = mac.doFinal();
            for(int x = 0; x < result.length; x++)
            {
                result[x] ^= previous[x];
            }
        }

        return result;

    }

    private Mac createSha1Hmac(final byte[] keyBytes)
            throws SaslException
    {
        try
        {
            SecretKeySpec key = new SecretKeySpec(keyBytes, getHmacName());
            Mac mac = Mac.getInstance(getHmacName());
            mac.init(key);
            return mac;
        }
        catch (NoSuchAlgorithmException e)
        {
            throw new SaslException(e.getMessage(), e);
        }
        catch (InvalidKeyException e)
        {
            throw new SaslException(e.getMessage(), e);
        }
    }

    protected abstract String getHmacName();

    @Override
    public boolean createUser(final String username, final String password, final Map<String, String> attributes)
    {
        return runTask(new Task<Boolean>()
        {
            @Override
            public Boolean execute()
            {
                getSecurityManager().authoriseUserOperation(Operation.CREATE, username);
                if (_users.containsKey(username))
                {
                    throw new IllegalArgumentException("User '" + username + "' already exists");
                }
                try
                {
                    Map<String, Object> userAttrs = new HashMap<String, Object>();
                    userAttrs.put(User.ID, UUID.randomUUID());
                    userAttrs.put(User.NAME, username);
                    userAttrs.put(User.PASSWORD, createStoredPassword(password));
                    userAttrs.put(User.TYPE, ScramAuthUser.SCRAM_USER_TYPE);
                    ScramAuthUser user = new ScramAuthUser(userAttrs, AbstractScramAuthenticationManager.this);
                    user.create();

                    return true;
                }
                catch (SaslException e)
                {
                    throw new IllegalArgumentException(e);
                }
            }
        });
    }

    org.apache.qpid.server.security.SecurityManager getSecurityManager()
    {
        return getBroker().getSecurityManager();
    }

    @Override
    public void deleteUser(final String user) throws AccountNotFoundException
    {
        runTask(new VoidTaskWithException<AccountNotFoundException>()
        {
            @Override
            public void execute() throws AccountNotFoundException
            {
                final ScramAuthUser authUser = getUser(user);
                if(authUser != null)
                {
                    authUser.delete();
                }
                else
                {
                    throw new AccountNotFoundException("No such user: '" + user + "'");
                }
            }
        });
    }

    @Override
    public void setPassword(final String username, final String password) throws AccountNotFoundException
    {
        runTask(new VoidTaskWithException<AccountNotFoundException>()
        {
            @Override
            public void execute() throws AccountNotFoundException
            {

                final ScramAuthUser authUser = getUser(username);
                if (authUser != null)
                {
                    authUser.setPassword(password);
                }
                else
                {
                    throw new AccountNotFoundException("No such user: '" + username + "'");
                }
            }
        });

    }

    @Override
    public Map<String, Map<String, String>> getUsers()
    {
        return runTask(new Task<Map<String, Map<String, String>>>()
        {
            @Override
            public Map<String, Map<String, String>> execute()
            {

                Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
                for (String user : _users.keySet())
                {
                    users.put(user, Collections.<String, String>emptyMap());
                }
                return users;
            }
        });
    }

    @Override
    public void reload() throws IOException
    {

    }

    @Override
    public void recoverUser(final User user)
    {
        _users.put(user.getName(), (ScramAuthUser) user);
    }

    protected String createStoredPassword(final String password) throws SaslException
    {
        byte[] salt = new byte[32];
        _random.nextBytes(salt);
        byte[] passwordBytes = createSaltedPassword(salt, password);
        return DatatypeConverter.printBase64Binary(salt) + "," + DatatypeConverter.printBase64Binary(passwordBytes);
    }

    @Override
    public <C extends ConfiguredObject> C addChild(final Class<C> childClass,
                                                   final Map<String, Object> attributes,
                                                   final ConfiguredObject... otherParents)
    {
        if(childClass == User.class)
        {
            String username = (String) attributes.get("name");
            String password = (String) attributes.get("password");

            if(createUser(username, password,null))
            {
                @SuppressWarnings("unchecked")
                C user = (C) _users.get(username);
                return user;
            }
            else
            {
                return null;

            }
        }
        return super.addChild(childClass, attributes, otherParents);
    }

    Map<String, ScramAuthUser> getUserMap()
    {
        return _users;
    }

}