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

Jean-Noël Rouvignac
22.29.2016 2250643bd27e47583d10cb33964693c6b44450d9
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
490
491
492
493
494
495
496
497
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2008 Sun Microsystems, Inc.
 * Portions Copyright 2013-2015 ForgeRock AS.
 */
package org.opends.server.authorization.dseecompat;
 
import static org.opends.messages.AccessControlMessages.*;
import static org.opends.server.authorization.dseecompat.Aci.*;
 
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.forgerock.i18n.LocalizableMessage;
 
/**
 * This class represents a single bind rule of an ACI permission-bind rule pair.
 */
public class BindRule {
 
    /** This hash table holds the keyword bind rule mapping. */
    private final HashMap<String, KeywordBindRule> keywordRuleMap = new HashMap<>();
 
    /** True is a boolean "not" was seen. */
    private boolean negate;
 
    /** Complex bind rules have left and right values. */
    private BindRule left;
    private BindRule right;
 
    /** Enumeration of the boolean type of the complex bind rule ("and" or "or"). */
    private EnumBooleanTypes booleanType;
    /** The keyword of a simple bind rule. */
    private EnumBindRuleKeyword keyword;
 
    /** Regular expression group position of a bind rule keyword. */
    private static final int keywordPos = 1;
    /** Regular expression group position of a bind rule operation. */
    private static final int opPos = 2;
    /** Regular expression group position of a bind rule expression. */
    private static final int expressionPos = 3;
    /** Regular expression group position of the remainder part of an operand. */
    private static final int remainingOperandPos = 1;
    /** Regular expression group position of the remainder of the bind rule. */
    private static final int remainingBindrulePos = 2;
 
    /** Regular expression for valid bind rule operator group. */
    private static final String opRegGroup = "([!=<>]+)";
 
    /** Regular expression for the expression part of a partially parsed bind rule. */
    private static final String expressionRegex = "\"([^\"]+)\"" + ZERO_OR_MORE_WHITESPACE;
 
    /** Regular expression for a single bind rule. */
    private static final String bindruleRegex =
        WORD_GROUP_START_PATTERN + ZERO_OR_MORE_WHITESPACE +
        opRegGroup + ZERO_OR_MORE_WHITESPACE + expressionRegex;
 
    /** Regular expression of the remainder part of a partially parsed bind rule. */
    private static final String remainingBindruleRegex =
        ZERO_OR_MORE_WHITESPACE_START_PATTERN + WORD_GROUP +
        ZERO_OR_MORE_WHITESPACE + "(.*)$";
 
    /**
     * Constructor that takes an keyword enumeration and corresponding
     * simple bind rule. The keyword string is the key for the keyword rule in
     * the keywordRuleMap. This is a simple bind rule representation:
 
     * keyword  op  rule
     *
     * An example of a simple bind rule is:
     *
     *  userdn = "ldap:///anyone"
     *
     * @param keyword The keyword enumeration.
     * @param rule The rule corresponding to this keyword.
     */
    private BindRule(EnumBindRuleKeyword keyword, KeywordBindRule rule) {
        this.keyword=keyword;
        this.keywordRuleMap.put(keyword.toString(), rule);
    }
 
 
    /*
     * TODO Verify that this handles the NOT boolean properly by
     * creating a unit test.
     *
     * I'm a bit confused by the constructor which takes left and right
     * arguments. Is it always supposed to have exactly two elements?
     * Is it supposed to keep nesting bind rules in a chain until all of
     * them have been processed?  The documentation for this method needs
     * to be a lot clearer.  Also, it doesn't look like it handles the NOT
     * type properly.
     */
    /**
     * Constructor that represents a complex bind rule. The left and right
     * bind rules are saved along with the boolean type operator. A complex
     * bind rule looks like:
     *
     *  bindrule   booleantype   bindrule
     *
     * Each side of the complex bind rule can be complex bind rule(s)
     * itself. An example of a complex bind rule would be:
     *
     * (dns="*.example.com" and (userdn="ldap:///anyone" or
     * (userdn="ldap:///cn=foo,dc=example,dc=com and ip=129.34.56.66)))
     *
     * This constructor should always have two elements. The processing
     * of a complex bind rule is dependent on the boolean operator type.
     * See the evalComplex method for more information.
     *
     *
     * @param left The bind rule left of the boolean.
     * @param right The right bind rule.
     * @param booleanType The boolean type enumeration ("and" or "or").
     */
    private BindRule(BindRule left, BindRule right, EnumBooleanTypes booleanType) {
        this.booleanType = booleanType;
        this.left = left;
        this.right = right;
    }
 
    /*
     * TODO Verify this method handles escaped parentheses by writing
     * a unit test.
     *
     * It doesn't look like the decode() method handles the possibility of
     * escaped parentheses in a bind rule.
     */
    /**
     * Decode an ACI bind rule string representation.
     * @param input The string representation of the bind rule.
     * @return A BindRule class representing the bind rule.
     * @throws AciException If the string is an invalid bind rule.
     */
    public static BindRule decode (String input) throws AciException {
        if (input == null || input.length() == 0)
        {
          return null;
        }
        String bindruleStr = input.trim();
        char firstChar = bindruleStr.charAt(0);
        char[] bindruleArray = bindruleStr.toCharArray();
 
        if (firstChar == '(')
        {
          BindRule bindrule_1 = null;
          int currentPos;
          int numOpen = 0;
          int numClose = 0;
 
          // Find the associated closed parenthesis
          for (currentPos = 0; currentPos < bindruleArray.length; currentPos++)
          {
            if (bindruleArray[currentPos] == '(')
            {
              numOpen++;
            }
            else if (bindruleArray[currentPos] == ')')
            {
              numClose++;
            }
            if (numClose == numOpen)
            {
              // We found the associated closed parenthesis the parenthesis are removed
              String bindruleStr1 = bindruleStr.substring(1, currentPos);
              bindrule_1 = BindRule.decode(bindruleStr1);
              break;
            }
          }
          /*
           * Check that the number of open parenthesis is the same as
           * the number of closed parenthesis.
           * Raise an exception otherwise.
           */
          if (numOpen > numClose) {
              throw new AciException(WARN_ACI_SYNTAX_BIND_RULE_MISSING_CLOSE_PAREN.get(input));
          }
          /*
           * If there are remaining chars => there MUST be an operand (AND / OR)
           * otherwise there is a syntax error
           */
          if (currentPos < bindruleArray.length - 1)
          {
            String remainingBindruleStr =
                bindruleStr.substring(currentPos + 1);
            return createBindRule(bindrule_1, remainingBindruleStr);
          }
          return bindrule_1;
        }
        else
        {
          StringBuilder b=new StringBuilder(bindruleStr);
          /*
           * TODO Verify by unit test that this negation
           * is correct. This code handles a simple bind rule negation such as:
           *
           *  not userdn="ldap:///anyone"
           */
          boolean negate=determineNegation(b);
          bindruleStr=b.toString();
          Pattern bindrulePattern = Pattern.compile(bindruleRegex);
          Matcher bindruleMatcher = bindrulePattern.matcher(bindruleStr);
          int bindruleEndIndex;
          if (bindruleMatcher.find())
          {
            bindruleEndIndex = bindruleMatcher.end();
            BindRule bindrule_1 = parseAndCreateBindrule(bindruleMatcher);
            bindrule_1.setNegate(negate);
            if (bindruleEndIndex < bindruleStr.length())
            {
              String remainingBindruleStr = bindruleStr.substring(bindruleEndIndex);
              return createBindRule(bindrule_1, remainingBindruleStr);
            }
            else {
              return bindrule_1;
            }
          }
          else {
              throw new AciException(WARN_ACI_SYNTAX_INVALID_BIND_RULE_SYNTAX.get(input));
          }
        }
    }
 
 
    /**
     * Parses a simple bind rule using the regular expression matcher.
     * @param bindruleMatcher A regular expression matcher holding
     * the engine to use in the creation of a simple bind rule.
     * @return A BindRule determined by the matcher.
     * @throws AciException If the bind rule matcher found errors.
     */
    private static BindRule parseAndCreateBindrule(Matcher bindruleMatcher) throws AciException {
        String keywordStr = bindruleMatcher.group(keywordPos);
        String operatorStr = bindruleMatcher.group(opPos);
        String expression = bindruleMatcher.group(expressionPos);
 
        // Get the Keyword
        final EnumBindRuleKeyword keyword = EnumBindRuleKeyword.createBindRuleKeyword(keywordStr);
        if (keyword == null)
        {
            throw new AciException(WARN_ACI_SYNTAX_INVALID_BIND_RULE_KEYWORD.get(keywordStr));
        }
 
        // Get the operator
        final EnumBindRuleType operator = EnumBindRuleType.createBindruleOperand(operatorStr);
        if (operator == null) {
            throw new AciException(WARN_ACI_SYNTAX_INVALID_BIND_RULE_OPERATOR.get(operatorStr));
        }
 
        //expression can't be null
        if (expression == null) {
            throw new AciException(WARN_ACI_SYNTAX_MISSING_BIND_RULE_EXPRESSION.get(operatorStr));
        }
        validateOperation(keyword, operator);
        KeywordBindRule rule = decode(expression, keyword, operator);
        return new BindRule(keyword, rule);
    }
 
    /**
     * Create a complex bind rule from a substring
     * parsed from the ACI string.
     * @param bindrule The left hand part of a complex bind rule
     * parsed previously.
     * @param remainingBindruleStr The string used to determine the right
     * hand part.
     * @return A BindRule representing a complex bind rule.
     * @throws AciException If the string contains an invalid
     * right hand bind rule string.
     */
    private static BindRule createBindRule(BindRule bindrule,
            String remainingBindruleStr) throws AciException {
        Pattern remainingBindrulePattern = Pattern.compile(remainingBindruleRegex);
        Matcher remainingBindruleMatcher = remainingBindrulePattern.matcher(remainingBindruleStr);
        if (remainingBindruleMatcher.find()) {
            String remainingOperand = remainingBindruleMatcher.group(remainingOperandPos);
            String remainingBindrule = remainingBindruleMatcher.group(remainingBindrulePos);
            EnumBooleanTypes operand = EnumBooleanTypes.createBindruleOperand(remainingOperand);
            if (operand == null
                    || (operand != EnumBooleanTypes.AND_BOOLEAN_TYPE
                            && operand != EnumBooleanTypes.OR_BOOLEAN_TYPE)) {
                LocalizableMessage message =
                        WARN_ACI_SYNTAX_INVALID_BIND_RULE_BOOLEAN_OPERATOR.get(remainingOperand);
                throw new AciException(message);
            }
            StringBuilder ruleExpr=new StringBuilder(remainingBindrule);
            /* TODO write a unit test to verify.
             * This is a check for something like:
             * bindrule and not (bindrule)
             * or something ill-advised like:
             * and not not not (bindrule).
             */
            boolean negate=determineNegation(ruleExpr);
            remainingBindrule=ruleExpr.toString();
            BindRule bindrule_2 = BindRule.decode(remainingBindrule);
            bindrule_2.setNegate(negate);
            return new BindRule(bindrule, bindrule_2, operand);
        }
        throw new AciException(WARN_ACI_SYNTAX_INVALID_BIND_RULE_SYNTAX.get(remainingBindruleStr));
    }
 
    /**
     * Tries to strip an "not" boolean modifier from the string and
     * determine at the same time if the value should be flipped.
     * For example:
     *
     * not not not bindrule
     *
     * is true.
     *
     * @param ruleExpr The bindrule expression to evaluate. This
     * string will be changed if needed.
     * @return True if the boolean needs to be negated.
     */
    private static boolean determineNegation(StringBuilder ruleExpr)  {
        boolean negate=false;
        String ruleStr=ruleExpr.toString();
        while(ruleStr.regionMatches(true, 0, "not ", 0, 4)) {
            negate = !negate;
            ruleStr = ruleStr.substring(4);
        }
        ruleExpr.replace(0, ruleExpr.length(), ruleStr);
        return negate;
    }
 
    /**
     * Set the negation parameter as determined by the function above.
     * @param v The value to assign negate to.
     */
    private void setNegate(boolean v) {
        negate=v;
    }
 
    /*
     * TODO This method needs to handle the userattr keyword. Also verify
     * that the rest of the keywords are handled correctly.
     * TODO Investigate moving this method into EnumBindRuleKeyword class.
     *
     * Does validateOperation need a default case?  Why is USERATTR not in this
     * list? Why is TIMEOFDAY not in this list when DAYOFWEEK is in the list?
     * Would it be more appropriate to put this logic in the
     * EnumBindRuleKeyword class so we can be sure it's always handled properly
     *  for all keywords?
     */
    /**
     * Checks the keyword operator enumeration to make sure it is valid.
     * This method doesn't handle all cases.
     * @param keyword The keyword enumeration to evaluate.
     * @param op The operation enumeration to evaluate.
     * @throws AciException If the operation is not valid for the keyword.
     */
    private static void validateOperation(EnumBindRuleKeyword keyword,
                                        EnumBindRuleType op)
    throws AciException {
        switch (keyword) {
        case USERDN:
        case ROLEDN:
        case GROUPDN:
        case IP:
        case DNS:
        case AUTHMETHOD:
        case DAYOFWEEK:
            if (op != EnumBindRuleType.EQUAL_BINDRULE_TYPE
                    && op != EnumBindRuleType.NOT_EQUAL_BINDRULE_TYPE) {
                throw new AciException(
                    WARN_ACI_SYNTAX_INVALID_BIND_RULE_KEYWORD_OPERATOR_COMBO.get(keyword, op));
            }
        }
    }
 
    /*
     * TODO Investigate moving into the EnumBindRuleKeyword class.
     *
     * Should we move the logic in the
     * decode(String,EnumBindRuleKeyword,EnumBindRuleType) method into the
     * EnumBindRuleKeyword class so we can be sure that it's always
     * handled properly for all keywords?
     */
    /**
     * Creates a keyword bind rule suitable for saving in the keyword
     * rule map table. Each individual keyword class will do further
     * parsing and validation of the expression string.  This processing
     * is part of the simple bind rule creation.
     * @param expr The expression string to further parse.
     * @param keyword The keyword to create.
     * @param op The operation part of the bind rule.
     * @return A keyword bind rule class that can be stored in the
     * map table.
     * @throws AciException If the expr string contains a invalid
     * bind rule.
     */
    private static KeywordBindRule decode(String expr, EnumBindRuleKeyword keyword, EnumBindRuleType op)
            throws AciException  {
        switch (keyword) {
        case USERDN:
            return UserDN.decode(expr, op);
        case ROLEDN:
            //The roledn keyword is not supported. Throw an exception with
            //a message if it is seen in the ACI.
            throw new AciException(WARN_ACI_SYNTAX_ROLEDN_NOT_SUPPORTED.get(expr));
        case GROUPDN:
            return GroupDN.decode(expr, op);
        case IP:
            return IP.decode(expr, op);
        case DNS:
            return DNS.decode(expr, op);
        case DAYOFWEEK:
            return DayOfWeek.decode(expr, op);
        case TIMEOFDAY:
            return TimeOfDay.decode(expr, op);
        case AUTHMETHOD:
            return AuthMethod.decode(expr, op);
        case USERATTR:
            return UserAttr.decode(expr, op);
        case SSF:
            return SSF.decode(expr, op);
        default:
            throw new AciException(WARN_ACI_SYNTAX_INVALID_BIND_RULE_KEYWORD.get(keyword));
        }
    }
 
    /**
     * Evaluate the results of a complex bind rule. If the boolean
     * is an AND type then left and right must be TRUE, else
     * it must be an OR result and one of the bind rules must be
     * TRUE.
     * @param left The left bind rule result to evaluate.
     * @param right The right bind result to evaluate.
     * @return The result of the complex evaluation.
     */
    private EnumEvalResult evalComplex(EnumEvalResult left, EnumEvalResult right) {
        if (booleanType == EnumBooleanTypes.AND_BOOLEAN_TYPE) {
          if (left == EnumEvalResult.TRUE && right == EnumEvalResult.TRUE) {
            return EnumEvalResult.TRUE;
          }
        } else if (left == EnumEvalResult.TRUE || right == EnumEvalResult.TRUE) {
          return EnumEvalResult.TRUE;
        }
       return EnumEvalResult.FALSE;
    }
 
    /**
     * Evaluate an bind rule against an evaluation context. If it is a simple
     * bind rule (no boolean type) then grab the keyword rule from the map
     * table and call the corresponding evaluate function. If it is a
     * complex rule call the routine above "evalComplex()".
     * @param evalCtx The evaluation context to pass to the keyword
     * evaluation function.
     * @return An result enumeration containing the result of the evaluation.
     */
    public EnumEvalResult evaluate(AciEvalContext evalCtx) {
        EnumEvalResult ret;
        //Simple bind rules have a null booleanType enumeration.
        if(this.booleanType == null) {
            KeywordBindRule rule=keywordRuleMap.get(keyword.toString());
            ret = rule.evaluate(evalCtx);
        } else {
            ret = evalComplex(left.evaluate(evalCtx),right.evaluate(evalCtx));
        }
        return EnumEvalResult.negateIfNeeded(ret, negate);
    }
 
    /** {@inheritDoc} */
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        toString(sb);
        return sb.toString();
    }
 
    /**
     * Appends a string representation of this object to the provided buffer.
     *
     * @param buffer
     *          The buffer into which a string representation of this object
     *          should be appended.
     */
    public final void toString(StringBuilder buffer) {
        if (this.keywordRuleMap != null) {
            for (KeywordBindRule rule : this.keywordRuleMap.values()) {
                rule.toString(buffer);
                buffer.append(";");
            }
        }
    }
}