Admin admin = ejbhelper.getAdmin(true);
int endEntityProfileId = 0;
boolean hardTokenExists = false;
boolean userExists = false;
ApprovalRequest ar = null;
boolean approvalSuccessfullStep1 = false;
boolean isRejectedStep1 = false;
// Get Significant user Id
final CAInfo significantcAInfo;
final ArrayList<java.security.cert.Certificate> genCertificates = new ArrayList<java.security.cert.Certificate>();
final IPatternLogger logger = TransactionLogger.getPatternLogger();
logAdminName(admin,logger);
try {
significantcAInfo = caAdminSession.getCAInfoOrThrowException(intAdmin, userDataWS.getCaName());
if(significantcAInfo == null){
throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + userDataWS.getCaName() + " couldn't be found.",
logger, ErrorCode.CA_NOT_EXISTS, null);
}
UserDataVO userDataVO = userAdminSession.findUser(intAdmin, userDataWS.getUsername());
if(userDataVO != null){
endEntityProfileId = userDataVO.getEndEntityProfileId();
userExists = true;
}else{
endEntityProfileId = endEntityProfileSession.getEndEntityProfileId(intAdmin, userDataWS.getEndEntityProfileName());
if(endEntityProfileId == 0){
throw EjbcaWSHelper.getEjbcaException("Error given end entity profile : " + userDataWS.getEndEntityProfileName() +" couldn't be found",
logger, ErrorCode.EE_PROFILE_NOT_EXISTS, null);
}
}
if(ejbhelper.isAdmin()){
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE, null);
}
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS, null);
}
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + significantcAInfo.getCAId())) {
throw new AuthorizationDeniedException("Admin " + admin + " was not authorized to resource " + AccessRulesConstants.CAPREFIX
+ significantcAInfo.getCAId());
}
if (userExists) {
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_EDITENDENTITY)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_EDITENDENTITY, null);
}
endEntityProfileId = userDataVO.getEndEntityProfileId();
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.EDIT_RIGHTS)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.EDIT_RIGHTS, null);
}
if (overwriteExistingSN) {
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
}
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.REVOKE_RIGHTS)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.REVOKE_RIGHTS, null);
}
}
} else {
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY, null);
}
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.CREATE_RIGHTS)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.CREATE_RIGHTS, null);
}
if (overwriteExistingSN) {
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
}
if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.REVOKE_RIGHTS)) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
+ AccessRulesConstants.REVOKE_RIGHTS, null);
}
}
}
}else{
if(WebServiceConfiguration.getApprovalForGenTokenCertificates()){
ar = new GenerateTokenApprovalRequest(userDataWS.getUsername(), userDataWS.getSubjectDN(), hardTokenDataWS.getLabel(),admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),significantcAInfo.getCAId(),endEntityProfileId);
int status = ApprovalDataVO.STATUS_REJECTED;
try{
status = approvalSession.isApproved(admin, ar.generateApprovalId(), 1);
approvalSuccessfullStep1 = status == ApprovalDataVO.STATUS_APPROVED;
if(approvalSuccessfullStep1){
ApprovalDataVO approvalDataVO = approvalSession.findNonExpiredApprovalRequest(intAdmin, ar.generateApprovalId());
String originalDN = ((GenerateTokenApprovalRequest) approvalDataVO.getApprovalRequest()).getDN();
userDataWS.setSubjectDN(originalDN); // replace requested DN with original DN to make sure nothing have changed.
}
isRejectedStep1 = status == ApprovalDataVO.STATUS_REJECTED;
if( status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
|| status == ApprovalDataVO.STATUS_EXPIRED){
throw new ApprovalException("");
}
}catch(ApprovalException e){
approvalSession.addApprovalRequest(admin, ar, globalConfigurationSession.getCachedGlobalConfiguration(admin));
throw new WaitingForApprovalException("Approval request with id " + ar.generateApprovalId() + " have been added for approval.",ar.generateApprovalId());
}
}else{
throw new AuthorizationDeniedException();
}
}
if(ar != null && isRejectedStep1){
throw new ApprovalRequestExecutionException("The approval for id " + ar.generateApprovalId() + " have been rejected.");
}
if(ar != null && !approvalSuccessfullStep1){
throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId() + " have not yet been approved", ar.generateApprovalId());
}
if(ar != null){
admin = new ApprovedActionAdmin(admin.getAdminInformation().getX509Certificate(), admin.getUsername(), admin.getEmail());
}
hardTokenExists = hardTokenSession.existsHardToken(admin, hardTokenDataWS.getHardTokenSN());
if(hardTokenExists){
if(overwriteExistingSN){
// fetch all old certificates and revoke them.
Collection<java.security.cert.Certificate> currentCertificates = hardTokenSession.findCertificatesInHardToken(admin, hardTokenDataWS.getHardTokenSN());
HardTokenData currentHardToken = hardTokenSession.getHardToken(admin, hardTokenDataWS.getHardTokenSN(), false);
Iterator<java.security.cert.Certificate> iter = currentCertificates.iterator();
while(iter.hasNext()){
java.security.cert.X509Certificate nextCert = (java.security.cert.X509Certificate) iter.next();
try {
userAdminSession.revokeCert(admin, CertTools.getSerialNumber(nextCert), CertTools.getIssuerDN(nextCert), RevokedCertInfo.REVOCATION_REASON_SUPERSEDED);
} catch (AlreadyRevokedException e) {
// Ignore previously revoked certificates
} catch (FinderException e) {
throw EjbcaWSHelper.getEjbcaException("Error revoking old certificate, the user : " + currentHardToken.getUsername() + " of the old certificate couldn't be found in database.",
logger, ErrorCode.USER_NOT_FOUND, null);
}
}
}else{
throw new HardTokenExistsException("Error hard token with sn " + hardTokenDataWS.getHardTokenSN() + " already exists.");
}
}
if(revokePreviousCards){
List<HardTokenDataWS> htd = getHardTokenDatas(admin,userDataWS.getUsername(), false, true, logger);
Iterator<HardTokenDataWS> htdIter = htd.iterator();
while(htdIter.hasNext()) {
HardTokenDataWS toRevoke = htdIter.next();
try{
if(hardTokenDataWS.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD) && toRevoke.getLabel() != null && !toRevoke.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)){
// Token have extended key usage MS Logon, don't revoke it
Iterator<java.security.cert.Certificate> revokeCerts = hardTokenSession.findCertificatesInHardToken(admin, toRevoke.getHardTokenSN()).iterator();
while(revokeCerts.hasNext()){
X509Certificate next = (X509Certificate) revokeCerts.next();
try{
if(WebServiceConfiguration.getSuspendAllCertificates() || next.getExtendedKeyUsage() == null || !next.getExtendedKeyUsage().contains(KeyPurposeId.id_kp_smartcardlogon.getId())){
userAdminSession.revokeCert(admin,next.getSerialNumber(), CertTools.getIssuerDN(next), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
}
}catch(CertificateParsingException e){
log.error(e);
} catch (FinderException e) {
log.error(e);
}
}
}else{
revokeToken(admin, toRevoke.getHardTokenSN(), RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, logger);
}
}catch(AlreadyRevokedException e){
// Do nothing
}
}
}
try{
// Check if the userdata exist and edit/add it depending on which
String password = PasswordGeneratorFactory.getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE).getNewPassword(8, 8);
UserDataVO userData = ejbhelper.convertUserDataVOWS(admin, userDataWS);
userData.setPassword(password);
if(userExists){
userAdminSession.changeUser(admin, userData, true);
}else{
userAdminSession.addUser(admin, userData, true);
}
Date bDate = new Date(System.currentTimeMillis() - (10 * 60 * 1000));
Iterator<TokenCertificateRequestWS> iter = tokenRequests.iterator();
while(iter.hasNext()){
TokenCertificateRequestWS next = iter.next();
int certificateProfileId = certificateProfileSession.getCertificateProfileId(admin, next.getCertificateProfileName());
if(certificateProfileId == 0){
EjbcaWSHelper.getEjbcaException("Error the given Certificate Profile : " + next.getCertificateProfileName() + " couldn't be found.",
logger, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
}
Date eDate = null;
if(next.getValidityIdDays() != null ){
try{
long validity = Long.parseLong(next.getValidityIdDays());
eDate = new Date(System.currentTimeMillis() + (validity * 3600 *24 * 1000));
}catch (NumberFormatException e){
EjbcaWSHelper.getEjbcaException("Error : Validity in Days must be a number",
logger, ErrorCode.BAD_VALIDITY_FORMAT, null);
}
}
CAInfo cAInfo = caAdminSession.getCAInfo(admin, next.getCAName());
if(cAInfo == null){
throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + next.getCAName() + " couldn't be found.",
logger, ErrorCode.CA_NOT_EXISTS, null);
}
if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId())) {
Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId(), null);
}
if(next.getType() == HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST){
userData.setCertificateProfileId(certificateProfileId);
userData.setCAId(cAInfo.getCAId());
userData.setPassword(password);
userData.setStatus(UserDataConstants.STATUS_NEW);
userAdminSession.changeUser(admin, userData, false);
PKCS10RequestMessage pkcs10req = new PKCS10RequestMessage(next.getPkcs10Data());
java.security.cert.Certificate cert;
if(eDate == null){
cert = signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey());
}else{
cert = signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey(), -1, bDate, eDate);
}
genCertificates.add(cert);
retval.add(new TokenCertificateResponseWS(new Certificate(cert)));
}else
if(next.getType() == HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST){
if(!next.getTokenType().equals(HardTokenConstants.TOKENTYPE_PKCS12)){
throw EjbcaWSHelper.getEjbcaException("Unsupported Key Store Type : " + next.getTokenType() + " only " + HardTokenConstants.TOKENTYPE_PKCS12 + " is supported",
logger, ErrorCode.NOT_SUPPORTED_KEY_STORE, null);
}
KeyPair keys = KeyTools.genKeys(next.getKeyspec(), next.getKeyalg());
userData.setCertificateProfileId(certificateProfileId);
userData.setCAId(cAInfo.getCAId());
userData.setPassword(password);
userData.setStatus(UserDataConstants.STATUS_NEW);
userAdminSession.changeUser(admin, userData, true);
X509Certificate cert;
if(eDate == null){
cert = (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic());
}else{
cert = (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic(), -1, bDate, eDate);
}
genCertificates.add(cert);
// Generate Keystore
// Fetch CA Cert Chain.
Collection<java.security.cert.Certificate> chain = caAdminSession.getCAInfo(admin, cAInfo.getCAId()).getCertificateChain();
String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
if (alias == null){
alias = userData.getUsername();
}
java.security.KeyStore pkcs12 = KeyTools.createP12(alias, keys.getPrivate(), cert, chain);
retval.add(new TokenCertificateResponseWS(new KeyStore(pkcs12, userDataWS.getPassword())));
}else{
throw EjbcaWSHelper.getEjbcaException("Error in request, only REQUESTTYPE_PKCS10_REQUEST and REQUESTTYPE_KEYSTORE_REQUEST are supported token requests.",
logger, ErrorCode.NOT_SUPPORTED_REQUEST_TYPE, null);
}
}
} catch(Exception e){
throw EjbcaWSHelper.getInternalException(e, logger);
} finally{
userAdminSession.setUserStatus(admin, userDataWS.getUsername(), UserDataConstants.STATUS_GENERATED);
}
// Add hard token data
HardToken hardToken;
String signatureInitialPIN = "";
String signaturePUK = "";
String basicInitialPIN = "";
String basicPUK = "";
Iterator<PinDataWS> iter = hardTokenDataWS.getPinDatas().iterator();
while(iter.hasNext()){
PinDataWS pinData = iter.next();
switch(pinData.getType()){
case HardTokenConstants.PINTYPE_BASIC :
basicInitialPIN = pinData.getInitialPIN();
basicPUK = pinData.getPUK();
break;
case HardTokenConstants.PINTYPE_SIGNATURE :
signatureInitialPIN = pinData.getInitialPIN();
signaturePUK = pinData.getPUK();
break;
default :
throw EjbcaWSHelper.getEjbcaException("Unsupported PIN Type " + pinData.getType(),
logger, ErrorCode.NOT_SUPPORTED_PIN_TYPE, null);
}
}
int tokenType = SwedishEIDHardToken.THIS_TOKENTYPE;
switch (hardTokenDataWS.getTokenType()){
case HardTokenConstants.TOKENTYPE_SWEDISHEID :
hardToken = new SwedishEIDHardToken(basicInitialPIN,basicPUK,signatureInitialPIN,signaturePUK,0);
break;
case HardTokenConstants.TOKENTYPE_ENHANCEDEID :
hardToken = new EnhancedEIDHardToken(signatureInitialPIN,signaturePUK,basicInitialPIN,basicPUK,false,0);
tokenType = EnhancedEIDHardToken.THIS_TOKENTYPE;
break;
default:
throw EjbcaWSHelper.getEjbcaException("Unsupported Token Type : " + hardTokenDataWS.getTokenType(),
logger, ErrorCode.NOT_SUPPORTED_TOKEN_TYPE, null);
}
hardToken.setLabel(hardTokenDataWS.getLabel());
if(overwriteExistingSN){
if(hardTokenExists){
try {
hardTokenSession.removeHardToken(admin, hardTokenDataWS.getHardTokenSN());
} catch (HardTokenDoesntExistsException e) {
throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.HARD_TOKEN_NOT_EXISTS, Level.ERROR);
}
}
}
hardTokenSession.addHardToken(admin, hardTokenDataWS.getHardTokenSN(), userDataWS.getUsername(), significantcAInfo.getSubjectDN(), tokenType, hardToken, genCertificates, hardTokenDataWS.getCopyOfSN());
if(ar!= null){
approvalSession.markAsStepDone(admin, ar.generateApprovalId(), GenerateTokenApprovalRequest.STEP_1_GENERATETOKEN);
}
} catch( EjbcaException e) {
throw e;
} catch (FinderException e) {
throw EjbcaWSHelper.getInternalException(e, logger);