Source Code Cross Referenced for KRSSResponseGenerator.java in  » Authentication-Authorization » ejbca » org » ejbca » core » protocol » xkms » generators » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Authentication Authorization » ejbca » org.ejbca.core.protocol.xkms.generators 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*************************************************************************
002:         *                                                                       *
003:         *  EJBCA: The OpenSource Certificate Authority                          *
004:         *                                                                       *
005:         *  This software is free software; you can redistribute it and/or       *
006:         *  modify it under the terms of the GNU Lesser General Public           *
007:         *  License as published by the Free Software Foundation; either         *
008:         *  version 2.1 of the License, or any later version.                    *
009:         *                                                                       *
010:         *  See terms of license at gnu.org.                                     *
011:         *                                                                       *
012:         *************************************************************************/package org.ejbca.core.protocol.xkms.generators;
013:
014:        import gnu.inet.encoding.StringprepException;
015:
016:        import java.io.UnsupportedEncodingException;
017:        import java.math.BigInteger;
018:        import java.security.KeyFactory;
019:        import java.security.KeyPair;
020:        import java.security.NoSuchAlgorithmException;
021:        import java.security.PrivateKey;
022:        import java.security.PublicKey;
023:        import java.security.cert.CertPath;
024:        import java.security.cert.CertPathValidator;
025:        import java.security.cert.CertPathValidatorException;
026:        import java.security.cert.CertStore;
027:        import java.security.cert.CertificateException;
028:        import java.security.cert.CertificateFactory;
029:        import java.security.cert.CollectionCertStoreParameters;
030:        import java.security.cert.PKIXParameters;
031:        import java.security.cert.TrustAnchor;
032:        import java.security.cert.X509Certificate;
033:        import java.security.interfaces.RSAPrivateCrtKey;
034:        import java.security.spec.InvalidKeySpecException;
035:        import java.security.spec.RSAPublicKeySpec;
036:        import java.util.ArrayList;
037:        import java.util.Collection;
038:        import java.util.Date;
039:        import java.util.HashSet;
040:        import java.util.Iterator;
041:        import java.util.List;
042:        import java.util.Set;
043:
044:        import javax.crypto.SecretKey;
045:        import javax.xml.bind.JAXBElement;
046:
047:        import org.apache.log4j.Logger;
048:        import org.apache.xml.security.encryption.XMLEncryptionException;
049:        import org.apache.xml.security.exceptions.XMLSecurityException;
050:        import org.apache.xml.security.signature.XMLSignatureException;
051:        import org.bouncycastle.util.encoders.Hex;
052:        import org.ejbca.core.model.InternalResources;
053:        import org.ejbca.core.model.SecConst;
054:        import org.ejbca.core.model.authorization.AuthorizationDeniedException;
055:        import org.ejbca.core.model.ca.caadmin.CAInfo;
056:        import org.ejbca.core.model.ca.crl.RevokedCertInfo;
057:        import org.ejbca.core.model.keyrecovery.KeyRecoveryData;
058:        import org.ejbca.core.model.ra.UserDataConstants;
059:        import org.ejbca.core.model.ra.UserDataVO;
060:        import org.ejbca.core.model.ra.raadmin.EndEntityProfile;
061:        import org.ejbca.core.protocol.xkms.common.XKMSConstants;
062:        import org.ejbca.core.protocol.xkms.common.XKMSUtil;
063:        import org.ejbca.util.CertTools;
064:        import org.ejbca.util.KeyTools;
065:        import org.w3._2000._09.xmldsig_.RSAKeyValueType;
066:        import org.w3._2000._09.xmldsig_.X509DataType;
067:        import org.w3._2002._03.xkms_.NotBoundAuthenticationType;
068:        import org.w3._2002._03.xkms_.RegisterRequestType;
069:        import org.w3._2002._03.xkms_.RequestAbstractType;
070:        import org.w3._2002._03.xkms_.ResultType;
071:        import org.w3._2002._03.xkms_.RevokeRequestType;
072:        import org.w3._2002._03.xkms_.UseKeyWithType;
073:        import org.w3c.dom.Document;
074:        import org.w3c.dom.Element;
075:
076:        /**
077:         * Class generating a common response for register, reissue and recover calls
078:         * 
079:         * 
080:         * @author Philip Vendil 
081:         *
082:         * @version $Id: KRSSResponseGenerator.java,v 1.5 2007/08/01 19:58:08 jeklund Exp $
083:         */
084:
085:        public class KRSSResponseGenerator extends
086:                RequestAbstractTypeResponseGenerator {
087:
088:            private static Logger log = Logger
089:                    .getLogger(KRSSResponseGenerator.class);
090:
091:            private static final InternalResources intres = InternalResources
092:                    .getInstance();
093:
094:            protected Document requestDoc = null;
095:
096:            public KRSSResponseGenerator(String remoteIP,
097:                    RequestAbstractType req, Document requestDoc) {
098:                super (remoteIP, req);
099:                this .requestDoc = requestDoc;
100:            }
101:
102:            /**
103:             * Method extracting the public key from the message.
104:             * @param req the request
105:             * @return the public key as and PublicKey or Certificate or null if no public key could be found.
106:             */
107:            protected Object getPublicKeyInfo(RequestAbstractType req,
108:                    boolean registerRequest) {
109:                Object retval = null;
110:
111:                if (GeneralizedKRSSMessageHelper.getKeyBindingAbstractType(req)
112:                        .getKeyInfo() != null
113:                        && GeneralizedKRSSMessageHelper
114:                                .getKeyBindingAbstractType(req).getKeyInfo()
115:                                .getContent().get(0) != null) {
116:                    try {
117:                        JAXBElement element = (JAXBElement) GeneralizedKRSSMessageHelper
118:                                .getKeyBindingAbstractType(req).getKeyInfo()
119:                                .getContent().get(0);
120:                        if (element.getValue() instanceof  RSAKeyValueType
121:                                && registerRequest) {
122:                            RSAKeyValueType rSAKeyValueType = (RSAKeyValueType) ((JAXBElement) GeneralizedKRSSMessageHelper
123:                                    .getKeyBindingAbstractType(req)
124:                                    .getKeyInfo().getContent().get(0))
125:                                    .getValue();
126:                            RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(
127:                                    new BigInteger(rSAKeyValueType.getModulus()),
128:                                    new BigInteger(rSAKeyValueType
129:                                            .getExponent()));
130:                            retval = KeyFactory.getInstance("RSA")
131:                                    .generatePublic(rSAPublicKeySpec);
132:                        }
133:                        if (element.getValue() instanceof  X509DataType) {
134:                            Iterator iter = ((X509DataType) element.getValue())
135:                                    .getX509IssuerSerialOrX509SKIOrX509SubjectName()
136:                                    .iterator();
137:                            while (iter.hasNext()) {
138:                                JAXBElement next = (JAXBElement) iter.next();
139:                                if (next.getName().getLocalPart().equals(
140:                                        "X509Certificate")) {
141:                                    byte[] encoded = (byte[]) next.getValue();
142:
143:                                    try {
144:                                        X509Certificate nextCert = CertTools
145:                                                .getCertfromByteArray(encoded);
146:                                        if (nextCert.getBasicConstraints() == -1) {
147:                                            retval = nextCert;
148:                                        }
149:                                    } catch (CertificateException e) {
150:                                        log
151:                                                .error(
152:                                                        intres
153:                                                                .getLocalizedMessage("xkms.errordecodingcert"),
154:                                                        e);
155:                                        resultMajor = XKMSConstants.RESULTMAJOR_RECIEVER;
156:                                        resultMinor = XKMSConstants.RESULTMINOR_FAILURE;
157:                                    }
158:
159:                                } else {
160:                                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
161:                                    resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
162:                                }
163:                            }
164:                        }
165:
166:                        if (retval == null) {
167:                            resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
168:                            resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
169:                        }
170:
171:                    } catch (InvalidKeySpecException e) {
172:                        log.error(e);
173:                        resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
174:                        resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
175:                    } catch (NoSuchAlgorithmException e) {
176:                        log.error(e);
177:                        resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
178:                        resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
179:                    }
180:                }
181:
182:                return retval;
183:            }
184:
185:            /**
186:             * Method performing the actual certificate generation, from the subjectDN and password
187:             * @param revocationCode The code used later by the user to revoke, it it is allowed by the XKMS Service
188:             * @return the generated certificate or null if generation failed
189:             */
190:            protected X509Certificate registerReissueOrRecover(boolean recover,
191:                    boolean reissue, ResultType response,
192:                    UserDataVO userDataVO, String password,
193:                    PublicKey publicKey, String revocationCode) {
194:                X509Certificate retval = null;
195:
196:                // Check the status of the user
197:                if ((!recover && userDataVO.getStatus() == UserDataConstants.STATUS_NEW)
198:                        || (recover && userDataVO.getStatus() == UserDataConstants.STATUS_KEYRECOVERY)) {
199:
200:                    try {
201:                        boolean usekeyrecovery = !reissue
202:                                && (getRAAdminSession()
203:                                        .loadGlobalConfiguration(pubAdmin))
204:                                        .getEnableKeyRecovery();
205:
206:                        boolean savekeys = userDataVO.getKeyRecoverable()
207:                                && usekeyrecovery
208:                                && (userDataVO.getStatus() != UserDataConstants.STATUS_KEYRECOVERY);
209:                        boolean loadkeys = (userDataVO.getStatus() == UserDataConstants.STATUS_KEYRECOVERY)
210:                                && usekeyrecovery;
211:
212:                        // get users Token Type.
213:                        int tokentype = userDataVO.getTokenType();
214:
215:                        PublicKey certKey = null;
216:                        PrivateKey privKey = null;
217:                        KeyPair keyPair = null;
218:                        KeyRecoveryData keyData = null;
219:                        boolean reusecertificate = false;
220:                        if (loadkeys) {
221:                            EndEntityProfile endEntityProfile = getRAAdminSession()
222:                                    .getEndEntityProfile(pubAdmin,
223:                                            userDataVO.getEndEntityProfileId());
224:                            reusecertificate = endEntityProfile
225:                                    .getReUseKeyRevoceredCertificate();
226:
227:                            // used saved keys.
228:                            keyData = getKeyRecoverySession().keyRecovery(
229:                                    pubAdmin, userDataVO.getUsername(),
230:                                    userDataVO.getEndEntityProfileId());
231:                            keyPair = keyData.getKeyPair();
232:                            certKey = keyPair.getPublic();
233:                            privKey = keyPair.getPrivate();
234:
235:                            if (reusecertificate) {
236:                                getKeyRecoverySession().unmarkUser(pubAdmin,
237:                                        userDataVO.getUsername());
238:                            }
239:                        } else {
240:                            // generate new keys.
241:                            if (!reissue
242:                                    && (tokentype == SecConst.TOKEN_SOFT_P12
243:                                            || tokentype == SecConst.TOKEN_SOFT_JKS || tokentype == SecConst.TOKEN_SOFT_PEM)) {
244:                                keyPair = KeyTools.genKeys(Integer
245:                                        .toString(XKMSConfig
246:                                                .getServerKeyLength()), "RSA");
247:                                certKey = keyPair.getPublic();
248:                                privKey = keyPair.getPrivate();
249:                            }
250:                            if (reissue
251:                                    || tokentype == SecConst.TOKEN_SOFT_BROWSERGEN) {
252:                                certKey = publicKey;
253:                            }
254:                        }
255:
256:                        X509Certificate cert = null;
257:                        if (reusecertificate) {
258:                            cert = (X509Certificate) keyData.getCertificate();
259:                            boolean finishUser = getCAAdminSession().getCAInfo(
260:                                    pubAdmin,
261:                                    CertTools.getIssuerDN(cert).hashCode())
262:                                    .getFinishUser();
263:                            if (finishUser) {
264:                                getAuthenticationSession().finishUser(pubAdmin,
265:                                        userDataVO.getUsername(), password);
266:                            }
267:
268:                        } else {
269:                            cert = (X509Certificate) getSignSession()
270:                                    .createCertificate(pubAdmin,
271:                                            userDataVO.getUsername(), password,
272:                                            certKey);
273:                        }
274:
275:                        if (savekeys) {
276:                            // Save generated keys to database.	             
277:                            getKeyRecoverySession().addKeyRecoveryData(
278:                                    pubAdmin, cert, userDataVO.getUsername(),
279:                                    keyPair);
280:                        }
281:
282:                        // Save the revocation code
283:                        if (revocationCode != null && !recover) {
284:                            UserDataVO data = getUserAdminSession().findUser(
285:                                    pubAdmin, userDataVO.getUsername());
286:                            data
287:                                    .getExtendedinformation()
288:                                    .setRevocationCodeIdentifier(revocationCode);
289:                            getUserAdminSession().changeUser(raAdmin, data,
290:                                    true);
291:
292:                        }
293:
294:                        if (privKey != null) {
295:                            GeneralizedKRSSMessageHelper.setPrivateKey(
296:                                    response, XKMSUtil
297:                                            .getEncryptedXMLFromPrivateKey(
298:                                                    (RSAPrivateCrtKey) privKey,
299:                                                    password));
300:                        }
301:
302:                        retval = cert;
303:                    } catch (Exception e) {
304:                        log
305:                                .error(
306:                                        intres
307:                                                .getLocalizedMessage("xkms.errorregisteringreq"),
308:                                        e);
309:                    }
310:
311:                    if (retval == null) {
312:                        resultMajor = XKMSConstants.RESULTMAJOR_RECIEVER;
313:                        resultMinor = XKMSConstants.RESULTMINOR_FAILURE;
314:                    }
315:
316:                } else {
317:                    log.error(intres.getLocalizedMessage(
318:                            "xkms.errorinreqwrongstatus", new Integer(
319:                                    userDataVO.getStatus()), userDataVO
320:                                    .getUsername()));
321:                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
322:                    resultMinor = XKMSConstants.RESULTMINOR_REFUSED;
323:                }
324:
325:                return retval;
326:            }
327:
328:            protected boolean confirmPOP(PublicKey publicKey) {
329:                boolean retval = false;
330:                // Check that POP is required
331:                if (XKMSConfig.isPOPRequired() && publicKey != null) {
332:                    // Get the public key 
333:                    try {
334:
335:                        org.w3c.dom.NodeList pOPElements = requestDoc
336:                                .getElementsByTagNameNS(
337:                                        "http://www.w3.org/2002/03/xkms#",
338:                                        "ProofOfPossession");
339:                        if (pOPElements.getLength() == 1) {
340:                            Element pOPe = (Element) pOPElements.item(0);
341:                            org.w3c.dom.NodeList popVerXmlSigs = pOPe
342:                                    .getElementsByTagNameNS(
343:                                            "http://www.w3.org/2000/09/xmldsig#",
344:                                            "Signature");
345:                            org.w3c.dom.Element popVerXmlSigElement = (org.w3c.dom.Element) popVerXmlSigs
346:                                    .item(0);
347:                            org.apache.xml.security.signature.XMLSignature popVerXmlSig = new org.apache.xml.security.signature.XMLSignature(
348:                                    popVerXmlSigElement, null);
349:                            if (popVerXmlSig.checkSignatureValue(publicKey)) {
350:                                retval = true;
351:                            }
352:                        }
353:
354:                        if (!retval) {
355:                            resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
356:                            resultMinor = XKMSConstants.RESULTMINOR_POPREQUIRED;
357:                        }
358:                    } catch (XMLSignatureException e) {
359:                        log.error(e);
360:                        resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
361:                        resultMinor = XKMSConstants.RESULTMINOR_POPREQUIRED;
362:                    } catch (XMLSecurityException e) {
363:                        log.error(e);
364:                        resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
365:                        resultMinor = XKMSConstants.RESULTMINOR_POPREQUIRED;
366:                    }
367:
368:                } else {
369:                    retval = true;
370:                }
371:
372:                return retval;
373:            }
374:
375:            protected boolean isPasswordEncrypted(RequestAbstractType req) {
376:                if (GeneralizedKRSSMessageHelper.getAuthenticationType(req) == null) {
377:                    return false;
378:                }
379:                return GeneralizedKRSSMessageHelper.getAuthenticationType(req)
380:                        .getKeyBindingAuthentication() != null;
381:            }
382:
383:            protected UserDataVO findUserData(String subjectDN) {
384:                UserDataVO retval = null;
385:
386:                if (subjectDN != null) {
387:                    try {
388:                        retval = getUserAdminSession().findUserBySubjectDN(
389:                                pubAdmin, subjectDN);
390:                    } catch (AuthorizationDeniedException e) {
391:                        log.error(intres
392:                                .getLocalizedMessage("xkms.errorinprivs"), e);
393:                    }
394:                    if (retval == null) {
395:                        resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
396:                        resultMinor = XKMSConstants.RESULTMINOR_NOMATCH;
397:                    }
398:                }
399:                return retval;
400:            }
401:
402:            /**
403:             * Method finding the userdata of the specified cert or null
404:             * if the user couldn't be foundl
405:             */
406:            protected UserDataVO findUserData(X509Certificate cert) {
407:                UserDataVO retval = null;
408:
409:                try {
410:                    String username = getCertStoreSession()
411:                            .findUsernameByCertSerno(pubAdmin,
412:                                    cert.getSerialNumber(),
413:                                    CertTools.getIssuerDN(cert));
414:                    retval = getUserAdminSession().findUser(pubAdmin, username);
415:                } catch (Exception e) {
416:                    log.error(intres.getLocalizedMessage(
417:                            "xkms.errorfindinguserdata", cert.getSubjectDN()
418:                                    .toString()));
419:                }
420:
421:                if (retval == null) {
422:                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
423:                    resultMinor = XKMSConstants.RESULTMINOR_NOMATCH;
424:                }
425:
426:                return retval;
427:            }
428:
429:            /**
430:             * Method that extracts and verifies the password. Then returns the undigested 
431:             * password from database
432:             * @param req in Document encoding
433:             * @param password cleartext version from database
434:             * @return The password or null if the password doesn't verify
435:             */
436:            protected String getEncryptedPassword(Document reqDoc,
437:                    String password) {
438:                String retval = null;
439:
440:                try {
441:                    SecretKey sk = XKMSUtil.getSecretKeyFromPassphrase(
442:                            password, true, 20, XKMSUtil.KEY_AUTHENTICATION);
443:                    org.w3c.dom.NodeList authenticationElements = reqDoc
444:                            .getElementsByTagNameNS(
445:                                    "http://www.w3.org/2002/03/xkms#",
446:                                    "Authentication");
447:                    Element ae = (Element) authenticationElements.item(0);
448:                    org.w3c.dom.NodeList xmlSigs = ae.getElementsByTagNameNS(
449:                            "http://www.w3.org/2000/09/xmldsig#", "Signature");
450:
451:                    org.w3c.dom.Element xmlSigElement = (org.w3c.dom.Element) xmlSigs
452:                            .item(0);
453:                    org.apache.xml.security.signature.XMLSignature xmlVerifySig = new org.apache.xml.security.signature.XMLSignature(
454:                            xmlSigElement, null);
455:
456:                    if (xmlVerifySig.checkSignatureValue(sk)) {
457:                        retval = password;
458:                    } else {
459:                        resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
460:                        resultMinor = XKMSConstants.RESULTMINOR_NOAUTHENTICATION;
461:                    }
462:                } catch (Exception e) {
463:                    log.error(intres
464:                            .getLocalizedMessage("xkms.errorauthverification"),
465:                            e);
466:                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
467:                    resultMinor = XKMSConstants.RESULTMINOR_NOAUTHENTICATION;
468:                }
469:
470:                return retval;
471:            }
472:
473:            /**
474:             * Returns the password when having NotBoundAuthentication instead
475:             * of KeyBindingAuthentication. 
476:             * 
477:             * @param req
478:             * @return The password or null if no NotBoundAuthentication were found.
479:             */
480:            protected String getClearPassword(RequestAbstractType req,
481:                    String dBPassword) {
482:                String retval = null;
483:                NotBoundAuthenticationType notBoundAuthenticationType = GeneralizedKRSSMessageHelper
484:                        .getAuthenticationType(req).getNotBoundAuthentication();
485:                if (notBoundAuthenticationType != null) {
486:                    retval = new String(notBoundAuthenticationType.getValue());
487:                } else {
488:                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
489:                    resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
490:                }
491:
492:                if (!retval.equals(dBPassword)) {
493:                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
494:                    resultMinor = XKMSConstants.RESULTMINOR_NOAUTHENTICATION;
495:                    retval = null;
496:                }
497:
498:                return retval;
499:            }
500:
501:            /**
502:             * Method that returns the subject DN taken from a UseKeyWith PKIX tag
503:             * If no such tag exist is null returned and errorcodes set.
504:             * @param req
505:             * @return the subjectDN of null
506:             */
507:            protected String getSubjectDN(RequestAbstractType req) {
508:                String retval = null;
509:
510:                Iterator<UseKeyWithType> iter = GeneralizedKRSSMessageHelper
511:                        .getKeyBindingAbstractType(req).getUseKeyWith()
512:                        .iterator();
513:                while (iter.hasNext()) {
514:                    UseKeyWithType next = iter.next();
515:                    if (next.getApplication().equals(
516:                            XKMSConstants.USEKEYWITH_PKIX)) {
517:                        retval = CertTools.stringToBCDNString(next
518:                                .getIdentifier());
519:                        break;
520:                    }
521:                }
522:
523:                if (retval == null) {
524:                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
525:                    resultMinor = XKMSConstants.RESULTMINOR_MESSAGENOTSUPPORTED;
526:                }
527:
528:                return retval;
529:            }
530:
531:            protected boolean certIsValid(X509Certificate cert) {
532:                boolean retval = false;
533:
534:                try {
535:                    CAInfo cAInfo = getCAAdminSession().getCAInfo(pubAdmin,
536:                            CertTools.getIssuerDN(cert).hashCode());
537:                    if (cAInfo != null) {
538:                        Collection caCertChain = cAInfo.getCertificateChain();
539:                        Iterator iter = caCertChain.iterator();
540:
541:                        boolean revoked = false;
542:
543:                        RevokedCertInfo certInfo = getCertStoreSession()
544:                                .isRevoked(pubAdmin,
545:                                        CertTools.getIssuerDN(cert),
546:                                        cert.getSerialNumber());
547:                        if (certInfo.getReason() != RevokedCertInfo.NOT_REVOKED) {
548:                            revoked = true;
549:                        }
550:
551:                        while (iter.hasNext()) {
552:                            X509Certificate cACert = (X509Certificate) iter
553:                                    .next();
554:                            RevokedCertInfo caCertInfo = getCertStoreSession()
555:                                    .isRevoked(pubAdmin,
556:                                            CertTools.getIssuerDN(cACert),
557:                                            cACert.getSerialNumber());
558:                            if (caCertInfo.getReason() != RevokedCertInfo.NOT_REVOKED) {
559:                                revoked = true;
560:                            }
561:
562:                        }
563:
564:                        if (!revoked) {
565:                            retval = verifyCert(caCertChain, null, cert);
566:                        }
567:                    }
568:                } catch (Exception e) {
569:                    log.error(e);
570:                }
571:
572:                if (retval == false) {
573:                    resultMajor = XKMSConstants.RESULTMAJOR_SENDER;
574:                    resultMinor = XKMSConstants.RESULTMINOR_REFUSED;
575:                }
576:
577:                return retval;
578:            }
579:
580:            /**
581:             * method that verifies the certificate and returns an error message
582:             * @param cACertChain
583:             * @param trustedCRLs
584:             * @param cert
585:             * @return  true if everything is OK
586:             */
587:            private boolean verifyCert(Collection cACertChain,
588:                    Collection trustedCRLs, X509Certificate usercert) {
589:
590:                boolean retval = false;
591:
592:                try {
593:                    X509Certificate rootCert = null;
594:                    Iterator iter = cACertChain.iterator();
595:                    while (iter.hasNext()) {
596:                        X509Certificate cert = (X509Certificate) iter.next();
597:                        if (cert.getIssuerDN().equals(cert.getSubjectDN())) {
598:                            rootCert = cert;
599:                            break;
600:                        }
601:                    }
602:
603:                    if (rootCert == null) {
604:                        throw new CertPathValidatorException(
605:                                "Error Root CA cert not found in cACertChain");
606:                    }
607:
608:                    List list = new ArrayList();
609:                    list.add(usercert);
610:                    list.addAll(cACertChain);
611:                    if (trustedCRLs != null) {
612:                        list.addAll(trustedCRLs);
613:                    }
614:
615:                    CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(
616:                            list);
617:                    CertStore store = CertStore.getInstance("Collection", ccsp);
618:
619:                    //validating path
620:                    List certchain = new ArrayList();
621:                    certchain.addAll(cACertChain);
622:                    certchain.add(usercert);
623:                    CertPath cp = CertificateFactory.getInstance("X.509", "BC")
624:                            .generateCertPath(certchain);
625:
626:                    Set trust = new HashSet();
627:                    trust.add(new TrustAnchor(rootCert, null));
628:
629:                    CertPathValidator cpv = CertPathValidator.getInstance(
630:                            "PKIX", "BC");
631:                    PKIXParameters param = new PKIXParameters(trust);
632:                    param.addCertStore(store);
633:                    param.setDate(new Date());
634:                    if (trustedCRLs == null) {
635:                        param.setRevocationEnabled(false);
636:                    } else {
637:                        param.setRevocationEnabled(true);
638:                    }
639:                    cpv.validate(cp, param);
640:                    retval = true;
641:                } catch (Exception e) {
642:                    log.error(intres
643:                            .getLocalizedMessage("xkms.errorverifyingcert"), e);
644:
645:                }
646:
647:                return retval;
648:            }
649:
650:            /**
651:             * Method that checks that the given respondWith specification is valid.
652:             * I.e contains one supported RespondWith tag.
653:             */
654:            public boolean checkValidRespondWithRequest(
655:                    List<String> respondWithList, boolean revokeCall) {
656:                boolean returnval = false;
657:                if (revokeCall) {
658:                    returnval = true;
659:                }
660:
661:                String[] supportedRespondWith = {
662:                        XKMSConstants.RESPONDWITH_X509CERT,
663:                        XKMSConstants.RESPONDWITH_X509CHAIN,
664:                        XKMSConstants.RESPONDWITH_X509CRL,
665:                        XKMSConstants.RESPONDWITH_PRIVATEKEY };
666:
667:                for (int i = 0; i < supportedRespondWith.length; i++) {
668:                    returnval |= respondWithList
669:                            .contains(supportedRespondWith[i]);
670:                    if (returnval) {
671:                        break;
672:                    }
673:                }
674:
675:                return returnval;
676:            }
677:
678:            /**
679:             * Method returning the revocation code identifier or null
680:             * if it doesn't exists.
681:             * 
682:             * @param req
683:             * @return the RevocationCode or null if it doesn't exist.
684:             */
685:            protected String getRevocationCode(RequestAbstractType req) {
686:                String retval = null;
687:
688:                if (req instanceof  RegisterRequestType) {
689:                    if (((RegisterRequestType) req).getPrototypeKeyBinding()
690:                            .getRevocationCodeIdentifier() != null) {
691:                        retval = new String(Hex
692:                                .encode(((RegisterRequestType) req)
693:                                        .getPrototypeKeyBinding()
694:                                        .getRevocationCodeIdentifier()));
695:                    }
696:                }
697:                if (req instanceof  RevokeRequestType) {
698:                    byte[] unMACedCode = ((RevokeRequestType) req)
699:                            .getRevocationCode();
700:                    if (unMACedCode != null) {
701:                        try {
702:                            retval = new String(
703:                                    Hex
704:                                            .encode(XKMSUtil
705:                                                    .getSecretKeyFromPassphrase(
706:                                                            new String(
707:                                                                    unMACedCode,
708:                                                                    "ISO8859-1"),
709:                                                            false,
710:                                                            20,
711:                                                            XKMSUtil.KEY_REVOCATIONCODEIDENTIFIER_PASS2)
712:                                                    .getEncoded()));
713:                        } catch (XMLEncryptionException e) {
714:                            log.error(e);
715:                        } catch (StringprepException e) {// is never thrown}
716:                        } catch (UnsupportedEncodingException e) {
717:                            log.error(e);
718:                        }
719:                    }
720:                }
721:
722:                return retval;
723:            }
724:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.