summaryrefslogtreecommitdiff
path: root/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java
blob: 1a1cce171b53c3a6eef416c440ffd2edbb92936a (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
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
/*
 *  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;

import org.apache.log4j.Logger;

import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.exchange.Exchange;

import org.apache.qpid.server.plugin.AccessControlFactory;
import org.apache.qpid.server.plugin.QpidServiceLoader;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.security.access.ObjectProperties;
import org.apache.qpid.server.security.access.ObjectType;
import org.apache.qpid.server.security.access.Operation;

import static org.apache.qpid.server.security.access.ObjectType.EXCHANGE;
import static org.apache.qpid.server.security.access.ObjectType.GROUP;
import static org.apache.qpid.server.security.access.ObjectType.METHOD;
import static org.apache.qpid.server.security.access.ObjectType.QUEUE;
import static org.apache.qpid.server.security.access.ObjectType.USER;
import static org.apache.qpid.server.security.access.ObjectType.VIRTUALHOST;
import static org.apache.qpid.server.security.access.Operation.BIND;
import static org.apache.qpid.server.security.access.Operation.CONSUME;
import static org.apache.qpid.server.security.access.Operation.CREATE;
import static org.apache.qpid.server.security.access.Operation.DELETE;
import static org.apache.qpid.server.security.access.Operation.PUBLISH;
import static org.apache.qpid.server.security.access.Operation.PURGE;
import static org.apache.qpid.server.security.access.Operation.UNBIND;

import javax.security.auth.Subject;
import java.net.SocketAddress;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * The security manager contains references to all loaded {@link AccessControl}s and delegates security decisions to them based
 * on virtual host name. The plugins can be external <em>OSGi</em> .jar files that export the required classes or just internal
 * objects for simpler plugins.
 *
 * @see AccessControl
 */
public class SecurityManager
{
    private static final Logger _logger = Logger.getLogger(SecurityManager.class);

    /** Container for the {@link java.security.Principal} that is using to this thread. */
    private static final ThreadLocal<Subject> _subject = new ThreadLocal<Subject>();

    public static final ThreadLocal<Boolean> _accessChecksDisabled = new ClearingThreadLocal(false);

    private Map<String, AccessControl> _globalPlugins = new HashMap<String, AccessControl>();
    private Map<String, AccessControl> _hostPlugins = new HashMap<String, AccessControl>();

    /**
     * A special ThreadLocal, which calls remove() on itself whenever the value is
     * the default, to avoid leaving a default value set after its use has passed.
     */
    private static final class ClearingThreadLocal extends ThreadLocal<Boolean>
    {
        private Boolean _defaultValue;

        public ClearingThreadLocal(Boolean defaultValue)
        {
            super();
            _defaultValue = defaultValue;
        }

        @Override
        protected Boolean initialValue()
        {
            return _defaultValue;
        }

        @Override
        public void set(Boolean value)
        {
            if (value == _defaultValue)
            {
                super.remove();
            }
            else
            {
                super.set(value);
            }
        }

        @Override
        public Boolean get()
        {
            Boolean value = super.get();
            if (value == _defaultValue)
            {
                super.remove();
            }
            return value;
        }
    }

    /*
     * Used by the VirtualHost to allow deferring to the broker level security plugins if required.
     */
    public SecurityManager(SecurityManager parent, String aclFile)
    {
        this(aclFile);

        // our global plugins are the parent's host plugins
        _globalPlugins = parent._hostPlugins;
    }

    public SecurityManager(String aclFile)
    {
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("aclFile", aclFile);
        for (AccessControlFactory provider : (new QpidServiceLoader<AccessControlFactory>()).instancesOf(AccessControlFactory.class))
        {
            AccessControl accessControl = provider.createInstance(attributes);
            if(accessControl != null)
            {
                addHostPlugin(accessControl);
            }
        }

        if(_logger.isDebugEnabled())
        {
            _logger.debug("Configured " + _hostPlugins.size() + " access control plugins");
        }
    }

    public static Subject getThreadSubject()
    {
        return _subject.get();
    }

    public static void setThreadSubject(final Subject subject)
    {
        _subject.set(subject);
    }

    public static Logger getLogger()
    {
        return _logger;
    }

    private static class CachedPropertiesMap extends LinkedHashMap<String, PublishAccessCheck>
    {
        @Override
        protected boolean removeEldestEntry(Entry<String, PublishAccessCheck> eldest)
        {
            return size() >= 200;
        }
    }

    private abstract class AccessCheck
    {
        abstract Result allowed(AccessControl plugin);
    }

    private boolean checkAllPlugins(AccessCheck checker)
    {
        if(_accessChecksDisabled.get())
        {
            return true;
        }

        Map<String, AccessControl> remainingPlugins = _globalPlugins.isEmpty()
                ? Collections.<String, AccessControl>emptyMap()
                : _hostPlugins.isEmpty() ? _globalPlugins : new HashMap<String, AccessControl>(_globalPlugins);

        if(!_hostPlugins.isEmpty())
        {
            for (Entry<String, AccessControl> hostEntry : _hostPlugins.entrySet())
            {
                // Create set of global only plugins
                AccessControl globalPlugin = remainingPlugins.get(hostEntry.getKey());
                if (globalPlugin != null)
                {
                    remainingPlugins.remove(hostEntry.getKey());
                }

                Result host = checker.allowed(hostEntry.getValue());

                if (host == Result.DENIED)
                {
                    // Something vetoed the access, we're done
                    return false;
                }

                // host allow overrides global allow, so only check global on abstain or defer
                if (host != Result.ALLOWED)
                {
                    if (globalPlugin == null)
                    {
                        if (host == Result.DEFER)
                        {
                            host = hostEntry.getValue().getDefault();
                        }
                        if (host == Result.DENIED)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        Result global = checker.allowed(globalPlugin);
                        if (global == Result.DEFER)
                        {
                            global = globalPlugin.getDefault();
                        }
                        if (global == Result.ABSTAIN && host == Result.DEFER)
                        {
                            global = hostEntry.getValue().getDefault();
                        }
                        if (global == Result.DENIED)
                        {
                            return false;
                        }
                    }
                }
            }
        }

        for (AccessControl plugin : remainingPlugins.values())
        {
            Result remaining = checker.allowed(plugin);
			if (remaining == Result.DEFER)
            {
                remaining = plugin.getDefault();
            }
			if (remaining == Result.DENIED)
            {
                return false;
            }
        }

        // getting here means either allowed or abstained from all plugins
        return true;
    }

    public boolean authoriseBind(final Exchange exch, final AMQQueue queue, final AMQShortString routingKey)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(BIND, EXCHANGE, new ObjectProperties(exch, queue, routingKey));
            }
        });
    }

    public boolean authoriseMethod(final Operation operation, final String componentName, final String methodName)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                ObjectProperties properties = new ObjectProperties();
                properties.setName(methodName);
                if (componentName != null)
                {
                    // Only set the property if there is a component name
	                properties.put(ObjectProperties.Property.COMPONENT, componentName);
                }
                return plugin.authorise(operation, METHOD, properties);
            }
        });
    }

    public boolean accessManagement()
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.access(ObjectType.MANAGEMENT, null);
            }
        });
    }

    public boolean accessVirtualhost(final String vhostname, final SocketAddress remoteAddress)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.access(VIRTUALHOST, remoteAddress);
            }
        });
    }

    public boolean authoriseConsume(final AMQQueue queue)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(CONSUME, QUEUE, new ObjectProperties(queue));
            }
        });
    }

    public boolean authoriseCreateExchange(final Boolean autoDelete, final Boolean durable, final AMQShortString exchangeName,
            final Boolean internal, final Boolean nowait, final Boolean passive, final AMQShortString exchangeType)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(CREATE, EXCHANGE, new ObjectProperties(autoDelete, durable, exchangeName,
                        internal, nowait, passive, exchangeType));
            }
        });
    }

    public boolean authoriseCreateQueue(final Boolean autoDelete, final Boolean durable, final Boolean exclusive,
            final Boolean nowait, final Boolean passive, final AMQShortString queueName, final String owner)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(CREATE, QUEUE, new ObjectProperties(autoDelete, durable, exclusive, nowait, passive, queueName, owner));
            }
        });
    }

    public boolean authoriseDelete(final AMQQueue queue)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(DELETE, QUEUE, new ObjectProperties(queue));
            }
        });
    }

    public boolean authoriseDelete(final Exchange exchange)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(DELETE, EXCHANGE, new ObjectProperties(exchange.getName()));
            }
        });
    }

    public boolean authoriseGroupOperation(final Operation operation, final String groupName)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(operation, GROUP, new ObjectProperties(groupName));
            }
        });
    }

    public boolean authoriseUserOperation(final Operation operation, final String userName)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(operation, USER, new ObjectProperties(userName));
            }
        });
    }

    private ConcurrentHashMap<String, ConcurrentHashMap<String, PublishAccessCheck>> _immediatePublishPropsCache
            = new ConcurrentHashMap<String, ConcurrentHashMap<String, PublishAccessCheck>>();
    private ConcurrentHashMap<String, ConcurrentHashMap<String, PublishAccessCheck>> _publishPropsCache
            = new ConcurrentHashMap<String, ConcurrentHashMap<String, PublishAccessCheck>>();

    public boolean authorisePublish(final boolean immediate, String routingKey, String exchangeName)
    {
        if(routingKey == null)
        {
            routingKey = "";
        }
        if(exchangeName == null)
        {
            exchangeName = "";
        }
        PublishAccessCheck check;
        ConcurrentHashMap<String, ConcurrentHashMap<String, PublishAccessCheck>> cache =
                immediate ? _immediatePublishPropsCache : _publishPropsCache;

        ConcurrentHashMap<String, PublishAccessCheck> exchangeMap = cache.get(exchangeName);
        if(exchangeMap == null)
        {
            cache.putIfAbsent(exchangeName, new ConcurrentHashMap<String, PublishAccessCheck>());
            exchangeMap = cache.get(exchangeName);
        }

            check = exchangeMap.get(routingKey);
            if(check == null)
            {
                check = new PublishAccessCheck(new ObjectProperties(exchangeName, routingKey, immediate));
                exchangeMap.put(routingKey, check);
            }

        return checkAllPlugins(check);
    }

    public boolean authorisePurge(final AMQQueue queue)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(PURGE, QUEUE, new ObjectProperties(queue));
            }
        });
    }

    public boolean authoriseUnbind(final Exchange exch, final AMQShortString routingKey, final AMQQueue queue)
    {
        return checkAllPlugins(new AccessCheck()
        {
            Result allowed(AccessControl plugin)
            {
                return plugin.authorise(UNBIND, EXCHANGE, new ObjectProperties(exch, queue, routingKey));
            }
        });
    }

    public static boolean setAccessChecksDisabled(final boolean status)
    {
        //remember current value
        boolean current = _accessChecksDisabled.get();

        _accessChecksDisabled.set(status);

        return current;
    }

    private class PublishAccessCheck extends AccessCheck
    {
        private final ObjectProperties _props;

        public PublishAccessCheck(ObjectProperties props)
        {
            _props = props;
        }

        Result allowed(AccessControl plugin)
        {
            return plugin.authorise(PUBLISH, EXCHANGE, _props);
        }
    }


    public void addHostPlugin(AccessControl plugin)
    {
        _hostPlugins.put(plugin.getClass().getName(), plugin);
    }

}