FileRepository | Line # 137 | 81 | 30 | 72.2% |
0.7218045
|
Filter | Line # 346 | 6 | 2 | 80% |
0.8
|
No Tests | |||
1 | /* | |
2 | * Copyright (c) 2000-2005, University of Salford | |
3 | * All rights reserved. | |
4 | * | |
5 | * Redistribution and use in source and binary forms, with or without | |
6 | * modification, are permitted provided that the following conditions are met: | |
7 | * | |
8 | * Redistributions of source code must retain the above copyright notice, this | |
9 | * list of conditions and the following disclaimer. | |
10 | * | |
11 | * Redistributions in binary form must reproduce the above copyright notice, | |
12 | * this list of conditions and the following disclaimer in the documentation | |
13 | * and/or other materials provided with the distribution. | |
14 | * | |
15 | * Neither the name of the University of Salford nor the names of its | |
16 | * contributors may be used to endorse or promote products derived from this | |
17 | * software without specific prior written permission. | |
18 | * | |
19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
29 | * POSSIBILITY OF SUCH DAMAGE. | |
30 | */ | |
31 | /* | |
32 | * Copyright (c) 2006, University of Kent | |
33 | * All rights reserved. | |
34 | * | |
35 | * Redistribution and use in source and binary forms, with or without | |
36 | * modification, are permitted provided that the following conditions are met: | |
37 | * | |
38 | * Redistributions of source code must retain the above copyright notice, this | |
39 | * list of conditions and the following disclaimer. | |
40 | * | |
41 | * Redistributions in binary form must reproduce the above copyright notice, | |
42 | * this list of conditions and the following disclaimer in the documentation | |
43 | * and/or other materials provided with the distribution. | |
44 | * | |
45 | * 1. Neither the name of the University of Kent nor the names of its | |
46 | * contributors may be used to endorse or promote products derived from this | |
47 | * software without specific prior written permission. | |
48 | * | |
49 | * 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS | |
50 | * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, | |
51 | * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | |
52 | * PURPOSE ARE DISCLAIMED. | |
53 | * | |
54 | * 3. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
55 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
56 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
57 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
58 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
59 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
60 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
61 | * POSSIBILITY OF SUCH DAMAGE. | |
62 | * | |
63 | * 4. YOU AGREE THAT THE EXCLUSIONS IN PARAGRAPHS 2 AND 3 ABOVE ARE REASONABLE | |
64 | * IN THE CIRCUMSTANCES. IN PARTICULAR, YOU ACKNOWLEDGE (1) THAT THIS | |
65 | * SOFTWARE HAS BEEN MADE AVAILABLE TO YOU FREE OF CHARGE, (2) THAT THIS | |
66 | * SOFTWARE IS NOT "PRODUCT" QUALITY, BUT HAS BEEN PRODUCED BY A RESEARCH | |
67 | * GROUP WHO DESIRE TO MAKE THIS SOFTWARE FREELY AVAILABLE TO PEOPLE WHO WISH | |
68 | * TO USE IT, AND (3) THAT BECAUSE THIS SOFTWARE IS NOT OF "PRODUCT" QUALITY | |
69 | * IT IS INEVITABLE THAT THERE WILL BE BUGS AND ERRORS, AND POSSIBLY MORE | |
70 | * SERIOUS FAULTS, IN THIS SOFTWARE. | |
71 | * | |
72 | * 5. This license is governed, except to the extent that local laws | |
73 | * necessarily apply, by the laws of England and Wales. | |
74 | */ | |
75 | ||
76 | package issrg.utils.repository; | |
77 | ||
78 | import issrg.utils.ParsedURL; | |
79 | import issrg.utils.RFC2253NameParser; | |
80 | import issrg.utils.RFC2253ParsingException; | |
81 | import issrg.utils.ExceptionPairException; | |
82 | import issrg.pba.rbac.CustomisePERMIS; | |
83 | import issrg.utils.ToRawCredential; | |
84 | ||
85 | import java.io.File; | |
86 | import java.io.FilenameFilter; | |
87 | import java.io.FileInputStream; | |
88 | import java.io.IOException; | |
89 | import java.security.Principal; | |
90 | import java.util.Hashtable; | |
91 | import java.util.Map; | |
92 | import javax.naming.directory.Attributes; | |
93 | import javax.naming.directory.Attribute; | |
94 | import javax.naming.directory.BasicAttributes; | |
95 | import javax.naming.directory.BasicAttribute; | |
96 | import java.util.regex.Pattern; | |
97 | import java.util.regex.Matcher; | |
98 | ||
99 | import org.apache.log4j.*; | |
100 | /** | |
101 | * This repository uses File URLs and the DN hash to find the attributes | |
102 | * from an entry. The File URLs should be of the form: | |
103 | * <pre> | |
104 | * file://<path>[?<attribute type>=<file name mask>[&...]...] | |
105 | * </pre> | |
106 | * The path should normally point to the directory where the files are. However, | |
107 | * it may point to a file, if a single file has to be used. (This may be useful | |
108 | * when loading a Policy AC). The filename of the AC may not match the hash of | |
109 | * the DN in this case. The path may be absolute or relative; in the latter case | |
110 | * the path is computed from the current directory of the application. | |
111 | * | |
112 | * <p>The query | |
113 | * part of the URL tells the FileRepository the mapping between the attribute | |
114 | * types and file name mask (a regular expression). You should specify at least | |
115 | * one attribute type mapping | |
116 | * (a URL is meaningless otherwise - no attributes can be retrieved). However, | |
117 | * if the query is omitted altogether, | |
118 | * "?attributeCertificateAttribute;binary=^.*\.ace$&userCertificate;binary=^.*\.cer$" | |
119 | * is assumed. | |
120 | * | |
121 | * <p>If the attribute type doesn't have the ";binary" suffix, | |
122 | * the file is treated as a text file with one value in it, and it is returned | |
123 | * as a string. Otherwise, a byte[] is the attribute value. | |
124 | * | |
125 | * <p>Example: | |
126 | * <pre> | |
127 | * file:///c:/certificates/?attributeCertificateAttribute;binary=^.*\.ace$&userCertificate;binary=^.*\.cer$&eduPerson=^.*\.edu$ | |
128 | * </pre> | |
129 | * | |
130 | * <p>This URL will tell the File Repository to look for | |
131 | * attributeCertificateAttribute;binary in *.ace files, and look for | |
132 | * userCertificate;binary attributes in *.cer files in c:/certificates/ | |
133 | * subdirectory. | |
134 | * | |
135 | * @author A.Otenko | |
136 | */ | |
137 | public class FileRepository extends DefaultRepository { | |
138 | ||
139 | private static Logger logger = Logger.getLogger(FileRepository.class); | |
140 | ||
141 | public static final String FILE_PROTOCOL="file"; | |
142 | ||
143 | /** | |
144 | * Suffix used to name binary attributes. It is ";binary". | |
145 | */ | |
146 | public static final String BINARY_SUFFIX=";binary"; | |
147 | ||
148 | /** | |
149 | * The default query assumed by the repository, if the query is omitted. | |
150 | * Current value is: "attributeCertificateAttribute;binary=^.*\.ace$&userCertificate;binary=^.*\.cer$" | |
151 | */ | |
152 | public static final String DEFAULT_QUERY="attributeCertificateAttribute;binary=^.*\\.ace$&userCertificate;binary=^.*\\.cer$"; | |
153 | ||
154 | protected File rootDir; | |
155 | protected File[] rootFile = new File[0]; | |
156 | protected Map typeMap = new Hashtable(); | |
157 | ||
158 | protected static final File[] systemRoots = File.listRoots(); | |
159 | ||
160 | protected int status=SUCCESS_STATUS; | |
161 | protected RepositoryException diagnosis=null; | |
162 | ||
163 | /** | |
164 | * Constructs a File Repository given the URL as defined above. | |
165 | * | |
166 | * @param url - the file URL | |
167 | * | |
168 | * @throws RepositoryException, if the URL is not a valid file URL, or | |
169 | * the path doesn't exist | |
170 | */ | |
171 | 6 | public FileRepository(String url) throws RepositoryException { |
172 | 6 | ParsedURL pu = ParsedURL.parseURL(url); |
173 | ||
174 | 6 | if (pu==null || !pu.getProtocol().toLowerCase().equals(FILE_PROTOCOL)){ |
175 | 0 | throw new RepositoryException("A "+FILE_PROTOCOL+": URL expected, but "+url+" was found"); |
176 | } | |
177 | ||
178 | 6 | String path = pu.getHost()==null?"/":pu.getHost(); // the host name is not specified -> it starts with a slash |
179 | 6 | if (pu.getPathString()!=null) path = path+"/"+pu.getPathString(); // even if path is a slash, we can still add a slash - two slashes are allowed |
180 | ||
181 | 6 | rootDir = new File(path); |
182 | 6 | if (!rootDir.exists()){ |
183 | 0 | throw new RepositoryException("Bad URL: "+url+" - "+pu.getPathString()+" must be a file or directory that exists"); |
184 | } | |
185 | ||
186 | 6 | if (rootDir.isFile()){ |
187 | 0 | rootFile = new File[]{rootDir}; |
188 | } | |
189 | ||
190 | 6 | String query = pu.getQuery(); |
191 | 6 | if (query==null) query=DEFAULT_QUERY; |
192 | ||
193 | 6 | query=query+"&"; // append "&", so type mapping always ends with it |
194 | ||
195 | 0 | for (int i=0, j=0; (j=query.indexOf("&", i))>=0; i=j+1){ // while there are any "&" |
196 | 12 | String q = query.substring(i, j); |
197 | 12 | int k=q.indexOf("="); // the sign separating the attribute type from the file mask |
198 | 12 | if (k<0 || k>=q.length()-1){ |
199 | 0 | throw new RepositoryException(url+" URL has an invalid attribute type mapping: "+pu.getQuery()+" @ "+i); |
200 | } | |
201 | ||
202 | 12 | String type = q.substring(0, k); |
203 | 12 | String mask = q.substring(k+1); |
204 | 12 | Pattern p = Pattern.compile(mask); |
205 | ||
206 | 12 | typeMap.put(type, p); |
207 | } | |
208 | //System.out.println("File Repository: "+rootDir.getAbsolutePath()+", type mapping: "+typeMap); //************ | |
209 | } | |
210 | ||
211 | /** | |
212 | * This method is called by getAttribute and getAllAttributes methods and | |
213 | * returns the attributes named, or all attributes, if no attribute names | |
214 | * were provided. | |
215 | * | |
216 | * @param dn - the name of the entry; FileRepository assumes they are | |
217 | * RFC2253-compliant LDAP DNs | |
218 | * @param attributes - the list of attribute names to return; if the | |
219 | * array is null, all available attributes are returned from the entry | |
220 | * | |
221 | * @return Attributes filled with the attributes requested, or null, if | |
222 | * there was a problem (getStatus will return FAILURE_STATUS) | |
223 | */ | |
224 | 48 | public Attributes getAttributes(Principal dn, String [] attributes) throws RepositoryException { |
225 | 48 | try{ |
226 | 48 | try{ |
227 | 48 | status = FAILURE_STATUS; |
228 | ||
229 | 48 | if (attributes==null){ // get all the attributes |
230 | 0 | attributes = (String[])typeMap.keySet().toArray(new String[0]); |
231 | } | |
232 | ||
233 | // attributes is not null now | |
234 | ||
235 | 48 | Attributes result = new BasicAttributes(); |
236 | ||
237 | 48 | File[] files = rootDir.isFile()? |
238 | rootFile: | |
239 | rootDir.listFiles(new Filter(dn.getName())); | |
240 | ||
241 | 48 | if (files==null){ // it may be null, if an IO error occured |
242 | 0 | throw new RepositoryException("Failed to list files in directory "+rootDir.getAbsolutePath()); |
243 | } | |
244 | ||
245 | 48 | ExceptionPairException pe=null; |
246 | ||
247 | 96 | for (int i=0; i<attributes.length; i++){ |
248 | 48 | boolean binary = attributes[i].endsWith(BINARY_SUFFIX); |
249 | 48 | Pattern mask = (Pattern)typeMap.get(attributes[i]); // get the corresponding mask |
250 | 48 | if (mask==null){ |
251 | 10 | mask = (Pattern)typeMap.get(attributes[i]+";binary"); // try to see if the ";binary" suffix was omitted in the attribute name |
252 | 10 | binary=true; // if the mask is not null, the attributes will be treated as binary, even though they don't have the suffix explicitly |
253 | } | |
254 | 0 | if (mask==null) continue; // skip this attribute, if no mask is defined for it |
255 | ||
256 | 48 | Attribute attr = null; |
257 | ||
258 | 92 | for (int j=0; j<files.length; j++){ |
259 | //System.out.println("Matching "+files[j].getName()+" against "+mask.pattern()+": "+mask.matcher(files[j].getName()).matches()); //************ | |
260 | 44 | if (!mask.matcher(files[j].getName()).matches()) continue; // this file does not contain data for the attribute |
261 | ||
262 | 24 | try{ |
263 | 24 | long len = files[j].length(); |
264 | 24 | if (len>0x0ffffffffL){ |
265 | 0 | throw new RepositoryException("File "+files[j].getAbsolutePath()+" is too long: "+len); |
266 | } | |
267 | ||
268 | //System.out.print("Reading file "+files[i].getName()+"..."); //************ | |
269 | 24 | byte [] content = new byte[(int)(len & 0xffffffff)]; // make space for the whole file |
270 | 24 | FileInputStream fis = new FileInputStream(files[j]); |
271 | ||
272 | 24 | fis.read(content); // TODO: need to check if the whole file has been actually read; this is unlikely, though |
273 | ||
274 | 24 | fis.close(); |
275 | ||
276 | 24 | if (attr==null) attr=new BasicAttribute(attributes[i]); |
277 | ||
278 | 24 | Object value=binary?(Object)content: (Object)new String(content); |
279 | ||
280 | 24 | if (!attr.add(value)){ |
281 | 0 | throw new RepositoryException("Failed to add a value read from file "+files[i].getAbsolutePath()); |
282 | } | |
283 | //System.out.println("done."); //************ | |
284 | }catch (Throwable ioe){ | |
285 | // set status to PARTIAL_SUCCESS, if pe!=null | |
286 | 0 | pe = new ExceptionPairException(ioe, pe); |
287 | } | |
288 | } | |
289 | ||
290 | 48 | if (attr!=null) { // then it has some values |
291 | 24 | result.put(attr); |
292 | ||
293 | 24 | status = SUCCESS_STATUS; |
294 | } | |
295 | } | |
296 | ||
297 | /* | |
298 | * now if status = FAILURE, then no attribute was successfully read. | |
299 | * This may mean two things: pe==null - no attributes are in the entry - status=SUCCESS | |
300 | * pe!=null - all reads failed - status=FAILURE | |
301 | * | |
302 | * if status = SUCCESS, then some attributes read successfully. | |
303 | * Then if pe==null, all attributes read successfully, status=SUCCESS | |
304 | * pe!=null - some attributes failed to read, status=PARTIAL_SUCCESS | |
305 | */ | |
306 | ||
307 | 48 | if (status==FAILURE_STATUS && pe==null){ // successfully read empty entry |
308 | 24 | status=SUCCESS_STATUS; |
309 | } | |
310 | ||
311 | 48 | if (status==SUCCESS_STATUS && pe!=null){ // failed to read some of the attributes |
312 | 0 | status=PARTIAL_SUCCESS_STATUS; |
313 | } | |
314 | ||
315 | 0 | if (status==FAILURE_STATUS) result=null; |
316 | 48 | logger.debug("to construct RawCredentials"); |
317 | 48 | Attributes atts = result; |
318 | 48 | ToRawCredential toRaw = new ToRawCredential(atts,this.getClass().getName()); |
319 | 48 | atts = toRaw.convert(); |
320 | 48 | return (Attributes)atts.clone(); |
321 | }catch(RepositoryException re){ // forward RepositoryExceptions, ... | |
322 | 0 | throw re; |
323 | }catch(Throwable th){ // wrap any other exceptions into RepositoryExceptions | |
324 | 0 | throw new RepositoryException("Unknown error", th); |
325 | } | |
326 | }catch(RepositoryException re){ | |
327 | 0 | diagnosis = re; |
328 | 0 | status=FAILURE_STATUS; |
329 | 0 | throw re; |
330 | } | |
331 | } | |
332 | ||
333 | 0 | public int getStatus(){ |
334 | 0 | return status; |
335 | } | |
336 | ||
337 | 48 | public Throwable getDiagnosis(){ |
338 | 48 | return diagnosis; |
339 | } | |
340 | } | |
341 | ||
342 | /** | |
343 | * This is the filter used to gather only the files that belong to the given | |
344 | * user. It uses a hash of the canonical LDAP DN to match the filenames. | |
345 | */ | |
346 | class Filter implements FilenameFilter { | |
347 | ||
348 | private static Logger logger = Logger.getLogger(Filter.class); | |
349 | ||
350 | String entry; | |
351 | ||
352 | /** | |
353 | * This constructor builds a Filter for a given LDAP DN. The DN is | |
354 | * canonicalised first, then the hash of the resulting string is | |
355 | * computed. It is assumed that the files from the entry with the given | |
356 | * DN will have this hash in their filename, so only these files match | |
357 | * the Filter. | |
358 | * | |
359 | * @param entry - the LDAP DN of the entry; can be a non-canonical DN | |
360 | */ | |
361 | 48 | public Filter (String entry) { |
362 | 48 | byte [] hash = issrg.ac.Util.hashDN(entry); |
363 | 0 | if (hash==null) hash = issrg.ac.Util.hashString(entry); |
364 | ||
365 | 48 | this.entry = issrg.ac.Util.hashToString(hash); |
366 | 48 | logger.debug("Will search for "+entry+" -> "+this.entry); |
367 | //logger.debug( "Will search for "+entry+" -> "+this.entry); | |
368 | // now entry is the hash to look for in the filenames. | |
369 | ||
370 | //System.out.println("Will search for "+entry+" -> "+this.entry); //********** | |
371 | } | |
372 | ||
373 | /** | |
374 | * This method tests if the specified file matches the DN. Only files | |
375 | * containing the hash of the entry DN in the filename are accepted. | |
376 | * Directories are ignored. | |
377 | * | |
378 | * @param dir - the File of the parent directory containing the file | |
379 | * @param name - the name of the file in question | |
380 | * | |
381 | * @return true, if the file is not a directory and contains the hash of | |
382 | * the canonical DN in the filename | |
383 | */ | |
384 | 384 | public boolean accept(File dir, String name){ |
385 | //System.out.println("\taccept file "+name+": "+(new File(dir, name).isFile() && name.indexOf(entry)>=0)+" - "+entry); //*********** | |
386 | ||
387 | 384 | return new File(dir, name).isFile() && name.indexOf(entry)>=0; |
388 | } | |
389 | } |
|