1 /************************************************************************
2 * Copyright (c) 2000-2006 The Apache Software Foundation. *
3 * All rights reserved. *
4 * ------------------------------------------------------------------- *
5 * Licensed under the Apache License, Version 2.0 (the "License"); you *
6 * may not use this file except in compliance with the License. You *
7 * may obtain a copy of the License at: *
8 * *
9 * http://www.apache.org/licenses/LICENSE-2.0 *
10 * *
11 * Unless required by applicable law or agreed to in writing, software *
12 * distributed under the License is distributed on an "AS IS" BASIS, *
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
14 * implied. See the License for the specific language governing *
15 * permissions and limitations under the License. *
16 ***********************************************************************/
17
18 package org.apache.james.transport.matchers.smime;
19
20 import java.security.Principal;
21 import java.security.cert.X509Certificate;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Iterator;
25 import java.util.List;
26
27 import javax.mail.MessagingException;
28
29 import org.apache.mailet.GenericMatcher;
30 import org.apache.mailet.Mail;
31
32 /***
33 * <p>
34 * Checks if the subject of a X509Certificate contains the supplied string. The
35 * certificate is read from the specified mail attribute.
36 * </p><p>
37 * If the specified attribute contains more than one certificate the matcher matches if at
38 * least one of the certificates contains the given string.
39 * </p>
40 * <p>
41 * Configuration string:
42 * <ul>
43 * <li>mailAttribute;string</li>
44 * </ul>
45 *
46 */
47 public class IsX509CertificateSubject extends GenericMatcher {
48 protected String sourceAttribute;
49 protected String check;
50
51 public void init() throws MessagingException {
52 String condition = getCondition();
53 if(condition == null || condition.indexOf(";") == -1)
54 throw new MessagingException("Invalid matcher configuration: "+condition);
55
56 int pos = condition.indexOf(";");
57 sourceAttribute = condition.substring(0,pos).trim();
58 check = condition.substring(pos+1, condition.length());
59 }
60
61 public Collection match(Mail mail) throws MessagingException {
62 List certificates;
63
64 Object obj = mail.getAttribute(sourceAttribute);
65 if (obj != null) {
66 if (obj instanceof X509Certificate) {
67 certificates = Collections.singletonList(obj);
68 } else {
69 certificates = (List) obj;
70 }
71
72 boolean valid = false;
73
74 for (Iterator iter = certificates.iterator(); iter.hasNext();) {
75 X509Certificate cert = (X509Certificate) iter.next();
76
77
78
79 Principal prin = cert.getSubjectDN();
80
81 if ((prin.toString().indexOf(check)) > 0) {
82 valid = true;
83 }
84 }
85
86 if (valid) {
87 return mail.getRecipients();
88 } else {
89 return null;
90 }
91 } else {
92 return null;
93 }
94 }
95
96 }
97