KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > protocol > xkms > generators > KISSResponseGenerator


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13
14 package org.ejbca.core.protocol.xkms.generators;
15
16 import java.security.cert.CertificateException JavaDoc;
17 import java.security.cert.CertificateExpiredException JavaDoc;
18 import java.security.cert.CertificateNotYetValidException JavaDoc;
19 import java.security.cert.X509Certificate JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.Date JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25
26 import javax.xml.bind.JAXBElement;
27
28 import org.apache.log4j.Logger;
29 import org.ejbca.core.model.InternalResources;
30 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
31 import org.ejbca.core.model.ca.store.CertificateInfo;
32 import org.ejbca.core.model.ra.UserDataVO;
33 import org.ejbca.core.protocol.xkms.common.XKMSConstants;
34 import org.ejbca.util.CertTools;
35 import org.ejbca.util.query.IllegalQueryException;
36 import org.ejbca.util.query.Query;
37 import org.ejbca.util.query.UserMatch;
38 import org.w3._2000._09.xmldsig_.KeyInfoType;
39 import org.w3._2000._09.xmldsig_.X509DataType;
40 import org.w3._2002._03.xkms_.QueryKeyBindingType;
41 import org.w3._2002._03.xkms_.RequestAbstractType;
42 import org.w3._2002._03.xkms_.UseKeyWithType;
43
44 /**
45  * Class generating a response for a locate and validate calls
46  *
47  *
48  * @author Philip Vendil 2006 sep 27
49  *
50  * @version $Id: KISSResponseGenerator.java,v 1.4 2007/01/07 19:44:14 herrvendil Exp $
51  */

52
53 public class KISSResponseGenerator extends
54         RequestAbstractTypeResponseGenerator {
55     
56      private static Logger log = Logger.getLogger(KISSResponseGenerator.class);
57     
58      private static final InternalResources intres = InternalResources.getInstance();
59     
60
61     public KISSResponseGenerator(String JavaDoc remoteIP,RequestAbstractType req) {
62         super(remoteIP,req);
63     }
64     
65
66     
67     
68     /**
69      * Method that should check the request and find
70      * the appropriate certificates
71      * @param queryKeyBindingType
72      * @param name
73      * @param result
74      * @return A List of matching certificates
75      */

76     protected List JavaDoc<X509Certificate JavaDoc> processRequest(QueryKeyBindingType queryKeyBindingType) {
77         ArrayList JavaDoc<X509Certificate JavaDoc> retval = new ArrayList JavaDoc<X509Certificate JavaDoc>();
78
79         int resSize = getResponseLimit() +1;
80
81         if(queryKeyBindingType.getTimeInstant() != null){
82             // TimeInstant in QueryKeyBinding not supported.
83
resultMajor = XKMSConstants.RESULTMAJOR_RECIEVER;
84             resultMinor = XKMSConstants.RESULTMINOR_TIMEINSTANTNOTSUPPORTED;
85
86             return retval;
87         }
88
89         // If keyInfo Exists
90
if(queryKeyBindingType.getKeyInfo() != null){
91             X509Certificate JavaDoc queryCert = null;
92             // Only X509 Certificate and X509Chain is supported
93
KeyInfoType keyInfoType = queryKeyBindingType.getKeyInfo();
94             
95             
96             if(keyInfoType.getContent().size() > 0 ){
97                 JAXBElement<X509DataType> x509DataType = (JAXBElement<X509DataType>) keyInfoType.getContent().get(0);
98
99                 Iterator JavaDoc iter = x509DataType.getValue().getX509IssuerSerialOrX509SKIOrX509SubjectName().iterator();
100                 while(iter.hasNext()){
101                     JAXBElement next = (JAXBElement) iter.next();
102                     if(next.getName().getLocalPart().equals("X509Certificate")){
103                         byte[] encoded = (byte[]) next.getValue();
104
105                         try {
106                             X509Certificate JavaDoc nextCert = CertTools.getCertfromByteArray(encoded);
107                             if(nextCert.getBasicConstraints() == -1){
108                                 queryCert = nextCert;
109                             }
110                         } catch (CertificateException JavaDoc e) {
111                             log.error(intres.getLocalizedMessage("xkms.errordecodingcert"),e);
112                             resultMajor = XKMSConstants.RESULTMAJOR_RECIEVER;
113                             resultMinor = XKMSConstants.RESULTMINOR_FAILURE;
114                         }
115
116                     }else{
117                         resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
118                         resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
119                     }
120                 }
121
122                 if(queryCert != null && fulfillsKeyUsageAndUseKeyWith(queryKeyBindingType,queryCert)){
123                     retval.add(queryCert);
124                 }else{
125                     resultMajor = XKMSConstants.RESULTMAJOR_SUCCESS;
126                     resultMinor = XKMSConstants.RESULTMINOR_NOMATCH;
127                 }
128             }else{
129                 resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
130                 resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
131             }
132         }else{
133             // Check that UseKeyWith isn't empty
134
if(queryKeyBindingType.getUseKeyWith().size() >0){
135                 Query query = genQueryFromUseKeyWith(queryKeyBindingType.getUseKeyWith());
136                 
137                 try {
138                     Collection JavaDoc userDatas = getUserAdminSession().query(pubAdmin, query, null, null, resSize);
139
140                     Iterator JavaDoc<UserDataVO> userIter = userDatas.iterator();
141                     while(userIter.hasNext() && retval.size() <= resSize){
142                         UserDataVO nextUser = userIter.next();
143                         // Find all the certificates of the mathing users
144
try {
145                             Collection JavaDoc userCerts = getCertStoreSession().findCertificatesByUsername(pubAdmin, nextUser.getUsername());
146                             // For all the certificates
147
Iterator JavaDoc<X509Certificate JavaDoc> userCertIter = userCerts.iterator();
148                             while(userCertIter.hasNext() && retval.size() <= resSize){
149                                 X509Certificate JavaDoc nextCert = userCertIter.next();
150                                 try {
151                                     // Check that the certificate is valid
152
nextCert.checkValidity(new Date JavaDoc());
153                                     // and not revoked
154
CertificateInfo certInfo = getCertStoreSession().getCertificateInfo(pubAdmin, CertTools.getFingerprintAsString(nextCert));
155                                     if(certInfo.getRevocationReason() == RevokedCertInfo.NOT_REVOKED){
156                                         if(fulfillsKeyUsageAndUseKeyWith(queryKeyBindingType,nextCert)){
157                                             retval.add(nextCert);
158                                         }
159                                     }
160                                 } catch (CertificateExpiredException JavaDoc e) {
161                                 } catch (CertificateNotYetValidException JavaDoc e) {
162                                 }
163                             }
164                         } catch (Exception JavaDoc e) {
165                             log.error(intres.getLocalizedMessage("xkms.errorcreatesession"),e);
166                             resultMajor = XKMSConstants.RESULTMAJOR_RECIEVER;
167                             resultMinor = XKMSConstants.RESULTMINOR_FAILURE;
168                         }
169
170                     }
171
172                 } catch (IllegalQueryException e) {
173                     log.error(intres.getLocalizedMessage("xkms.illegaluserquery"),e);
174                     resultMajor = XKMSConstants.RESULTMAJOR_RECIEVER;
175                     resultMinor = XKMSConstants.RESULTMINOR_FAILURE;
176                 }
177             }else{
178                 resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
179                 resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
180             }
181
182         }
183         
184         if(resultMajor == null){
185           if(retval.size() == getResponseLimit() + 1){
186             retval.remove(retval.size() -1);
187             resultMajor = XKMSConstants.RESULTMAJOR_SUCCESS;
188             resultMinor = XKMSConstants.RESULTMINOR_TOOMANYRESPONSES;
189           }
190         
191           if(retval.size() == 0){
192             resultMajor = XKMSConstants.RESULTMAJOR_SUCCESS;
193             resultMinor = XKMSConstants.RESULTMINOR_NOMATCH;
194           }
195         }
196         
197         return retval;
198     }
199
200     private boolean fulfillsKeyUsageAndUseKeyWith(QueryKeyBindingType queryKeyBindingType, X509Certificate JavaDoc cert) {
201         boolean retval = true;
202         // Check that the certificate fullfills the key usage spec
203
if(queryKeyBindingType.getKeyUsage().size() != 0){
204             List JavaDoc<String JavaDoc> certKeyUsages = getCertKeyUsageSpec(cert);
205             Iterator JavaDoc<String JavaDoc> iter = queryKeyBindingType.getKeyUsage().iterator();
206             while(iter.hasNext()){
207               String JavaDoc next = iter.next();
208               if(!certKeyUsages.contains(next)){
209                   retval = false;
210                   break;
211               }
212             }
213             
214
215         }
216         
217         if(retval == true){
218           // Check that the certificate fullfills the usekeywith spec
219
if(queryKeyBindingType.getUseKeyWith().size() != 0){
220                 try{
221                   List JavaDoc<UseKeyWithType> certUseKeyWithList= genUseKeyWithAttributes(cert, queryKeyBindingType.getUseKeyWith());
222                   if(certUseKeyWithList.size() == 0){
223                       retval = false;
224                   }
225                 }catch(Exception JavaDoc e){
226                     log.error(intres.getLocalizedMessage("xkms.errorextractingusekeywith"),e);
227                     resultMajor = XKMSConstants.RESULTMAJOR_RECIEVER;
228                     resultMinor = XKMSConstants.RESULTMINOR_FAILURE;
229                 }
230             }
231         }
232         
233         return retval;
234     }
235
236
237
238     
239
240
241
242
243
244     /**
245      * Method that checks that the given respondWith specification is valid.
246      * I.e contains one supported RespondWith tag.
247      */

248     public boolean checkValidRespondWithRequest(List JavaDoc<String JavaDoc> respondWithList){
249         boolean returnval = false;
250         
251         String JavaDoc[] supportedRespondWith = {XKMSConstants.RESPONDWITH_KEYNAME,
252                                          XKMSConstants.RESPONDWITH_KEYVALUE,
253                                          XKMSConstants.RESPONDWITH_X509CERT,
254                                          XKMSConstants.RESPONDWITH_X509CHAIN,
255                                          XKMSConstants.RESPONDWITH_X509CRL};
256          
257         for(int i=0;i<supportedRespondWith.length;i++){
258           returnval |= respondWithList.contains(supportedRespondWith[i]);
259           if(returnval){
260               break;
261           }
262         }
263                 
264         return returnval;
265     }
266
267
268    
269    protected Query genQueryFromUseKeyWith(List JavaDoc<UseKeyWithType> list){
270        Query retval = new Query(Query.TYPE_USERQUERY);
271        boolean retvalEmpty = true;
272        
273        Iterator JavaDoc<UseKeyWithType> iter = list.iterator();
274        while(iter.hasNext()){
275
276            if(!retvalEmpty){
277               retval.add(Query.CONNECTOR_OR);
278            }
279            
280            UseKeyWithType useKeyWithType = iter.next();
281            if(useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_XKMS)||
282               useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_XKMSPROFILE) ||
283               useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_TLS)){
284                 retval.add(UserMatch.MATCH_WITH_URI,UserMatch.MATCH_TYPE_BEGINSWITH,useKeyWithType.getIdentifier());
285                 retvalEmpty=false;
286            }
287            if(useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_SMIME)||
288               useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_PGP)){
289                retval.add(UserMatch.MATCH_WITH_RFC822NAME,UserMatch.MATCH_TYPE_BEGINSWITH,useKeyWithType.getIdentifier());
290                retvalEmpty=false;
291            }
292            if(useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_TLSHTTP)){
293                retval.add(UserMatch.MATCH_WITH_COMMONNAME,UserMatch.MATCH_TYPE_BEGINSWITH,useKeyWithType.getIdentifier());
294                retvalEmpty=false;
295            }
296            if(useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_TLSSMTP)){
297                retval.add(UserMatch.MATCH_WITH_DNSNAME,UserMatch.MATCH_TYPE_BEGINSWITH,useKeyWithType.getIdentifier());
298                retvalEmpty=false;
299            }
300            if(useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_IPSEC)){
301                retval.add(UserMatch.MATCH_WITH_IPADDRESS,UserMatch.MATCH_TYPE_BEGINSWITH,useKeyWithType.getIdentifier());
302                retvalEmpty=false;
303            }
304            if(useKeyWithType.getApplication().equals(XKMSConstants.USEKEYWITH_PKIX)){
305                retval.add(UserMatch.MATCH_WITH_DN,UserMatch.MATCH_TYPE_EQUALS,CertTools.stringToBCDNString(useKeyWithType.getIdentifier()));
306                retvalEmpty=false;
307            }
308            
309
310        }
311
312        return retval;
313    }
314    
315
316
317
318 }
319
Popular Tags