001/*
002 * (C) Copyright 2007-2016 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 */
020
021package org.nuxeo.ecm.directory.ldap;
022
023import java.io.IOException;
024import java.text.ParseException;
025import java.util.regex.Pattern;
026import java.util.regex.PatternSyntaxException;
027
028import javax.naming.NamingEnumeration;
029import javax.naming.NamingException;
030import javax.naming.directory.Attribute;
031import javax.naming.directory.Attributes;
032
033import org.apache.directory.shared.ldap.filter.BranchNode;
034import org.apache.directory.shared.ldap.filter.ExprNode;
035import org.apache.directory.shared.ldap.filter.FilterParser;
036import org.apache.directory.shared.ldap.filter.FilterParserImpl;
037import org.apache.directory.shared.ldap.filter.PresenceNode;
038import org.apache.directory.shared.ldap.filter.SimpleNode;
039import org.apache.directory.shared.ldap.filter.SubstringNode;
040import org.apache.directory.shared.ldap.name.DefaultStringNormalizer;
041import org.apache.directory.shared.ldap.schema.Normalizer;
042import org.nuxeo.ecm.directory.DirectoryException;
043
044/**
045 * Helper class to parse and evaluate if a LDAP filter expression matches a fetched LDAP entry.
046 * <p>
047 * This is done by recursively evaluating the abstract syntax tree of the expression as parsed by an apache directory
048 * shared method.
049 *
050 * @author Olivier Grisel <ogrisel@nuxeo.com>
051 */
052public class LDAPFilterMatcher {
053
054    private final FilterParser parser;
055
056    // lazily initialized normalizer for the substring match
057    private Normalizer normalizer;
058
059    LDAPFilterMatcher() {
060        parser = new FilterParserImpl();
061    }
062
063    /**
064     * Check whether a raw string filter expression matches on the given LDAP entry.
065     *
066     * @param attributes the ldap entry to match
067     * @param filter a raw string filter expression (eg. <tt>(!(&(attr1=*)(attr2=value2)(attr3=val*)))</tt> )
068     * @return true if the ldap entry matches the filter
069     */
070    public boolean match(Attributes attributes, String filter) {
071        if (filter == null || "".equals(filter)) {
072            return true;
073        }
074        try {
075            ExprNode parsedFilter = parser.parse(filter);
076            return recursiveMatch(attributes, parsedFilter);
077        } catch (DirectoryException | IOException | ParseException e) {
078            throw new DirectoryException("could not parse LDAP filter: " + filter, e);
079        }
080    }
081
082    private boolean recursiveMatch(Attributes attributes, ExprNode filterElement) {
083        if (filterElement instanceof PresenceNode) {
084            return presenceMatch(attributes, (PresenceNode) filterElement);
085        } else if (filterElement instanceof SimpleNode) {
086            return simpleMatch(attributes, (SimpleNode) filterElement);
087        } else if (filterElement instanceof SubstringNode) {
088            return substringMatch(attributes, (SubstringNode) filterElement);
089        } else if (filterElement instanceof BranchNode) {
090            return branchMatch(attributes, (BranchNode) filterElement);
091        } else {
092            throw new DirectoryException("unsupported filter element type: " + filterElement);
093        }
094    }
095
096    /**
097     * Handle attribute presence check (eg: <tt>(attr1=*)</tt>)
098     */
099    private boolean presenceMatch(Attributes attributes, PresenceNode presenceElement) {
100        return attributes.get(presenceElement.getAttribute()) != null;
101    }
102
103    /**
104     * Handle simple equality test on any non-null value (eg: <tt>(attr2=value2)</tt>).
105     *
106     * @return true if the equality holds
107     */
108    protected static boolean simpleMatch(Attributes attributes, SimpleNode simpleElement) {
109        Attribute attribute = attributes.get(simpleElement.getAttribute());
110        if (attribute == null) {
111            // null attribute cannot match any equality statement
112            return false;
113        }
114        boolean isCaseSensitive = isCaseSensitiveMatch(attribute);
115        try {
116            NamingEnumeration<?> rawValues = attribute.getAll();
117            try {
118                while (rawValues.hasMore()) {
119                    String rawValue = rawValues.next().toString();
120                    if (isCaseSensitive || !(simpleElement.getValue() instanceof String)) {
121                        if (simpleElement.getValue().equals(rawValue)) {
122                            return true;
123                        }
124                    } else {
125                        String stringElementValue = (String) simpleElement.getValue();
126                        if (stringElementValue.equalsIgnoreCase(rawValue)) {
127                            return true;
128                        }
129                    }
130                }
131            } finally {
132                rawValues.close();
133            }
134        } catch (NamingException e) {
135            throw new DirectoryException("could not retrieve value for attribute: " + simpleElement.getAttribute());
136        }
137        return false;
138    }
139
140    protected static boolean isCaseSensitiveMatch(Attribute attribute) {
141        // TODO: introspect the content of
142        // attribute.getAttributeSyntaxDefinition() to know whether the
143        // attribute is case sensitive for exact match and cache the results.
144        // fallback to case in-sensitive if syntax definition is missing
145        return false;
146    }
147
148    protected static boolean isCaseSensitiveSubstringMatch(Attribute attribute) {
149        // TODO: introspect the content of
150        // attribute.getAttributeSyntaxDefinition() to know whether the
151        // attribute is case sensitive for substring match and cache the
152        // results.
153        // fallback to case in-sensitive if syntax definition is missing
154        return false;
155    }
156
157    /**
158     * Implement the substring match on any non-null value of a string attribute (eg: <tt>(attr3=val*)</tt>).
159     *
160     * @return the result of the regex evaluation
161     */
162    protected boolean substringMatch(Attributes attributes, SubstringNode substringElement) {
163        try {
164
165            Attribute attribute = attributes.get(substringElement.getAttribute());
166            if (attribute == null) {
167                // null attribute cannot match any regex
168                return false;
169            }
170            NamingEnumeration<?> rawValues = attribute.getAll();
171            try {
172                while (rawValues.hasMore()) {
173                    String rawValue = rawValues.next().toString();
174                    getNormalizer();
175                    StringBuffer sb = new StringBuffer();
176                    String initial = substringElement.getInitial();
177                    String finalSegment = substringElement.getFinal();
178                    if (initial != null && !initial.isEmpty()) {
179                        sb.append(Pattern.quote((String) normalizer.normalize(initial)));
180                    }
181                    sb.append(".*");
182                    for (Object segment : substringElement.getAny()) {
183                        if (segment instanceof String) {
184                            sb.append(Pattern.quote((String) normalizer.normalize(segment)));
185                            sb.append(".*");
186                        }
187                    }
188                    if (finalSegment != null && !finalSegment.isEmpty()) {
189                        sb.append(Pattern.quote((String) normalizer.normalize(finalSegment)));
190                    }
191                    Pattern pattern;
192                    try {
193                        if (isCaseSensitiveSubstringMatch(attribute)) {
194                            pattern = Pattern.compile(sb.toString());
195                        } else {
196                            pattern = Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE);
197                        }
198                    } catch (PatternSyntaxException e) {
199                        throw new DirectoryException("could not build regexp for substring: "
200                                + substringElement.toString());
201                    }
202                    if (pattern.matcher(rawValue).matches()) {
203                        return true;
204                    }
205                }
206            } finally {
207                rawValues.close();
208            }
209            return false;
210        } catch (NamingException e1) {
211            throw new DirectoryException("could not retrieve value for attribute: " + substringElement.getAttribute());
212        }
213    }
214
215    private Normalizer getNormalizer() {
216        if (normalizer == null) {
217            normalizer = new DefaultStringNormalizer();
218        }
219        return normalizer;
220    }
221
222    /**
223     * Handle conjunction, disjunction and negation nodes and recursively call the generic matcher on children.
224     *
225     * @return the boolean value of the evaluation of the sub expression
226     */
227    private boolean branchMatch(Attributes attributes, BranchNode branchElement) {
228        if (branchElement.isConjunction()) {
229            for (ExprNode child : branchElement.getChildren()) {
230                if (!recursiveMatch(attributes, child)) {
231                    return false;
232                }
233            }
234            return true;
235        } else if (branchElement.isDisjunction()) {
236            for (ExprNode child : branchElement.getChildren()) {
237                if (recursiveMatch(attributes, child)) {
238                    return true;
239                }
240            }
241            return false;
242        } else if (branchElement.isNegation()) {
243            return !recursiveMatch(attributes, branchElement.getChild());
244        } else {
245            throw new DirectoryException("unsupported branching filter element type: " + branchElement.toString());
246        }
247    }
248
249}