1 13 14 package org.ejbca.core.ejb.ca.caadmin; 15 16 import java.io.ByteArrayOutputStream ; 17 import java.io.IOException ; 18 import java.io.UnsupportedEncodingException ; 19 import java.security.KeyStore ; 20 import java.security.MessageDigest ; 21 import java.security.NoSuchAlgorithmException ; 22 import java.security.PrivateKey ; 23 import java.security.PublicKey ; 24 import java.security.cert.CertPath ; 25 import java.security.cert.CertPathValidator ; 26 import java.security.cert.CertPathValidatorException ; 27 import java.security.cert.CertPathValidatorResult ; 28 import java.security.cert.Certificate ; 29 import java.security.cert.CertificateEncodingException ; 30 import java.security.cert.CertificateException ; 31 import java.security.cert.CertificateExpiredException ; 32 import java.security.cert.CertificateFactory ; 33 import java.security.cert.CertificateNotYetValidException ; 34 import java.security.cert.PKIXCertPathValidatorResult ; 35 import java.security.cert.PKIXParameters ; 36 import java.security.cert.TrustAnchor ; 37 import java.security.cert.X509Certificate ; 38 import java.security.interfaces.RSAPublicKey ; 39 import java.util.ArrayList ; 40 import java.util.Collection ; 41 import java.util.Date ; 42 import java.util.Enumeration ; 43 import java.util.HashMap ; 44 import java.util.HashSet ; 45 import java.util.Iterator ; 46 47 import javax.ejb.CreateException ; 48 import javax.ejb.EJBException ; 49 import javax.ejb.FinderException ; 50 import javax.naming.NamingException ; 51 52 import org.bouncycastle.asn1.ASN1Set; 53 import org.bouncycastle.jce.ECNamedCurveTable; 54 import org.bouncycastle.jce.PKCS10CertificationRequest; 55 import org.bouncycastle.jce.X509KeyUsage; 56 import org.bouncycastle.jce.interfaces.ECPrivateKey; 57 import org.bouncycastle.util.encoders.Hex; 58 import org.ejbca.core.EjbcaException; 59 import org.ejbca.core.ejb.BaseSessionBean; 60 import org.ejbca.core.ejb.ServiceLocator; 61 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal; 62 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome; 63 import org.ejbca.core.ejb.ca.crl.ICreateCRLSessionLocal; 64 import org.ejbca.core.ejb.ca.crl.ICreateCRLSessionLocalHome; 65 import org.ejbca.core.ejb.ca.sign.ISignSessionLocal; 66 import org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome; 67 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal; 68 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome; 69 import org.ejbca.core.ejb.log.ILogSessionLocal; 70 import org.ejbca.core.ejb.log.ILogSessionLocalHome; 71 import org.ejbca.core.model.InternalResources; 72 import org.ejbca.core.model.SecConst; 73 import org.ejbca.core.model.authorization.AuthorizationDeniedException; 74 import org.ejbca.core.model.authorization.AvailableAccessRules; 75 import org.ejbca.core.model.ca.caadmin.CA; 76 import org.ejbca.core.model.ca.caadmin.CACacheManager; 77 import org.ejbca.core.model.ca.caadmin.CADoesntExistsException; 78 import org.ejbca.core.model.ca.caadmin.CAExistsException; 79 import org.ejbca.core.model.ca.caadmin.CAInfo; 80 import org.ejbca.core.model.ca.caadmin.IllegalKeyStoreException; 81 import org.ejbca.core.model.ca.caadmin.X509CA; 82 import org.ejbca.core.model.ca.caadmin.X509CAInfo; 83 import org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAServiceInfo; 84 import org.ejbca.core.model.ca.caadmin.extendedcaservices.ExtendedCAServiceInfo; 85 import org.ejbca.core.model.ca.caadmin.extendedcaservices.OCSPCAServiceInfo; 86 import org.ejbca.core.model.ca.caadmin.extendedcaservices.XKMSCAServiceInfo; 87 import org.ejbca.core.model.ca.catoken.CAToken; 88 import org.ejbca.core.model.ca.catoken.CATokenAuthenticationFailedException; 89 import org.ejbca.core.model.ca.catoken.CATokenConstants; 90 import org.ejbca.core.model.ca.catoken.CATokenInfo; 91 import org.ejbca.core.model.ca.catoken.CATokenOfflineException; 92 import org.ejbca.core.model.ca.catoken.HardCATokenContainer; 93 import org.ejbca.core.model.ca.catoken.HardCATokenInfo; 94 import org.ejbca.core.model.ca.catoken.HardCATokenManager; 95 import org.ejbca.core.model.ca.catoken.IHardCAToken; 96 import org.ejbca.core.model.ca.catoken.NullCAToken; 97 import org.ejbca.core.model.ca.catoken.SoftCAToken; 98 import org.ejbca.core.model.ca.catoken.SoftCATokenInfo; 99 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfile; 100 import org.ejbca.core.model.ca.crl.RevokedCertInfo; 101 import org.ejbca.core.model.log.Admin; 102 import org.ejbca.core.model.log.LogEntry; 103 import org.ejbca.core.model.ra.ExtendedInformation; 104 import org.ejbca.core.model.ra.UserDataVO; 105 import org.ejbca.core.protocol.IRequestMessage; 106 import org.ejbca.core.protocol.IResponseMessage; 107 import org.ejbca.core.protocol.PKCS10RequestMessage; 108 import org.ejbca.core.protocol.X509ResponseMessage; 109 import org.ejbca.util.Base64; 110 import org.ejbca.util.CertTools; 111 import org.ejbca.util.KeyTools; 112 113 114 115 215 public class CAAdminSessionBean extends BaseSessionBean { 216 217 218 private CADataLocalHome cadatahome; 219 220 221 private ILogSessionLocal logsession; 222 223 224 private IAuthorizationSessionLocal authorizationsession; 225 226 227 private ICertificateStoreSessionLocal certificatestoresession; 228 229 230 private ISignSessionLocal signsession; 231 232 233 private ICreateCRLSessionLocal jobrunner; 234 235 236 private static final InternalResources intres = InternalResources.getInstance(); 237 238 242 public void ejbCreate() throws CreateException { 243 cadatahome = (CADataLocalHome)getLocator().getLocalHome(CADataLocalHome.COMP_NAME); 244 CertTools.installBCProvider(); 246 } 247 248 249 268 public void createCA(Admin admin, CAInfo cainfo) throws CAExistsException, AuthorizationDeniedException, CATokenOfflineException, CATokenAuthenticationFailedException { 269 int castatus = SecConst.CA_OFFLINE; 270 try{ 272 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 273 }catch(AuthorizationDeniedException ade){ 274 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca", "create", cainfo.getName()); 275 getLogSession().log (admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE, msg, ade); 276 throw new AuthorizationDeniedException(msg); 277 } 278 try{ 280 int caid = cainfo.getCAId(); 281 if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){ 282 String msg = intres.getLocalizedMessage("caadmin.wrongcaid", new Integer (caid)); 283 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg); 284 throw new CAExistsException(msg); 285 } 286 cadatahome.findByPrimaryKey(new Integer (caid)); 287 String msg = intres.getLocalizedMessage("caadmin.caexistsid", new Integer (caid)); 288 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg); 289 throw new CAExistsException(msg); 290 }catch(javax.ejb.FinderException fe) {} 291 292 try{ 293 cadatahome.findByName(cainfo.getName()); 294 String msg = intres.getLocalizedMessage("caadmin.caexistsname", cainfo.getName()); 295 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg); 296 throw new CAExistsException(msg); 297 }catch(javax.ejb.FinderException fe) {} 298 299 CAToken catoken = null; 301 CATokenInfo catokeninfo = cainfo.getCATokenInfo(); 302 if(catokeninfo instanceof SoftCATokenInfo){ 303 try{ 304 catoken = new SoftCAToken(); 305 ((SoftCAToken) catoken).generateKeys(catokeninfo); 306 }catch(Exception e){ 307 String msg = intres.getLocalizedMessage("caadmin.errorcreatetoken"); 308 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, e); 309 throw new EJBException (e); 310 } 311 } else if(catokeninfo instanceof HardCATokenInfo){ 312 catoken = new HardCATokenContainer(); 313 ((HardCATokenContainer) catoken).updateCATokenInfo(catokeninfo); 314 try{ 315 catoken.activate(((HardCATokenInfo) catokeninfo).getAuthenticationCode()); 316 }catch(CATokenAuthenticationFailedException ctaf){ 317 String msg = intres.getLocalizedMessage("caadmin.errorcreatetokenpin"); 318 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, ctaf); 319 throw ctaf; 320 }catch(CATokenOfflineException ctoe){ 321 String msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName()); 322 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, ctoe); 323 throw ctoe; 324 } 325 } 326 327 CA ca = null; 329 if(cainfo instanceof X509CAInfo){ 330 X509CAInfo x509cainfo = (X509CAInfo) cainfo; 331 ca = new X509CA((X509CAInfo) cainfo); 333 X509CA x509ca = (X509CA) ca; 334 ca.setCAToken(catoken); 335 336 Collection certificatechain = null; 338 339 CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin,cainfo.getCertificateProfileId()); 341 if(x509cainfo.getPolicyId() != null){ 342 certprofile.setUseCertificatePolicies(true); 343 certprofile.setCertificatePolicyId(x509cainfo.getPolicyId()); 344 }else{ 345 if(certprofile.getUseCertificatePolicies()) 346 x509ca.setPolicyId(certprofile.getCertificatePolicyId()); 347 } 348 349 if(cainfo.getSignedBy() == CAInfo.SELFSIGNED){ 350 try{ 351 Certificate cacertificate = null; 353 354 log.debug("CAAdminSessionBean : " + cainfo.getSubjectDN()); 355 356 UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), x509cainfo.getSubjectAltName(), null, 357 0,0,0, cainfo.getCertificateProfileId(), null, null, 0, 0, null); 358 359 cacertificate = ca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN),-1, cainfo.getValidity(), certprofile); 360 361 log.debug("CAAdminSessionBean : " + ((X509Certificate ) cacertificate).getSubjectDN().toString()); 362 363 certificatechain = new ArrayList (); 365 certificatechain.add(cacertificate); 366 367 castatus = SecConst.CA_ACTIVE; 369 }catch(CATokenOfflineException e){ 370 String msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName()); 371 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, e); 372 throw e; 373 }catch(Exception fe){ 374 String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName()); 375 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, fe); 376 throw new EJBException (fe); 377 } 378 } 379 if(cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA){ 380 certificatechain = new ArrayList (); 381 castatus = SecConst.CA_WAITING_CERTIFICATE_RESPONSE; 383 } 384 385 if(cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0){ 386 try{ 388 CADataLocal signcadata = cadatahome.findByPrimaryKey(new Integer (cainfo.getSignedBy())); 389 CA signca = signcadata.getCA(); 390 checkSignerValidity(admin, signcadata); 392 Certificate cacertificate = null; 394 395 UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), x509cainfo.getSubjectAltName(), null, 396 0, 0, 0, cainfo.getCertificateProfileId(),null, null, 0, 0, null); 397 398 cacertificate = signca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), -1, cainfo.getValidity(), certprofile); 399 400 Collection rootcachain = signca.getCertificateChain(); 402 certificatechain = new ArrayList (); 403 certificatechain.add(cacertificate); 404 certificatechain.addAll(rootcachain); 405 castatus = SecConst.CA_ACTIVE; 407 }catch(CATokenOfflineException e){ 408 String msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName()); 409 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, e); 410 throw e; 411 }catch(Exception fe){ 412 String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName()); 413 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, fe); 414 throw new EJBException (fe); 415 } 416 } 417 418 x509ca.setCertificateChain(certificatechain); 420 421 } 422 423 425 getSignSession().publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers()); 426 427 428 429 if(castatus ==SecConst.CA_ACTIVE){ 430 Iterator iter = cainfo.getExtendedCAServiceInfos().iterator(); 432 while(iter.hasNext()){ 433 ExtendedCAServiceInfo info = (ExtendedCAServiceInfo) iter.next(); 434 if(info instanceof OCSPCAServiceInfo){ 435 try{ 436 ca.initExternalService(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE, ca); 437 ArrayList ocspcertificate = new ArrayList (); 438 ocspcertificate.add(((OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE)).getOCSPSignerCertificatePath().get(0)); 439 getSignSession().publishCACertificate(admin, ocspcertificate, ca.getCRLPublishers()); 440 }catch(Exception fe){ 441 String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "OCSPCAService"); 442 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe); 443 throw new EJBException (fe); 444 } 445 } 446 if(info instanceof XKMSCAServiceInfo){ 447 try{ 448 ca.initExternalService(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE, ca); 449 ArrayList xkmscertificate = new ArrayList (); 450 xkmscertificate.add(((XKMSCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE)).getXKMSSignerCertificatePath().get(0)); 451 getSignSession().publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers()); 452 }catch(Exception fe){ 453 String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "XKMSCAService"); 454 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe); 455 throw new EJBException (fe); 456 } 457 } 458 if(info instanceof CmsCAServiceInfo){ 459 try{ 460 ca.initExternalService(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE, ca); 461 ArrayList cmscertificate = new ArrayList (); 462 cmscertificate.add(((CmsCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE)).getCertificatePath().get(0)); 463 getSignSession().publishCACertificate(admin, cmscertificate, ca.getCRLPublishers()); 464 }catch(Exception fe){ 465 String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "CMSCAService"); 466 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe); 467 throw new EJBException (fe); 468 } 469 } 470 } 471 } 472 try{ 474 cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), castatus, ca); 475 if(castatus == SecConst.CA_ACTIVE){ 476 this.getCRLCreateSession().run(admin,cainfo.getSubjectDN()); 478 } 479 String msg = intres.getLocalizedMessage("caadmin.createdca", cainfo.getName(), new Integer (castatus)); 480 getLogSession().log(admin, ca.getCAId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CACREATED, msg); 481 }catch(javax.ejb.CreateException e){ 482 String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName()); 483 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,msg); 484 throw new EJBException (e); 485 } 486 487 488 } 490 503 public void editCA(Admin admin, CAInfo cainfo) throws AuthorizationDeniedException{ 504 boolean ocsprenewcert = false; 505 boolean xkmsrenewcert = false; 506 boolean cmsrenewcert = false; 507 508 try{ 510 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 511 }catch(AuthorizationDeniedException e){ 512 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoeditca", cainfo.getName()); 513 getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e); 514 throw new AuthorizationDeniedException(msg); 515 } 516 517 Iterator iter = cainfo.getExtendedCAServiceInfos().iterator(); 519 while(iter.hasNext()){ 520 Object next = iter.next(); 521 if(next instanceof OCSPCAServiceInfo){ 522 ocsprenewcert = ((OCSPCAServiceInfo) next).getRenewFlag(); 523 } 524 if(next instanceof XKMSCAServiceInfo){ 525 xkmsrenewcert = ((XKMSCAServiceInfo) next).getRenewFlag(); 526 } 527 if(next instanceof CmsCAServiceInfo){ 528 cmsrenewcert = ((CmsCAServiceInfo) next).getRenewFlag(); 529 } 530 } 531 532 533 try{ 535 CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer (cainfo.getCAId())); 536 CA ca = cadata.getCA(); 537 538 ca.updateCA(cainfo); 540 cadata.setCA(ca); 542 543 if(ocsprenewcert){ 545 X509Certificate ocspcert = (X509Certificate ) ((OCSPCAServiceInfo) 546 ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE)) 547 .getOCSPSignerCertificatePath().get(0); 548 ArrayList ocspcertificate = new ArrayList (); 549 ocspcertificate.add(ocspcert); 550 getSignSession().publishCACertificate(admin, ocspcertificate, ca.getCRLPublishers()); 551 } 552 if(xkmsrenewcert){ 553 X509Certificate xkmscert = (X509Certificate ) ((XKMSCAServiceInfo) 554 ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE)) 555 .getXKMSSignerCertificatePath().get(0); 556 ArrayList xkmscertificate = new ArrayList (); 557 xkmscertificate.add(xkmscert); 558 getSignSession().publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers()); 559 } 560 if(cmsrenewcert){ 561 X509Certificate cmscert = (X509Certificate ) ((CmsCAServiceInfo) 562 ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE)) 563 .getCertificatePath().get(0); 564 ArrayList cmscertificate = new ArrayList (); 565 cmscertificate.add(cmscert); 566 getSignSession().publishCACertificate(admin, cmscertificate, ca.getCRLPublishers()); 567 } 568 String msg = intres.getLocalizedMessage("caadmin.editedca", cainfo.getName()); 570 getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED, msg); 571 }catch(Exception fe) { 572 String msg = intres.getLocalizedMessage("caadmin.erroreditca", cainfo.getName()); 573 log.error(msg, fe); 574 getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED, msg, fe); 575 throw new EJBException (fe); 576 } 577 } 579 590 public void removeCA(Admin admin, int caid) throws AuthorizationDeniedException{ 591 try{ 593 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 594 }catch(AuthorizationDeniedException e){ 595 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoremoveca", new Integer (caid)); 596 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE, msg, e); 597 throw new AuthorizationDeniedException(msg); 598 } 599 try{ 601 CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer (caid)); 602 cadata.remove(); 604 CACacheManager.instance().removeCA(caid); 606 HardCATokenManager.instance().addCAToken(caid, null); 608 String msg = intres.getLocalizedMessage("caadmin.removedca", new Integer (caid)); 609 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED, msg); 610 }catch(Exception e) { 611 String msg = intres.getLocalizedMessage("caadmin.errorremoveca", new Integer (caid)); 612 log.error(msg, e); 613 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED, msg, e); 614 throw new EJBException (e); 615 } 616 } 618 624 public void renameCA(Admin admin, String oldname, String newname) throws CAExistsException, AuthorizationDeniedException{ 625 try{ 627 CADataLocal cadata = cadatahome.findByName(oldname); 628 int caid = cadata.getCaId().intValue(); 630 try{ 631 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 632 }catch(AuthorizationDeniedException e){ 633 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtorenameca", new Integer (caid)); 634 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e); 635 throw new AuthorizationDeniedException(msg); 636 } 637 638 try{ 639 CADataLocal cadatanew = cadatahome.findByName(newname); 640 cadatanew.getCaId(); 641 throw new CAExistsException(" CA name " + newname + " already exists."); 642 }catch(javax.ejb.FinderException fe) { 643 cadata.setName(newname); 645 CACacheManager.instance().removeCA(cadata.getCaId().intValue()); 647 String msg = intres.getLocalizedMessage("caadmin.renamedca", oldname, newname); 648 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED,msg); 649 } 650 }catch(javax.ejb.FinderException fe) { 651 String msg = intres.getLocalizedMessage("caadmin.errorrenameca", oldname); 652 log.error(msg, fe); 653 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 654 throw new EJBException (fe); 655 } 656 } 658 667 public CAInfo getCAInfo(Admin admin, String name) { 668 CAInfo cainfo = null; 669 try{ 670 CADataLocal cadata = cadatahome.findByName(name); 671 if(cadata.getStatus() == SecConst.CA_ACTIVE && new Date (cadata.getExpireTime()).before(new Date ())){ 672 cadata.setStatus(SecConst.CA_EXPIRED); 673 } 674 authorizedToCA(admin,cadata.getCaId().intValue()); 675 676 cainfo = cadata.getCA().getCAInfo(); 677 } catch(javax.ejb.FinderException fe) { 678 log.debug("Can not find CA with name: '"+name+"'."); 680 } catch(Exception e) { 681 String msg = intres.getLocalizedMessage("caadmin.errorgetcainfo", name); 682 log.error(msg, e); 683 throw new EJBException (e); 684 } 685 return cainfo; 686 } 688 697 public CAInfo getCAInfo(Admin admin, int caid){ 698 CAInfo cainfo = null; 699 try{ 700 authorizedToCA(admin,caid); 701 CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer (caid)); 702 if(cadata.getStatus() == SecConst.CA_ACTIVE && new Date (cadata.getExpireTime()).before(new Date ())){ 703 cadata.setStatus(SecConst.CA_EXPIRED); 704 } 705 706 cainfo = cadata.getCA().getCAInfo(); 707 } catch(javax.ejb.FinderException fe) { 708 log.debug("Can not find CA with id: '"+caid+"'"); 710 } catch(Exception e){ 711 String msg = intres.getLocalizedMessage("caadmin.errorgetcainfo", new Integer (caid)); 712 log.error(msg, e); 713 throw new EJBException (e); 714 } 715 return cainfo; 716 } 718 725 public HashMap getCAIdToNameMap(Admin admin){ 726 HashMap returnval = new HashMap (); 727 try{ 728 Collection result = cadatahome.findAll(); 729 Iterator iter = result.iterator(); 730 while(iter.hasNext()){ 731 CADataLocal cadata = (CADataLocal) iter.next(); 732 returnval.put(cadata.getCaId(), cadata.getName()); 733 } 734 }catch(javax.ejb.FinderException fe){} 735 736 737 return returnval; 738 } 739 740 748 public Collection getAvailableCAs(Admin admin){ 749 ArrayList returnval = new ArrayList (); 750 try{ 751 Collection result = cadatahome.findAll(); 752 Iterator iter = result.iterator(); 753 while(iter.hasNext()){ 754 CADataLocal cadata = (CADataLocal) iter.next(); 755 if(cadata.getStatus() != SecConst.CA_WAITING_CERTIFICATE_RESPONSE && cadata.getStatus() != SecConst.CA_EXTERNAL) 756 returnval.add(cadata.getCaId()); 757 } 758 }catch(javax.ejb.FinderException fe){} 759 760 return returnval; 761 } 762 763 764 774 public IRequestMessage makeRequest(Admin admin, int caid, Collection cachain, boolean setstatustowaiting) throws CADoesntExistsException, AuthorizationDeniedException, CertPathValidatorException , CATokenOfflineException{ 775 PKCS10RequestMessage returnval = null; 776 try{ 778 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 779 }catch(AuthorizationDeniedException e){ 780 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocertreq", new Integer (caid)); 781 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e); 782 throw new AuthorizationDeniedException(msg); 783 } 784 785 CADataLocal cadata = null; 787 try{ 788 cadata = this.cadatahome.findByPrimaryKey(new Integer (caid)); 789 CA ca = cadata.getCA(); 790 791 try{ 792 if(ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA){ 794 795 796 ca.setRequestCertificateChain(createCertChain(cachain)); 797 798 ASN1Set attributes = null; 801 802 810 811 PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithRSA", 812 CertTools.stringToBcX509Name(ca.getSubjectDN()), ca.getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), attributes, ca.getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), ca.getCAToken().getProvider()); 813 814 returnval = new PKCS10RequestMessage(req); 816 if(setstatustowaiting){ 818 cadata.setStatus(SecConst.CA_WAITING_CERTIFICATE_RESPONSE); 819 ca.setStatus(SecConst.CA_WAITING_CERTIFICATE_RESPONSE); 820 } 821 822 cadata.setCA(ca); 823 }else{ 824 String msg = intres.getLocalizedMessage("caadmin.errorcertreqinternalca", new Integer (caid)); 826 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 827 throw new EJBException (new EjbcaException(msg)); 828 } 829 }catch(CATokenOfflineException e) { 830 String msg = intres.getLocalizedMessage("caadmin.errorcertreq", new Integer (caid)); 831 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e); 832 throw e; 833 } 834 }catch(CertPathValidatorException e) { 835 String msg = intres.getLocalizedMessage("caadmin.errorcertreq", new Integer (caid)); 836 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e); 837 throw e; 838 }catch(Exception e){ 839 String msg = intres.getLocalizedMessage("caadmin.errorcertreq", new Integer (caid)); 840 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e); 841 throw new EJBException (e); 842 } 843 844 String msg = intres.getLocalizedMessage("caadmin.certreqcreated", new Integer (caid)); 845 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED,msg); 846 847 return returnval; 848 } 850 856 public void receiveResponse(Admin admin, int caid, IResponseMessage responsemessage) throws AuthorizationDeniedException, CertPathValidatorException , EjbcaException{ 857 Certificate cacert = null; 859 try{ 861 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 862 }catch(AuthorizationDeniedException e){ 863 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", new Integer (caid)); 864 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e); 865 throw new AuthorizationDeniedException(msg); 866 } 867 868 CADataLocal cadata = null; 870 try{ 871 cadata = this.cadatahome.findByPrimaryKey(new Integer (caid)); 872 CA ca = cadata.getCA(); 873 874 try{ 875 if(responsemessage instanceof X509ResponseMessage){ 876 cacert = ((X509ResponseMessage) responsemessage).getCertificate(); 877 }else{ 878 String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg"); 879 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util. Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 880 throw new EjbcaException(msg); 881 } 882 883 if(ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA){ 885 887 if(!CertTools.getSubjectDN((X509Certificate ) cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))){ 889 String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN((X509Certificate ) cacert), ca.getSubjectDN()); 890 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 891 throw new EjbcaException(msg); 892 } 893 894 ArrayList cachain = new ArrayList (); 895 cachain.add(cacert); 896 cachain.addAll(ca.getRequestCertificateChain()); 897 898 ca.setCertificateChain(createCertChain(cachain)); 899 cadata.setStatus(SecConst.CA_ACTIVE); 901 902 ArrayList cacertcol = new ArrayList (); 904 cacertcol.add(cacert); 905 getSignSession().publishCACertificate(admin, cacertcol, ca.getCRLPublishers()); 906 907 if(ca instanceof X509CA){ 908 cadata.setExpireTime(((X509Certificate ) cacert).getNotAfter().getTime()); 909 } 910 911 Iterator iter = ca.getExternalCAServiceTypes().iterator(); 913 while(iter.hasNext()){ 914 int type = ((Integer ) iter.next()).intValue(); 915 try{ 916 ca.initExternalService(type, ca); 917 ArrayList extcacertificate = new ArrayList (); 918 if(type == ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE){ 919 extcacertificate.add(((OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE)).getOCSPSignerCertificatePath().get(0)); 920 } 921 if(type == ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE){ 922 extcacertificate.add(((XKMSCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE)).getXKMSSignerCertificatePath().get(0)); 923 } 924 if(type == ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE){ 925 extcacertificate.add(((CmsCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE)).getCertificatePath().get(0)); 926 } 927 getSignSession().publishCACertificate(admin, extcacertificate, ca.getCRLPublishers()); 928 }catch(CATokenOfflineException e){ 929 String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", new Integer (caid)); 930 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,e); 931 throw e; 932 }catch(Exception fe){ 933 String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", new Integer (caid)); 934 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe); 935 throw new EJBException (fe); 936 } 937 } 938 cadata.setCA(ca); 940 this.getCRLCreateSession().run(admin,ca.getSubjectDN()); 942 }else{ 943 String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", new Integer (caid)); 944 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 946 throw new EjbcaException(msg); 947 } 948 949 }catch(CATokenOfflineException e){ 950 String msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer (caid)); 951 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e); 952 throw e; 953 } catch (CertificateEncodingException e) { 954 String msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer (caid)); 955 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e); 956 throw new EjbcaException(e.getMessage()); 957 } catch (CertificateException e) { 958 String msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer (caid)); 959 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e); 960 throw new EjbcaException(e.getMessage()); 961 } catch (IOException e) { 962 String msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer (caid)); 963 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e); 964 throw new EjbcaException(e.getMessage()); 965 } 966 }catch(FinderException e){ 967 String msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer (caid)); 968 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e); 969 throw new EjbcaException(e.getMessage()); 970 } catch (UnsupportedEncodingException e) { 971 String msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer (caid)); 972 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e); 973 throw new EjbcaException(e.getMessage()); 974 } 975 976 String msg = intres.getLocalizedMessage("caadmin.certrespreceived", new Integer (caid)); 977 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED,msg); 978 } 980 985 public IResponseMessage processRequest(Admin admin, CAInfo cainfo, IRequestMessage requestmessage) 986 throws CAExistsException, CADoesntExistsException, AuthorizationDeniedException, CATokenOfflineException { 987 CA ca = null; 988 Collection certchain = null; 989 IResponseMessage returnval = null; 990 try{ 992 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 993 }catch(AuthorizationDeniedException e){ 994 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", cainfo.getName()); 995 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e); 996 throw new AuthorizationDeniedException(msg); 997 } 998 999 try{ 1001 int caid = cainfo.getCAId(); 1002 if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){ 1003 String msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName()); 1004 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1005 throw new CAExistsException(msg); 1006 } 1007 cadatahome.findByPrimaryKey(new Integer (caid)); 1008 String msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName()); 1009 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1010 throw new CAExistsException(msg); 1011 }catch(javax.ejb.FinderException fe) {} 1012 1013 try{ 1014 cadatahome.findByName(cainfo.getName()); 1015 String msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName()); 1016 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1017 throw new CAExistsException(msg); 1018 }catch(javax.ejb.FinderException fe) {} 1019 1020 if(cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0){ 1022 try{ 1023 CADataLocal signcadata = cadatahome.findByPrimaryKey(new Integer (cainfo.getSignedBy())); 1024 CA signca = signcadata.getCA(); 1025 try{ 1026 checkSignerValidity(admin, signcadata); 1028 1029 PublicKey publickey = requestmessage.getRequestPublicKey(); 1031 1032 Certificate cacertificate = null; 1034 if(cainfo instanceof X509CAInfo){ 1035 UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), ((X509CAInfo) cainfo).getSubjectAltName(), null, 1036 0, 0, 0, cainfo.getCertificateProfileId(), null, null, 0, 0, null); 1037 if(requestmessage instanceof PKCS10RequestMessage){ 1038 ExtendedInformation extInfo = new ExtendedInformation(); 1039 PKCS10CertificationRequest pkcs10 = ((PKCS10RequestMessage) requestmessage).getCertificationRequest(); 1040 extInfo.setCustomData("PKCS10", new String (Base64.encode(pkcs10.getEncoded()))); 1041 cadata.setExtendedinformation(extInfo); 1042 } 1043 CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin, cainfo.getCertificateProfileId()); 1044 cacertificate = signca.generateCertificate(cadata, publickey, -1, cainfo.getValidity(), certprofile); 1045 returnval = new X509ResponseMessage(); 1046 returnval.setCertificate(cacertificate); 1047 } 1048 Collection rootcachain = signca.getCertificateChain(); 1050 certchain = new ArrayList (); 1051 certchain.add(cacertificate); 1052 certchain.addAll(rootcachain); 1053 1054 if(cainfo instanceof X509CAInfo){ 1055 ca = new X509CA((X509CAInfo) cainfo); 1057 ca.setCertificateChain(certchain); 1058 ca.setCAToken(new NullCAToken()); 1059 } 1060 1061 cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_EXTERNAL, ca); 1063 1064 getSignSession().publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers()); 1066 1067 }catch(CATokenOfflineException e){ 1068 String msg = intres.getLocalizedMessage("caadmin.errorprocess", cainfo.getName()); 1069 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e); 1070 throw e; 1071 } 1072 }catch(Exception e){ 1073 String msg = intres.getLocalizedMessage("caadmin.errorprocess", cainfo.getName()); 1074 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e); 1075 throw new EJBException (e); 1076 } 1077 1078 } 1079 1080 if(certchain != null) { 1081 String msg = intres.getLocalizedMessage("caadmin.processedca", cainfo.getName()); 1082 getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED,msg); 1083 } 1084 else { 1085 String msg = intres.getLocalizedMessage("caadmin.errorprocess", cainfo.getName()); 1086 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1087 } 1088 1089 return returnval; 1090 } 1092 1102 public void renewCA(Admin admin, int caid, IResponseMessage responsemessage, boolean regenerateKeys) throws CADoesntExistsException, AuthorizationDeniedException, CertPathValidatorException , CATokenOfflineException{ 1103 debug(">CAAdminSession, renewCA(), caid=" + caid); 1104 Collection cachain = null; 1105 Certificate cacertificate = null; 1106 try{ 1108 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 1109 }catch(AuthorizationDeniedException e){ 1110 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtorenew", new Integer (caid)); 1111 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e); 1112 throw new AuthorizationDeniedException(msg); 1113 } 1114 1115 CADataLocal cadata = null; 1117 try{ 1118 cadata = this.cadatahome.findByPrimaryKey(new Integer (caid)); 1119 CA ca = cadata.getCA(); 1120 1121 1122 if(ca.getStatus() == SecConst.CA_OFFLINE){ 1123 String msg = intres.getLocalizedMessage("error.catokenoffline", cadata.getName()); 1124 throw new CATokenOfflineException(msg); 1125 } 1126 1127 CAToken caToken = ca.getCAToken(); 1128 if(caToken instanceof SoftCAToken && regenerateKeys){ 1129 ((SoftCAToken) caToken).generateKeys(ca.getCAToken().getCATokenInfo()); 1130 ca.setCAToken(caToken); 1131 } 1132 1133 try{ 1134 if(ca.getSignedBy() != CAInfo.SIGNEDBYEXTERNALCA){ 1136 if(ca.getSignedBy() == CAInfo.SELFSIGNED){ 1137 if( ca instanceof X509CA){ 1139 UserDataVO cainfodata = new UserDataVO("nobody", ca.getSubjectDN(), ca.getSubjectDN().hashCode(), ((X509CA) ca).getSubjectAltName(), null, 1140 0, 0, 0, ca.getCertificateProfileId(), null, null, 0, 0 ,null); 1141 1142 CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin, ca.getCertificateProfileId()); 1143 cacertificate = ca.generateCertificate(cainfodata, ca.getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN),-1, ca.getValidity(), certprofile); 1144 } 1145 cachain = new ArrayList (); 1147 cachain.add(cacertificate); 1148 1149 }else{ 1150 if(ca.getSignedBy() > CAInfo.SPECIALCAIDBORDER || ca.getSignedBy() < 0){ 1152 CADataLocal signcadata = cadatahome.findByPrimaryKey(new Integer (ca.getSignedBy())); 1154 CA signca = signcadata.getCA(); 1155 checkSignerValidity(admin, signcadata); 1157 if( ca instanceof X509CA){ 1159 UserDataVO cainfodata = new UserDataVO("nobody", ca.getSubjectDN(), ca.getSubjectDN().hashCode(), ((X509CA) ca).getSubjectAltName(), null, 1160 0,0,0, ca.getCertificateProfileId(), null, null, 0,0, null); 1161 1162 CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin, ca.getCertificateProfileId()); 1163 cacertificate = signca.generateCertificate(cainfodata, ca.getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN),-1, ca.getValidity(), certprofile); 1164 } 1165 1166 Collection rootcachain = signca.getCertificateChain(); 1168 cachain = new ArrayList (); 1169 cachain.add(cacertificate); 1170 cachain.addAll(rootcachain); 1171 } 1172 } 1173 }else{ 1174 if(responsemessage instanceof X509ResponseMessage){ 1177 cacertificate = ((X509ResponseMessage) responsemessage).getCertificate(); 1178 }else{ 1179 String msg = intres.getLocalizedMessage("error.errorcertrespillegalmsg"); 1180 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1181 throw new EJBException (new EjbcaException(msg)); 1182 } 1183 1184 if(!CertTools.getSubjectDN((X509Certificate ) cacertificate).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))){ 1186 String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN((X509Certificate ) cacertificate), ca.getSubjectDN()); 1187 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1188 throw new EJBException (new EjbcaException(msg)); 1189 } 1190 1191 cachain = new ArrayList (); 1192 cachain.add(cacertificate); 1193 cachain.addAll(ca.getRequestCertificateChain()); 1194 1195 cachain = createCertChain(cachain); 1196 1197 } 1198 if(cacertificate instanceof X509Certificate ) 1200 cadata.setExpireTime(((X509Certificate ) cacertificate).getNotAfter().getTime()); 1201 cadata.setStatus(SecConst.CA_ACTIVE); 1202 1203 ca.setCertificateChain(cachain); 1204 cadata.setCA(ca); 1205 1206 ArrayList cacert = new ArrayList (); 1208 cacert.add(ca.getCACertificate()); 1209 getSignSession().publishCACertificate(admin, cacert, ca.getCRLPublishers()); 1210 1211 1212 }catch(CATokenOfflineException e){ 1213 String msg = intres.getLocalizedMessage("caadmin.errorrenewca", new Integer (caid)); 1214 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e); 1215 throw e; 1216 } 1217 }catch(Exception e){ 1218 String msg = intres.getLocalizedMessage("caadmin.errorrenewca", new Integer (caid)); 1219 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e); 1220 throw new EJBException (e); 1221 } 1222 String msg = intres.getLocalizedMessage("caadmin.renewdca", new Integer (caid)); 1223 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CARENEWED,msg); 1224 debug("<CAAdminSession, renewCA(), caid=" + caid); 1225 } 1227 1235 public void revokeCA(Admin admin, int caid, int reason) throws CADoesntExistsException, AuthorizationDeniedException{ 1236 try{ 1238 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 1239 }catch(AuthorizationDeniedException e){ 1240 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtorevoke", new Integer (caid)); 1241 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e); 1242 throw new AuthorizationDeniedException(msg); 1243 } 1244 1245 CADataLocal ca = null; 1247 try{ 1248 ca = this.cadatahome.findByPrimaryKey(new Integer (caid)); 1249 }catch(javax.ejb.FinderException fe){ 1250 throw new EJBException (fe); 1251 } 1252 1253 String issuerdn = ca.getSubjectDN(); 1254 1255 1256 try{ 1257 CA cadata = ca.getCA(); 1258 1259 getCertificateStoreSession().revokeCertificate(admin, cadata.getCACertificate(), cadata.getCRLPublishers(), reason); 1261 if(cadata.getStatus() != SecConst.CA_EXTERNAL){ 1263 getCertificateStoreSession().revokeAllCertByCA(admin, issuerdn, RevokedCertInfo.REVOKATION_REASON_CACOMPROMISE); 1264 getCRLCreateSession().run(admin, issuerdn); 1265 } 1266 1267 cadata.setRevokationReason(reason); 1268 cadata.setRevokationDate(new Date ()); 1269 if(cadata.getStatus() != SecConst.CA_EXTERNAL){ 1270 ca.setStatus(SecConst.CA_REVOKED); 1271 } 1272 ca.setCA(cadata); 1273 1274 }catch(Exception e){ 1275 String msg = intres.getLocalizedMessage("caadmin.errorrevoke", ca.getName()); 1276 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAREVOKED,msg,e); 1277 throw new EJBException (e); 1278 } 1279 1280 String msg = intres.getLocalizedMessage("caadmin.revokedca", ca.getName(), new Integer (reason)); 1281 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAREVOKED,msg); 1282 } 1284 1293 public void upgradeFromOldCAHSMKeyStore(Admin admin, int caid){ 1294 try{ 1295 if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) 1297 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator"); 1298 1299 CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer (caid)); 1300 CA ca = cadata.getCA(); 1301 CAToken token = ca.getCAToken(); 1302 CATokenInfo tokeninfo = token.getCATokenInfo(); 1303 HardCATokenInfo htokeninfo = null; 1304 if (tokeninfo instanceof HardCATokenInfo) { 1305 error("(this is not an error) Found hard token for ca with id: "+caid); 1306 htokeninfo = (HardCATokenInfo)tokeninfo; 1307 } else { 1308 error("(this is not an error) No need to update soft token for ca with id: "+caid); 1309 } 1310 if (htokeninfo != null) { 1311 String oldtoken = htokeninfo.getClassPath(); 1312 if (oldtoken.equals("se.anatom.ejbca.ca.caadmin.hardcatokens.NFastCAToken") 1313 || oldtoken.equals("se.primeKey.caToken.nFast.NFastCAToken")) { 1314 htokeninfo.setClassPath("org.ejbca.core.model.ca.catoken.NFastCAToken"); 1315 error("(this is not an error) Updated catoken classpath ("+oldtoken+") for ca with id: "+caid); 1316 token.updateCATokenInfo(htokeninfo); 1317 ca.setCAToken(token); 1318 cadata.setCA(ca); 1319 } else { 1320 error("(this is not an error) No need to update catoken classpath ("+oldtoken+") for ca with id: "+caid); 1321 } 1322 } 1323 }catch(Exception e){ 1324 error("An error occured when trying to upgrade hard token classpath: ", e); 1325 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,"An error occured when trying to upgrade hard token classpath", e); 1326 throw new EJBException (e); 1327 } 1328 1329 } 1331 1344 public void importCAFromKeyStore(Admin admin, String caname, byte[] p12file, char[] keystorepass, 1345 char[] privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) throws Exception { 1346 try{ 1347 if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) { 1349 getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.ROLE_SUPERADMINISTRATOR); 1350 } 1351 java.security.KeyStore keystore=KeyStore.getInstance("PKCS12", "BC"); 1353 keystore.load(new java.io.ByteArrayInputStream (p12file),keystorepass); 1354 if ( privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias) ) { 1356 throw new Exception ("Alias \"" + privateSignatureKeyAlias + "\" not found."); 1357 } 1358 Certificate [] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias); 1359 if (signatureCertChain.length < 1) { 1360 String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias; 1361 log.error(msg); 1362 throw new Exception (msg); 1363 } 1364 ArrayList certificatechain = new ArrayList (); 1365 for(int i=0;i< signatureCertChain.length;i++){ 1366 certificatechain.add(signatureCertChain[i]); 1367 } 1368 X509Certificate caSignatureCertificate = (X509Certificate ) signatureCertChain[0]; 1369 if ( caSignatureCertificate.getKeyUsage() != null ) { 1370 if (!caSignatureCertificate.getKeyUsage()[0] || !caSignatureCertificate.getKeyUsage()[5]) { 1371 String msg = "Key assigned to alias \"" + privateSignatureKeyAlias + "\" cannot be used for signatures. Key usage vector is:"; 1372 for (int i=0; i<9; i++) { 1373 msg += " " + caSignatureCertificate.getKeyUsage()[i]; 1374 } 1375 log.error(msg); 1376 throw new Exception (msg); 1377 } 1378 } else { 1379 log.warn("No key usage vector found for \"" + privateSignatureKeyAlias + "\". Assuming it is valid for signatures." ); 1380 } 1381 PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey(); 1382 PrivateKey p12PrivateSignatureKey = null; 1383 if ( p12PublicSignatureKey instanceof RSAPublicKey ) { 1384 p12PrivateSignatureKey = (PrivateKey ) keystore.getKey( privateSignatureKeyAlias, privkeypass); 1385 } else { 1386 p12PrivateSignatureKey = (ECPrivateKey) keystore.getKey( privateSignatureKeyAlias, privkeypass); 1387 log.debug("ImportSignatureKeyAlgorithm (expecting ECDSA)="+((ECPrivateKey) keystore.getKey( privateSignatureKeyAlias, privkeypass)).getAlgorithm()); 1388 } 1389 PrivateKey p12PrivateEncryptionKey = null; 1391 PublicKey p12PublicEncryptionKey = null; 1392 X509Certificate caEncryptionCertificate = null; 1393 if (privateEncryptionKeyAlias != null) { 1394 if ( !keystore.isKeyEntry(privateEncryptionKeyAlias) ) { 1395 throw new Exception ("Alias \"" + privateEncryptionKeyAlias + "\" not found."); 1396 } 1397 Certificate [] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias); 1398 if (encryptionCertChain.length < 1) { 1399 String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias; 1400 log.error(msg); 1401 throw new Exception (msg); 1402 } 1403 caEncryptionCertificate = (X509Certificate ) encryptionCertChain[0]; 1404 if ( caEncryptionCertificate.getKeyUsage() != null ) { 1405 if ( !caEncryptionCertificate.getKeyUsage()[2] ) { 1406 String msg = "Key asigned to alias \"" + privateEncryptionKeyAlias + "\" cannot be used for key encipherment. Key usage vector is:"; 1407 for (int i=0; i<caEncryptionCertificate.getKeyUsage().length; i++) { 1408 msg += " " + caEncryptionCertificate.getKeyUsage()[i]; 1409 } 1410 log.error(msg); 1411 throw new Exception (msg); 1412 } 1413 } else { 1414 log.warn("No key usage vector found for \"" + privateEncryptionKeyAlias + "\". Assuming it is valid for signatures." ); 1415 } 1416 p12PrivateEncryptionKey = (PrivateKey ) keystore.getKey( privateEncryptionKeyAlias, privkeypass); 1417 p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey(); 1418 } 1419 CAToken catoken = new SoftCAToken(); 1421 ((SoftCAToken) catoken).importKeysFromP12(p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, 1422 p12PublicEncryptionKey, signatureCertChain); 1423 log.debug("CA-Info: "+catoken.getCATokenInfo().getSignatureAlgorithm() + " " + catoken.getCATokenInfo().getEncryptionAlgorithm()); 1424 int signedby = CAInfo.SIGNEDBYEXTERNALCA; 1426 int certprof = SecConst.CERTPROFILE_FIXED_SUBCA; 1427 String description = "Imported external signed CA"; 1428 if(signatureCertChain.length == 1) { 1429 if (verifyIssuer(caSignatureCertificate, caSignatureCertificate)) { 1430 signedby = CAInfo.SELFSIGNED; 1431 certprof = SecConst.CERTPROFILE_FIXED_ROOTCA; 1432 description = "Imported root CA"; 1433 } else { 1434 log.error("Cannot import CA " + caSignatureCertificate.getSubjectDN().getName() 1438 + ": certificate " + caSignatureCertificate.getSerialNumber() 1439 + " is not self-signed."); 1440 throw new Exception ("Cannot import CA " 1441 + caSignatureCertificate.getSubjectDN().getName() 1442 + ": certificate is not self-signed. Check " 1443 + "certificate chain in PKCS#12"); 1444 } 1445 } else if (signatureCertChain.length > 1){ 1446 Collection cas = getAvailableCAs(admin); 1447 Iterator iter = cas.iterator(); 1448 while (iter.hasNext()) { 1453 int caid = ((Integer )iter.next()).intValue(); 1454 CAInfo superCaInfo = getCAInfo(admin, caid); 1455 Iterator i = superCaInfo.getCertificateChain().iterator(); 1456 if (i.hasNext()) { 1457 X509Certificate superCaCert = (X509Certificate )i.next(); 1458 if (verifyIssuer(caSignatureCertificate, superCaCert)) { 1459 signedby = caid; 1460 description = "Imported sub CA"; 1461 break; 1462 } 1463 } 1464 } 1465 } 1466 String keyAlgorithm = CATokenConstants.KEYALGORITHM_RSA; 1468 String keySpecification = "2048"; 1469 if (!(p12PublicSignatureKey instanceof RSAPublicKey )) { 1470 Enumeration en = ECNamedCurveTable.getNames(); 1471 while ( en.hasMoreElements() ) { 1472 String currentCurveName = (String ) en.nextElement(); 1473 if ( (ECNamedCurveTable.getParameterSpec(currentCurveName)).getCurve().equals( ((ECPrivateKey) p12PrivateSignatureKey).getParameters().getCurve() ) ) { 1474 keySpecification = currentCurveName; 1475 keyAlgorithm = CATokenConstants.KEYALGORITHM_ECDSA; 1476 break; 1477 } 1478 } 1479 } 1480 ArrayList extendedcaservices = new ArrayList (); 1481 extendedcaservices.add( 1482 new OCSPCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE, 1483 "CN=OCSPSignerCertificate, " + caSignatureCertificate.getSubjectDN().toString(), 1484 "", 1485 keySpecification, 1486 keyAlgorithm)); 1487 extendedcaservices.add( 1489 new XKMSCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, 1490 "CN=XKMSCertificate, " + caSignatureCertificate.getSubjectDN().toString(), 1491 "", 1492 keySpecification, 1493 keyAlgorithm)); 1494 extendedcaservices.add( 1496 new CmsCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, 1497 "CN=CMSCertificate, " + caSignatureCertificate.getSubjectDN().toString(), 1498 "", 1499 keySpecification, 1500 keyAlgorithm)); 1501 int validity = (int)((caSignatureCertificate.getNotAfter().getTime() - caSignatureCertificate.getNotBefore().getTime()) / (24*3600*1000)); 1502 X509CAInfo cainfo = new X509CAInfo(caSignatureCertificate.getSubjectDN().toString(), 1503 caname, SecConst.CA_ACTIVE, new Date (), 1504 "", certprof, 1505 validity, 1506 caSignatureCertificate.getNotAfter(), CAInfo.CATYPE_X509, 1508 signedby, 1509 certificatechain, 1510 catoken.getCATokenInfo(), 1511 description, 1512 -1, null, "", 24, 0, 10, new ArrayList (), 1518 true, false, true, false, "", "", "", true, extendedcaservices, 1527 false, new ArrayList (), 1, false); X509CA ca = new X509CA(cainfo); 1532 ca.setCAToken(catoken); 1533 ca.setCertificateChain(certificatechain); 1534 log.debug("CA-Info: "+catoken.getCATokenInfo().getSignatureAlgorithm() + " " + ca.getCAToken().getCATokenInfo().getEncryptionAlgorithm()); 1535 getSignSession().publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers()); 1537 Iterator iter = cainfo.getExtendedCAServiceInfos().iterator(); 1539 while(iter.hasNext()){ 1540 ExtendedCAServiceInfo info = (ExtendedCAServiceInfo) iter.next(); 1541 if(info instanceof OCSPCAServiceInfo){ 1542 try{ 1543 ca.initExternalService(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE, ca); 1544 ArrayList ocspcertificate = new ArrayList (); 1545 ocspcertificate.add(((OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE)).getOCSPSignerCertificatePath().get(0)); 1546 getSignSession().publishCACertificate(admin, ocspcertificate, ca.getCRLPublishers()); 1547 }catch(Exception fe){ 1548 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,"Couldn't Create ExternalCAService.",fe); 1549 throw new EJBException (fe); 1550 } 1551 } 1552 if(info instanceof XKMSCAServiceInfo){ 1553 try{ 1554 ca.initExternalService(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE, ca); 1555 ArrayList xkmscertificate = new ArrayList (); 1556 xkmscertificate.add(((XKMSCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE)).getXKMSSignerCertificatePath().get(0)); 1557 getSignSession().publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers()); 1558 }catch(Exception fe){ 1559 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,"Couldn't Create ExternalCAService.",fe); 1560 throw new EJBException (fe); 1561 } 1562 } 1563 if(info instanceof CmsCAServiceInfo){ 1564 try{ 1565 ca.initExternalService(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE, ca); 1566 ArrayList cmscertificate = new ArrayList (); 1567 cmscertificate.add(((CmsCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE)).getCertificatePath().get(0)); 1568 getSignSession().publishCACertificate(admin, cmscertificate, ca.getCRLPublishers()); 1569 }catch(Exception fe){ 1570 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,"Couldn't Create ExternalCAService.",fe); 1571 throw new EJBException (fe); 1572 } 1573 } 1574 } 1575 cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_ACTIVE, ca); 1577 this.getCRLCreateSession().run(admin,cainfo.getSubjectDN()); 1578 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CACREATED,"CA imported successfully from old P12 file, status: " + ca.getStatus()); 1579 } catch(Exception e) { 1580 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CACREATED,"An error occured when trying to import CA from old P12 file", e); 1581 throw new EJBException (e); 1582 } 1583 } 1585 1599 public byte[] exportCAKeyStore(Admin admin, String caname, char[] keystorepass, char[] privkeypass, String privateSignatureKeyAlias, 1600 String privateEncryptionKeyAlias) throws Exception { 1601 log.debug(">exportCAKeyStore"); 1602 try { 1603 CA thisCa = cadatahome.findByName(caname).getCA(); 1604 if ( thisCa.getCAType() != CATokenInfo.CATOKENTYPE_P12 ) { 1606 throw new Exception ("Cannot export anything but a soft token."); 1607 } 1608 if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) { 1610 getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.ROLE_SUPERADMINISTRATOR); 1611 } 1612 CAToken thisCAToken = thisCa.getCAToken(); 1614 KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); 1615 keystore.load(null, keystorepass); 1616 1617 PrivateKey p12PrivateEncryptionKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); 1618 PublicKey p12PublicEncryptionKey = ((SoftCAToken) thisCAToken).getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); 1619 PrivateKey p12PrivateCertSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN); 1620 PrivateKey p12PrivateCRLSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN); 1621 if ( !p12PrivateCertSignKey.equals(p12PrivateCRLSignKey) ) { 1622 throw new Exception ("Assertion of equal signature keys failed."); 1623 } 1624 X509Certificate [] certificateChainSignature = (X509Certificate []) thisCa.getCertificateChain().toArray(new X509Certificate [0]); 1626 X509Certificate [] certificateChainEncryption = new X509Certificate [1]; 1627 certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null, p12PrivateEncryptionKey, p12PublicEncryptionKey, 1630 thisCAToken.getCATokenInfo().getEncryptionAlgorithm(), true, X509KeyUsage.keyEncipherment); 1631 log.debug("Exporting with sigAlgorithm "+certificateChainSignature[0].getSigAlgName()+"encAlgorithm="+thisCAToken.getCATokenInfo().getEncryptionAlgorithm()); 1632 if ( keystore.isKeyEntry(privateSignatureKeyAlias) ) { 1633 throw new Exception ("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore."); 1634 } 1635 if ( keystore.isKeyEntry(privateEncryptionKeyAlias) ) { 1636 throw new Exception ("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore."); 1637 } 1638 1639 keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass, certificateChainSignature); 1640 keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass, certificateChainEncryption); 1641 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 1643 keystore.store(baos, keystorepass); 1644 if ( keystore.isKeyEntry(privateSignatureKeyAlias) ) { 1645 keystore.deleteEntry(privateSignatureKeyAlias); 1646 } 1647 if ( keystore.isKeyEntry(privateEncryptionKeyAlias) ) { 1648 keystore.deleteEntry(privateEncryptionKeyAlias); 1649 } 1650 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEXPORTED,"CA exported successfully from to P12 file."); 1651 return baos.toByteArray(); 1652 } catch(Exception e){ 1653 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEXPORTED,"An error occured when trying to export CA to P12 file", e); 1654 throw new EJBException (e); 1655 } 1656 } 1658 1659 1667 public Collection getAllCACertificates(Admin admin){ 1668 ArrayList returnval = new ArrayList (); 1669 1670 try{ 1671 Collection caids = getAvailableCAs(admin); 1672 Iterator iter = caids.iterator(); 1673 while(iter.hasNext()){ 1674 Integer caid = (Integer )iter.next(); 1675 CADataLocal cadata = cadatahome.findByPrimaryKey(caid); 1676 CA ca = cadata.getCA(); 1677 if (log.isDebugEnabled()) { 1678 debug("Getting certificate chain for CA: "+ca.getName()+", "+ca.getCAId()); 1679 } 1680 returnval.add(ca.getCACertificate()); 1681 } 1682 }catch(javax.ejb.FinderException fe) { 1683 error("Can't find CA: ", fe); 1684 } catch(UnsupportedEncodingException uee){ 1685 throw new EJBException (uee); 1686 } catch(IllegalKeyStoreException e){ 1687 throw new EJBException (e); 1688 } 1689 return returnval; 1690 } 1692 1700 public boolean isKeyStorePassword(Admin admin, String capassword) { 1701 try { 1702 if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) { 1703 getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.ROLE_SUPERADMINISTRATOR); 1704 } 1705 } catch (AuthorizationDeniedException e) { 1706 return false; 1707 } 1708 String keyStorePass = ServiceLocator.getInstance().getString("java:comp/env/keyStorePass"); 1709 return ( keyStorePass.equals(capassword) ); 1710 } 1712 1720 public String getKeyFingerPrint(Admin admin, String caname) throws Exception { 1721 try { 1722 if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) { 1723 getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.ROLE_SUPERADMINISTRATOR); 1724 } 1725 CA thisCa; 1726 thisCa = cadatahome.findByName(caname).getCA(); 1727 1728 if ( thisCa.getCAType() != CATokenInfo.CATOKENTYPE_P12 ) { 1730 throw new Exception ("Cannot extract fingerprint from a non-soft token."); 1731 } 1732 CAToken thisCAToken = thisCa.getCAToken(); 1734 PrivateKey p12PrivateEncryptionKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); 1735 PrivateKey p12PrivateCertSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN); 1736 PrivateKey p12PrivateCRLSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN); 1737 MessageDigest md = MessageDigest.getInstance("SHA1"); 1738 md.update(p12PrivateEncryptionKey.getEncoded()); 1739 md.update(p12PrivateCertSignKey.getEncoded()); 1740 md.update(p12PrivateCRLSignKey.getEncoded()); 1741 return new String (Hex.encode(md.digest())); 1742 } catch (Exception e) { 1743 throw new Exception (e); 1744 } 1745 } 1747 1748 1762 public void activateCAToken(Admin admin, int caid, String authorizationcode) throws AuthorizationDeniedException, CATokenAuthenticationFailedException, CATokenOfflineException{ 1763 try{ 1765 getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.REGULAR_ACTIVATECA); 1766 }catch(AuthorizationDeniedException ade){ 1767 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoactivatetoken", new Integer (caid)); 1768 getLogSession().log (admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,ade); 1769 throw new AuthorizationDeniedException(msg); 1770 } 1771 1772 try{ 1773 if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){ 1774 String msg = intres.getLocalizedMessage("caadmin.erroractivatetoken", new Integer (caid)); 1775 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1776 throw new CATokenAuthenticationFailedException(msg); 1777 } 1778 CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer (caid)); 1779 boolean cATokenDisconnected = false; 1780 try{ 1781 if(cadata.getCA().getCAToken().getCATokenInfo() instanceof HardCATokenInfo){ 1782 if(((HardCATokenInfo) cadata.getCA().getCAToken().getCATokenInfo()).getCATokenStatus() == IHardCAToken.STATUS_OFFLINE){ 1783 cATokenDisconnected = true; 1784 } 1785 } 1786 }catch (IllegalKeyStoreException e) { 1787 String msg = intres.getLocalizedMessage("caadmin.errorreadingtoken", new Integer (caid)); 1788 log.error(msg,e); 1789 } catch (UnsupportedEncodingException e) { 1790 String msg = intres.getLocalizedMessage("caadmin.errorreadingtoken", new Integer (caid)); 1791 log.error(msg,e); 1792 } 1793 if(cadata.getStatus() == SecConst.CA_OFFLINE || cATokenDisconnected){ 1794 try { 1795 cadata.getCA().getCAToken().activate(authorizationcode); 1796 cadata.setStatus(SecConst.CA_ACTIVE); 1797 CACacheManager.instance().removeCA(cadata.getCaId().intValue()); 1799 String msg = intres.getLocalizedMessage("caadmin.catokenactivated", cadata.getName()); 1800 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED,msg); 1801 } catch (IllegalKeyStoreException e) { 1802 throw new EJBException (e); 1803 } catch (UnsupportedEncodingException e) { 1804 throw new EJBException (e); 1805 } 1806 }else{ 1807 String msg = intres.getLocalizedMessage("caadmin.errornotoffline", cadata.getName()); 1808 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1809 throw new CATokenAuthenticationFailedException(msg); 1810 } 1811 }catch(javax.ejb.FinderException fe) { 1812 String msg = intres.getLocalizedMessage("caadmin.errorcanotfound", new Integer (caid)); 1813 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1814 throw new EJBException (fe); 1815 } 1816 } 1817 1818 1830 public void deactivateCAToken(Admin admin, int caid) throws AuthorizationDeniedException, EjbcaException{ 1831 try{ 1833 getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.REGULAR_ACTIVATECA); 1834 }catch(AuthorizationDeniedException ade){ 1835 String msg = intres.getLocalizedMessage("caadmin.notauthorizedtodeactivatetoken", new Integer (caid)); 1836 getLogSession().log (admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,ade); 1837 throw new AuthorizationDeniedException(msg); 1838 } 1839 1840 try{ 1841 if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){ 1842 String msg = intres.getLocalizedMessage("caadmin.errordeactivatetoken", new Integer (caid)); 1844 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1845 throw new EjbcaException(msg); 1846 } 1847 CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer (caid)); 1848 if(cadata.getStatus() == SecConst.CA_ACTIVE){ 1849 try { 1850 cadata.getCA().getCAToken().deactivate(); 1851 cadata.setStatus(SecConst.CA_OFFLINE); 1852 CACacheManager.instance().removeCA(cadata.getCaId().intValue()); 1854 String msg = intres.getLocalizedMessage("caadmin.catokendeactivated", cadata.getName()); 1855 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_INFO_CAEDITED,msg); 1856 } catch (IllegalKeyStoreException e) { 1857 throw new EJBException (e); 1858 } catch (UnsupportedEncodingException e) { 1859 throw new EJBException (e); 1860 } 1861 }else{ 1862 String msg = intres.getLocalizedMessage("caadmin.errornotonline", cadata.getName()); 1863 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1864 throw new EjbcaException(msg); 1865 } 1866 }catch(javax.ejb.FinderException fe) { 1867 String msg = intres.getLocalizedMessage("caadmin.errorcanotfound", new Integer (caid)); 1868 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg); 1869 throw new EJBException (fe); 1870 } 1871 } 1872 1873 1878 public boolean exitsCertificateProfileInCAs(Admin admin, int certificateprofileid){ 1879 boolean returnval = false; 1880 try{ 1881 Collection result = cadatahome.findAll(); 1882 Iterator iter = result.iterator(); 1883 while(iter.hasNext()){ 1884 CADataLocal cadata = (CADataLocal) iter.next(); 1885 returnval = returnval || (cadata.getCA().getCertificateProfileId() == certificateprofileid); 1886 } 1887 }catch(javax.ejb.FinderException fe){} 1888 catch(java.io.UnsupportedEncodingException e){} 1889 catch(IllegalKeyStoreException e){} 1890 1891 return returnval; 1892 } 1894 1895 1900 public boolean exitsPublisherInCAs(Admin admin, int publisherid){ 1901 boolean returnval = false; 1902 try{ 1903 Collection result = cadatahome.findAll(); 1904 Iterator iter = result.iterator(); 1905 while(iter.hasNext()){ 1906 CADataLocal cadata = (CADataLocal) iter.next(); 1907 Iterator pubiter = cadata.getCA().getCRLPublishers().iterator(); 1908 while(pubiter.hasNext()){ 1909 Integer pubInt = (Integer )pubiter.next(); 1910 returnval = returnval || (pubInt.intValue() == publisherid); 1911 } 1912 } 1913 }catch(javax.ejb.FinderException fe){} 1914 catch(java.io.UnsupportedEncodingException e){} 1915 catch(IllegalKeyStoreException e){} 1916 1917 return returnval; 1918 } 1920 private boolean authorizedToCA(Admin admin, int caid){ 1921 boolean returnval = false; 1922 try{ 1923 returnval = getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.CAPREFIX + caid); 1924 }catch(AuthorizationDeniedException e){} 1925 return returnval; 1926 } 1927 1928 1932 1934 private ILogSessionLocal getLogSession() { 1935 if(logsession == null){ 1936 try{ 1937 ILogSessionLocalHome home = (ILogSessionLocalHome) getLocator().getLocalHome(ILogSessionLocalHome.COMP_NAME); 1938 logsession = home.create(); 1939 }catch(Exception e){ 1940 throw new EJBException (e); 1941 } 1942 } 1943 return logsession; 1944 } 1946 1947 1950 private IAuthorizationSessionLocal getAuthorizationSession() { 1951 if(authorizationsession == null){ 1952 try{ 1953 IAuthorizationSessionLocalHome home = (IAuthorizationSessionLocalHome) getLocator().getLocalHome(IAuthorizationSessionLocalHome.COMP_NAME); 1954 authorizationsession = home.create(); 1955 }catch(Exception e){ 1956 throw new EJBException (e); 1957 } 1958 } 1959 return authorizationsession; 1960 } 1962 1965 private ICreateCRLSessionLocal getCRLCreateSession() { 1966 if(jobrunner == null){ 1967 try{ 1968 ICreateCRLSessionLocalHome home = (ICreateCRLSessionLocalHome) getLocator().getLocalHome(ICreateCRLSessionLocalHome.COMP_NAME); 1969 jobrunner = home.create(); 1970 }catch(Exception e){ 1971 throw new EJBException (e); 1972 } 1973 } 1974 return jobrunner; 1975 } 1976 1977 1980 private ICertificateStoreSessionLocal getCertificateStoreSession() { 1981 if(certificatestoresession == null){ 1982 try{ 1983 ICertificateStoreSessionLocalHome home = (ICertificateStoreSessionLocalHome) getLocator().getLocalHome(ICertificateStoreSessionLocalHome.COMP_NAME); 1984 certificatestoresession = home.create(); 1985 }catch(Exception e){ 1986 throw new EJBException (e); 1987 } 1988 } 1989 return certificatestoresession; 1990 } 1992 1995 private ISignSessionLocal getSignSession() { 1996 if(signsession == null){ 1997 try{ 1998 ISignSessionLocalHome signsessionhome = (ISignSessionLocalHome) getLocator().getLocalHome(ISignSessionLocalHome.COMP_NAME); 1999 signsession = signsessionhome.create(); 2000 }catch(Exception e){ 2001 throw new EJBException (e); 2002 } 2003 } 2004 return signsession; 2005 } 2007 2019 private boolean verifyIssuer(X509Certificate subject, X509Certificate issuer) throws Exception { 2020 try { 2021 PublicKey issuerKey = issuer.getPublicKey(); 2022 subject.verify(issuerKey); 2023 return true; 2024 } catch (java.security.GeneralSecurityException e) { 2025 return false; 2026 } 2027 } 2028 2029 2038 private void checkSignerValidity(Admin admin, CADataLocal signcadata) throws UnsupportedEncodingException , IllegalKeyStoreException { 2039 X509Certificate signcert = (X509Certificate ) signcadata.getCA().getCACertificate(); 2041 try{ 2042 signcert.checkValidity(); 2043 }catch(CertificateExpiredException ce){ 2044 signcadata.setStatus(SecConst.CA_EXPIRED); 2046 String msg = intres.getLocalizedMessage("signsession.caexpired", signcadata.getSubjectDN()); 2047 getLogSession().log(admin, signcadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,ce); 2048 throw new EJBException (ce); 2049 }catch(CertificateNotYetValidException cve){ 2050 String msg = intres.getLocalizedMessage("signsession.canotyetvalid", signcadata.getSubjectDN()); 2051 getLogSession().log(admin, signcadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date (), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,cve); 2052 throw new EJBException (cve); 2053 } 2054 } 2055 2056 2063 private Collection createCertChain(Collection certlist) throws CertPathValidatorException { 2064 ArrayList returnval = new ArrayList (); 2065 2066 certlist = orderCertificateChain(certlist); 2067 2068 TrustAnchor trustanchor = null; 2070 ArrayList calist = new ArrayList (); 2071 Iterator iter = certlist.iterator(); 2072 while(iter.hasNext()){ 2073 Certificate next = (Certificate ) iter.next(); 2074 if(next instanceof X509Certificate && CertTools.isSelfSigned(((X509Certificate ) next))){ 2075 trustanchor = new TrustAnchor ((X509Certificate ) next, null); 2076 } 2077 else{ 2078 calist.add(next); 2079 } 2080 } 2081 2082 if(calist.size() == 0){ 2083 returnval.add(trustanchor.getTrustedCert()); 2085 }else{ 2086 try { 2087 HashSet trustancors = new HashSet (); 2088 trustancors.add(trustanchor); 2089 2090 2093 2094 PKIXParameters params = new PKIXParameters (trustancors); 2096 2097 params.setRevocationEnabled(false); 2099 params.setDate( new Date () ); 2101 2103 CertPathValidator certPathValidator 2104 = CertPathValidator.getInstance(CertPathValidator.getDefaultType(), "BC"); 2105 CertificateFactory fact = CertTools.getCertificateFactory(); 2106 CertPath certpath = fact.generateCertPath(calist); 2107 2108 iter = certpath.getCertificates().iterator(); 2109 2110 2111 CertPathValidatorResult result = certPathValidator.validate(certpath, params); 2112 2113 PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult )result; 2115 returnval.addAll(certpath.getCertificates()); 2116 2117 TrustAnchor ta = pkixResult.getTrustAnchor(); 2119 X509Certificate cert = ta.getTrustedCert(); 2120 returnval.add(cert); 2121 } catch (CertPathValidatorException e) { 2122 throw e; 2123 } catch(Exception e){ 2124 throw new EJBException (e); 2125 } 2126 } 2127 2128 2129 return returnval; 2130 } 2131 2132 2138 private Collection orderCertificateChain(Collection certlist) throws CertPathValidatorException { 2139 ArrayList returnval = new ArrayList (); 2140 X509Certificate rootca = null; 2141 HashMap cacertmap = new HashMap (); 2142 Iterator iter = certlist.iterator(); 2143 while(iter.hasNext()){ 2144 X509Certificate cert = (X509Certificate ) iter.next(); 2145 if(CertTools.isSelfSigned(cert)) 2146 rootca = cert; 2147 else 2148 cacertmap.put(cert.getIssuerDN().toString(),cert); 2149 } 2150 2151 if(rootca == null) 2152 throw new CertPathValidatorException ("No root CA certificate found in certificatelist"); 2153 2154 returnval.add(0,rootca); 2155 X509Certificate currentcert = rootca; 2156 int i =0; 2157 while(certlist.size() != returnval.size() && i <= certlist.size()){ 2158 X509Certificate nextcert = (X509Certificate ) cacertmap.get(currentcert.getSubjectDN().toString()); 2159 if(nextcert == null) 2160 throw new CertPathValidatorException ("Error building certificate path"); 2161 2162 returnval.add(0,nextcert); 2163 currentcert = nextcert; 2164 i++; 2165 } 2166 2167 if(i > certlist.size()) 2168 throw new CertPathValidatorException ("Error building certificate path"); 2169 2170 2171 return returnval; 2172 } 2173 2174 2175} | Popular Tags |