summaryrefslogtreecommitdiff
path: root/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java
blob: ebc73440ed01be3c1d15e09cff14c9c46d994c45 (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
481
482
483
484
485
486
487
488
489
/*
 *  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.access.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.WeakHashMap;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.server.logging.actors.CurrentActor;
import org.apache.qpid.server.security.Result;
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 org.apache.qpid.server.security.access.Permission;
import org.apache.qpid.server.security.access.logging.AccessControlMessages;

/**
 * Models the rule configuration for the access control plugin.
 *
 * The access control rule definitions are loaded from an external configuration file, passed in as the
 * target to the {@link load(ConfigurationFile)} method. The file specified 
 */
public class RuleSet
{
    private static final Logger _logger = Logger.getLogger(RuleSet.class);
    
    private static final String AT = "@";
	private static final String SLASH = "/";

	public static final String DEFAULT_ALLOW = "defaultallow";
	public static final String DEFAULT_DENY = "defaultdeny";
	public static final String TRANSITIVE = "transitive";
	public static final String EXPAND = "expand";
    public static final String AUTONUMBER = "autonumber";
    public static final String CONTROLLED = "controlled";
    public static final String VALIDATE = "validate";
    
    public static final List<String> CONFIG_PROPERTIES = Arrays.asList(
            DEFAULT_ALLOW, DEFAULT_DENY, TRANSITIVE, EXPAND, AUTONUMBER, CONTROLLED
        );
    
    private static final Integer _increment = 10;
	
    private final Map<String, List<String>> _groups = new HashMap<String, List<String>>();
    private final SortedMap<Integer, Rule> _rules = new TreeMap<Integer, Rule>();
    private final Map<String, Map<Operation, Map<ObjectType, List<Rule>>>> _cache =
                        new WeakHashMap<String, Map<Operation, Map<ObjectType, List<Rule>>>>();
    private final Map<String, Boolean> _config = new HashMap<String, Boolean>();
    
    public RuleSet()
    {
        // set some default configuration properties
        configure(DEFAULT_DENY, Boolean.TRUE);
        configure(TRANSITIVE, Boolean.TRUE);
    }
    
    /**
     * Clear the contents, invluding groups, rules and configuration.
     */
    public void clear()
    {
        _rules.clear();
        _cache.clear();
        _config.clear();
        _groups.clear();
    }
    
    public int getRuleCount()
    {
        return _rules.size();
    }
	
	/**
	 * Filtered rules list based on an identity and operation.
	 * 
	 * Allows only enabled rules with identity equal to all, the same, or a group with identity as a member,
	 * and operation is either all or the same operation.
	 */		
	public List<Rule> getRules(String identity, Operation operation, ObjectType objectType)
	{
        // Lookup identity in cache and create empty operation map if required
		Map<Operation, Map<ObjectType, List<Rule>>> operations = _cache.get(identity);		
		if (operations == null)
		{	
			operations = new EnumMap<Operation, Map<ObjectType, List<Rule>>>(Operation.class);
			_cache.put(identity, operations);
		}
		
        // Lookup operation and create empty object type map if required        
        Map<ObjectType, List<Rule>> objects = operations.get(operation);
		if (objects == null)
		{
            objects = new EnumMap<ObjectType, List<Rule>>(ObjectType.class);
            operations.put(operation, objects);
        }

        // Lookup object type rules for the operation
        if (!objects.containsKey(objectType))
        {
            boolean controlled = false;
            List<Rule> filtered = new LinkedList<Rule>();
            for (Rule rule : _rules.values())
            {
                if (rule.isEnabled()
                    && (rule.getAction().getOperation() == Operation.ALL || rule.getAction().getOperation() == operation)
                    && (rule.getAction().getObjectType() == ObjectType.ALL || rule.getAction().getObjectType() == objectType))
                {
                    controlled = true;

                    if (rule.getIdentity().equalsIgnoreCase(Rule.ALL)
                        || rule.getIdentity().equalsIgnoreCase(identity)
                        || (_groups.containsKey(rule.getIdentity()) && _groups.get(rule.getIdentity()).contains(identity)))
                    {
                        filtered.add(rule);
                    }
                }
            }
            
            // Return null if there are no rules at all for this operation and object type
            if (filtered.isEmpty() && controlled == false)
            {
                filtered = null;
            }
            
            // Save the rules we selected
            objects.put(objectType, filtered);
        }
		
        // Return the cached rules
		return objects.get(objectType);
	}
    
    public boolean isValidNumber(Integer number)
    {
        return !_rules.containsKey(number);
    }
	
    public void grant(Integer number, String identity, Permission permission, Operation operation)
    {
        Action action = new Action(operation);
        addRule(number, identity, permission, action);
    }
    
    public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, ObjectProperties properties)
    {
        Action action = new Action(operation, object, properties);
        addRule(number, identity, permission, action);
    }
    
    public boolean ruleExists(String identity, Action action)
    {
		for (Rule rule : _rules.values())
		{
		    if (rule.getIdentity().equals(identity) && rule.getAction().equals(action))
		    {
		        return true;
		    }
		}
		return false;
    }
    
    private Permission noLog(Permission permission)
    {
        switch (permission)
        {
            case ALLOW:
            case ALLOW_LOG:
                return Permission.ALLOW;
            case DENY:
            case DENY_LOG:
            default:
                return Permission.DENY;
        }
    }

    // TODO make this work when group membership is not known at file parse time
    public void addRule(Integer number, String identity, Permission permission, Action action)
    {
		if (!action.isAllowed())
		{
			throw new IllegalArgumentException("Action is not allowd: " + action);
		}
        if (ruleExists(identity, action))
        {
            return;
        }
        
        // expand actions - possibly multiply number by
        if (isSet(EXPAND))
        {
            if (action.getOperation() == Operation.CREATE && action.getObjectType() == ObjectType.TOPIC)
            {
                addRule(null, identity, noLog(permission), new Action(Operation.BIND, ObjectType.EXCHANGE,
                        new ObjectProperties("amq.topic", action.getProperties().get(ObjectProperties.Property.NAME))));
                ObjectProperties topicProperties = new ObjectProperties();
                topicProperties.put(ObjectProperties.Property.DURABLE, true);
                addRule(null, identity, permission, new Action(Operation.CREATE, ObjectType.QUEUE, topicProperties));
                return;
            }
            if (action.getOperation() == Operation.DELETE && action.getObjectType() == ObjectType.TOPIC)
            {
                addRule(null, identity, noLog(permission), new Action(Operation.UNBIND, ObjectType.EXCHANGE,
                        new ObjectProperties("amq.topic", action.getProperties().get(ObjectProperties.Property.NAME))));
                ObjectProperties topicProperties = new ObjectProperties();
                topicProperties.put(ObjectProperties.Property.DURABLE, true);
                addRule(null, identity, permission, new Action(Operation.DELETE, ObjectType.QUEUE, topicProperties));
                return;
            }
        }
        
		// transitive action dependencies
        if (isSet(TRANSITIVE))
        {
            if (action.getOperation() == Operation.CREATE && action.getObjectType() == ObjectType.QUEUE)
            {
                ObjectProperties exchProperties = new ObjectProperties(action.getProperties());
                exchProperties.setName(ExchangeDefaults.DEFAULT_EXCHANGE_NAME);
                exchProperties.put(ObjectProperties.Property.ROUTING_KEY, action.getProperties().get(ObjectProperties.Property.NAME));
                addRule(null, identity, noLog(permission), new Action(Operation.BIND, ObjectType.EXCHANGE, exchProperties));
				if (action.getProperties().isSet(ObjectProperties.Property.AUTO_DELETE))
				{
					addRule(null, identity, noLog(permission), new Action(Operation.DELETE, ObjectType.QUEUE, action.getProperties()));
				}
            }
            else if (action.getOperation() == Operation.DELETE && action.getObjectType() == ObjectType.QUEUE)
            {
                ObjectProperties exchProperties = new ObjectProperties(action.getProperties());
                exchProperties.setName(ExchangeDefaults.DEFAULT_EXCHANGE_NAME);
                exchProperties.put(ObjectProperties.Property.ROUTING_KEY, action.getProperties().get(ObjectProperties.Property.NAME));
                addRule(null, identity, noLog(permission), new Action(Operation.UNBIND, ObjectType.EXCHANGE, exchProperties));
            }
            else if (action.getOperation() != Operation.ACCESS && action.getObjectType() != ObjectType.VIRTUALHOST)
            {
                addRule(null, identity, noLog(permission), new Action(Operation.ACCESS, ObjectType.VIRTUALHOST));
            }
        }
        
        // set rule number if needed
        Rule rule = new Rule(number, identity, action, permission);        
        if (rule.getNumber() == null)
        {
            if (_rules.isEmpty())
            {
                rule.setNumber(0);
            }
            else
            {
                rule.setNumber(_rules.lastKey() + _increment);
            }
        }
        
        // save rule
        _cache.remove(identity);
        _rules.put(rule.getNumber(), rule);
	}
    
    public void enableRule(int ruleNumber)
    {
        _rules.get(Integer.valueOf(ruleNumber)).enable();
    }
    
    public void disableRule(int ruleNumber)
    {
        _rules.get(Integer.valueOf(ruleNumber)).disable();
    }
    
    public boolean addGroup(String group, List<String> constituents)
    {
        if (_groups.containsKey(group))
        {
            // cannot redefine
            return false;
        }
        else
        {
            _groups.put(group, new ArrayList<String>());
        }
        
        for (String name : constituents)
        {
            if (name.equalsIgnoreCase(group))
            {
                // recursive definition
                return false;
            }
            
            if (!checkName(name))
            {
                // invalid name
                return false;
            }
            
            if (_groups.containsKey(name))
            {
                // is a group
                _groups.get(group).addAll(_groups.get(name));
            }
            else
            {
                // is a user
                if (!isvalidUserName(name))
                {
                    // invalid username
                    return false;
                }
                _groups.get(group).add(name);
            }
        }
        return true;
    }
    
    /** Return true if the name is well-formed (contains legal characters). */
    protected boolean checkName(String name)
    {
        for (int i = 0; i < name.length(); i++)
        {
            Character c = name.charAt(i);
            if (!Character.isLetterOrDigit(c) && c != '-' && c != '_' && c != '@' && c != '.' && c != '/')
            {
                return false;
            }
        }
        return true;
    }
    
    /** Returns true if a username has the name[@domain][/realm] format  */
    protected boolean isvalidUserName(String name)
    {	
		// check for '@' and '/' in namne
		int atPos = name.indexOf(AT);
		int slashPos = name.indexOf(SLASH);
		boolean atFound = atPos != StringUtils.INDEX_NOT_FOUND && atPos == name.lastIndexOf(AT);
		boolean slashFound = slashPos != StringUtils.INDEX_NOT_FOUND && slashPos == name.lastIndexOf(SLASH);
				
		// must be at least one character after '@' or '/'
		if (atFound && atPos > name.length() - 2)
		{
			return false;
		}
		if (slashFound && slashPos > name.length() - 2)
		{
			return false;
		}
		
		// must be at least one character between '@' and '/'
		if (atFound && slashFound)
		{
			return (atPos < (slashPos - 1));
		}
		
		// otherwise all good
		return true; 
    }

	// C++ broker authorise function prototype
    // virtual bool authorise(const std::string& id, const Action& action, const ObjectType& objType,
	//		const std::string& name, std::map<Property, std::string>* params=0);
	
	// Possibly add a String name paramater?

    /**
     * Check the authorisation granted to a particular identity for an operation on an object type with
     * specific properties.
     *
     * Looks up the entire ruleset, whcih may be cached, for the user and operation and goes through the rules
     * in order to find the first one that matches. Either defers if there are no rules, returns the result of
     * the first match found, or denies access if there are no matching rules. Normally, it would be expected
     * to have a default deny or allow rule at the end of an access configuration however.
     */
    public Result check(String identity, Operation operation, ObjectType objectType, ObjectProperties properties)
    {
        // Create the action to check
        Action action = new Action(operation, objectType, properties);

		// get the list of rules relevant for this request
		List<Rule> rules = getRules(identity, operation, objectType);
		if (rules == null)
		{
		    if (isSet(CONTROLLED))
		    {
    		    // Abstain if there are no rules for this operation
                return Result.ABSTAIN;
		    }
		    else
		    {
		        return getDefault();
		    }
		}
		
		// Iterate through a filtered set of rules dealing with this identity and operation
        for (Rule current : rules)
		{
			// Check if action matches
            if (action.matches(current.getAction()))
            {
                Permission permission = current.getPermission();
                
                switch (permission)
                {
                    case ALLOW_LOG:
                        CurrentActor.get().message(AccessControlMessages.ALLOWED(
                                action.getOperation().toString(), action.getObjectType().toString(), action.getProperties().toString()));
                    case ALLOW:
                        return Result.ALLOWED;
                    case DENY_LOG:
                        CurrentActor.get().message(AccessControlMessages.DENIED(
                                action.getOperation().toString(), action.getObjectType().toString(), action.getProperties().toString()));
                    case DENY:
                        return Result.DENIED;
                }

                return Result.DENIED;
            }
        }
        
        // Defer to the next plugin of this type, if it exists
		return Result.DEFER;
    }
	
	/** Default deny. */
	public Result getDefault()
	{
	    if (isSet(DEFAULT_ALLOW))
        {
            return Result.ALLOWED;
        }
        if (isSet(DEFAULT_DENY))
        {
            return Result.DENIED;
        }
        return Result.ABSTAIN;
	}
	
	/**
	 * Check if a configuration property is set.
	 */
	protected boolean isSet(String key)
	{
	    return BooleanUtils.isTrue(_config.get(key));
	}

    /**
     * Configure properties for the plugin instance.
     * 
     * @param properties
     */
    public void configure(Map<String, Boolean> properties)
    {
        _config.putAll(properties);
    }

    /**
     * Configure a single property for the plugin instance.
     * 
     * @param key
     * @param value
     */
    public void configure(String key, Boolean value)
    {
        _config.put(key, value);
    }
}