use of org.xipki.security.ConcurrentContentSigner in project xipki by xipki.
the class CaManagerImpl method loadConf.
@Override
public void loadConf(CaConf conf) throws CaMgmtException {
ParamUtil.requireNonNull("conf", conf);
if (!caSystemSetuped) {
throw new CaMgmtException("CA system is not initialized yet.");
}
// CMP control
for (String name : conf.getCmpControlNames()) {
CmpControlEntry entry = conf.getCmpControl(name);
CmpControlEntry entryB = cmpControlDbEntries.get(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.info("ignore existed CMP control {}", name);
continue;
} else {
String msg = concat("CMP control ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
addCmpControl(entry);
LOG.info("added CMP control {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add CMP control ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// Responder
for (String name : conf.getResponderNames()) {
ResponderEntry entry = conf.getResponder(name);
ResponderEntry entryB = responderDbEntries.get(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.info("ignore existed CMP responder {}", name);
continue;
} else {
String msg = concat("CMP responder ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
addResponder(entry);
LOG.info("added CMP responder {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add CMP responder ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// Environment
for (String name : conf.getEnvironmentNames()) {
String entry = conf.getEnvironment(name);
String entryB = envParameterResolver.getParameter(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.info("ignore existed environment parameter {}", name);
continue;
} else {
String msg = concat("environment parameter ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
addEnvParam(name, entry);
LOG.info("could not add environment parameter {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add environment parameter ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// CRL signer
for (String name : conf.getCrlSignerNames()) {
X509CrlSignerEntry entry = conf.getCrlSigner(name);
X509CrlSignerEntry entryB = crlSignerDbEntries.get(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.info("ignore existed CRL signer {}", name);
continue;
} else {
String msg = concat("CRL signer ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
addCrlSigner(entry);
LOG.info("added CRL signer {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add CRL signer ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// Requestor
for (String name : conf.getRequestorNames()) {
RequestorEntry entry = conf.getRequestor(name);
RequestorEntry entryB = requestorDbEntries.get(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.info("ignore existed CMP requestor {}", name);
continue;
} else {
String msg = concat("CMP requestor ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
addRequestor(entry);
LOG.info("added CMP requestor {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add CMP requestor ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// Publisher
for (String name : conf.getPublisherNames()) {
PublisherEntry entry = conf.getPublisher(name);
PublisherEntry entryB = publisherDbEntries.get(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.info("ignore existed publisher {}", name);
continue;
} else {
String msg = concat("publisher ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
addPublisher(entry);
LOG.info("added publisher {}", name);
} catch (CaMgmtException ex) {
String msg = "could not add publisher " + name;
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// CertProfile
for (String name : conf.getCertProfileNames()) {
CertprofileEntry entry = conf.getCertProfile(name);
CertprofileEntry entryB = certprofileDbEntries.get(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.info("ignore existed certProfile {}", name);
continue;
} else {
String msg = concat("certProfile ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
addCertprofile(entry);
LOG.info("added certProfile {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add certProfile ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// User
for (String name : conf.getUserNames()) {
Object obj = conf.getUser(name);
UserEntry entryB = queryExecutor.getUser(name, true);
if (entryB != null) {
boolean equals = false;
if (obj instanceof UserEntry) {
UserEntry entry = (UserEntry) obj;
equals = entry.equals(entryB);
} else {
AddUserEntry entry = (AddUserEntry) obj;
equals = PasswordHash.validatePassword(entry.getPassword(), entryB.getHashedPassword());
}
if (equals) {
LOG.info("ignore existed user {}", name);
continue;
} else {
String msg = concat("user ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
}
try {
if (obj instanceof UserEntry) {
queryExecutor.addUser((UserEntry) obj);
} else {
queryExecutor.addUser((AddUserEntry) obj);
}
LOG.info("added user {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add user ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
// CA
for (String caName : conf.getCaNames()) {
SingleCaConf scc = conf.getCa(caName);
GenSelfIssued genSelfIssued = scc.getGenSelfIssued();
CaEntry caEntry = scc.getCaEntry();
if (caEntry != null) {
if (!(caEntry instanceof X509CaEntry)) {
throw new CaMgmtException(concat("Unsupported CaEntry ", caName, " (only X509CaEntry is supported"));
}
X509CaEntry entry = (X509CaEntry) caEntry;
if (caInfos.containsKey(caName)) {
CaEntry entryB = caInfos.get(caName).getCaEntry();
if (entry.getCert() == null && genSelfIssued != null) {
SignerConf signerConf = new SignerConf(entry.getSignerConf());
ConcurrentContentSigner signer;
try {
signer = securityFactory.createSigner(entry.getSignerType(), signerConf, (X509Certificate) null);
} catch (ObjectCreationException ex) {
throw new CaMgmtException(concat("could not create signer for CA ", caName), ex);
}
entry.setCert(signer.getCertificate());
}
if (entry.equals(entryB, true)) {
LOG.info("ignore existed CA {}", caName);
} else {
String msg = concat("CA ", caName, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
} else {
if (genSelfIssued != null) {
X509Certificate cert = generateRootCa(entry, genSelfIssued.getProfile(), genSelfIssued.getCsr(), genSelfIssued.getSerialNumber());
LOG.info("generated root CA {}", caName);
String fn = genSelfIssued.getCertFilename();
if (fn != null) {
try {
IoUtil.save(fn, cert.getEncoded());
LOG.info("saved generated certificate of root CA {} to {}", caName, fn);
} catch (CertificateEncodingException ex) {
LogUtil.error(LOG, ex, concat("could not encode certificate of CA ", caName));
} catch (IOException ex) {
LogUtil.error(LOG, ex, concat("error while saving certificate of root CA ", caName, " to ", fn));
}
}
} else {
try {
addCa(entry);
LOG.info("added CA {}", caName);
} catch (CaMgmtException ex) {
String msg = concat("could not add CA ", caName);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
}
}
if (scc.getAliases() != null) {
Set<String> aliasesB = getAliasesForCa(caName);
for (String aliasName : scc.getAliases()) {
if (aliasesB != null && aliasesB.contains(aliasName)) {
LOG.info("ignored adding existing CA alias {} to CA {}", aliasName, caName);
} else {
try {
addCaAlias(aliasName, caName);
LOG.info("associated alias {} to CA {}", aliasName, caName);
} catch (CaMgmtException ex) {
String msg = concat("could not associate alias ", aliasName, " to CA ", caName);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
}
}
if (scc.getProfileNames() != null) {
Set<String> profilesB = caHasProfiles.get(caName);
for (String profileName : scc.getProfileNames()) {
if (profilesB != null && profilesB.contains(profileName)) {
LOG.info("ignored adding certprofile {} to CA {}", profileName, caName);
} else {
try {
addCertprofileToCa(profileName, caName);
LOG.info("added certprofile {} to CA {}", profileName, caName);
} catch (CaMgmtException ex) {
String msg = concat("could not add certprofile ", profileName, " to CA ", caName);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
}
}
if (scc.getPublisherNames() != null) {
Set<String> publishersB = caHasPublishers.get(caName);
for (String publisherName : scc.getPublisherNames()) {
if (publishersB != null && publishersB.contains(publisherName)) {
LOG.info("ignored adding publisher {} to CA {}", publisherName, caName);
} else {
try {
addPublisherToCa(publisherName, caName);
LOG.info("added publisher {} to CA {}", publisherName, caName);
} catch (CaMgmtException ex) {
String msg = concat("could not add publisher ", publisherName, " to CA ", caName);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
}
}
if (scc.getRequestors() != null) {
Set<CaHasRequestorEntry> requestorsB = caHasRequestors.get(caName);
for (CaHasRequestorEntry requestor : scc.getRequestors()) {
String requestorName = requestor.getRequestorIdent().getName();
CaHasRequestorEntry requestorB = null;
if (requestorsB != null) {
for (CaHasRequestorEntry m : requestorsB) {
if (m.getRequestorIdent().getName().equals(requestorName)) {
requestorB = m;
break;
}
}
}
if (requestorB != null) {
if (requestor.equals(requestorB)) {
LOG.info("ignored adding requestor {} to CA {}", requestorName, caName);
} else {
String msg = concat("could not add requestor ", requestorName, " to CA", caName);
LOG.error(msg);
throw new CaMgmtException(msg);
}
} else {
try {
addRequestorToCa(requestor, caName);
LOG.info("added publisher {} to CA {}", requestorName, caName);
} catch (CaMgmtException ex) {
String msg = concat("could not add requestor ", requestorName, " to CA ", caName);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
}
}
if (scc.getUsers() != null) {
List<CaHasUserEntry> usersB = queryExecutor.getCaHasUsersForCa(caName, idNameMap);
for (CaHasUserEntry user : scc.getUsers()) {
String userName = user.getUserIdent().getName();
CaHasUserEntry userB = null;
if (usersB != null) {
for (CaHasUserEntry m : usersB) {
if (m.getUserIdent().getName().equals(userName)) {
userB = m;
break;
}
}
}
if (userB != null) {
if (user.equals(userB)) {
LOG.info("ignored adding user {} to CA {}", userName, caName);
} else {
String msg = concat("could not add user ", userName, " to CA", caName);
LOG.error(msg);
throw new CaMgmtException(msg);
}
} else {
try {
addUserToCa(user, caName);
LOG.info("added user {} to CA {}", userName, caName);
} catch (CaMgmtException ex) {
String msg = concat("could not add user ", userName, " to CA ", caName);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
}
}
// scc.getUsers()
}
// SCEP
for (String name : conf.getScepNames()) {
ScepEntry entry = conf.getScep(name);
ScepEntry entryB = scepDbEntries.get(name);
if (entryB != null) {
if (entry.equals(entryB)) {
LOG.error("ignore existed SCEP {}", name);
continue;
} else {
String msg = concat("SCEP ", name, " existed, could not re-added it");
LOG.error(msg);
throw new CaMgmtException(msg);
}
} else {
try {
addScep(entry);
LOG.info("added SCEP {}", name);
} catch (CaMgmtException ex) {
String msg = concat("could not add SCEP ", name);
LogUtil.error(LOG, ex, msg);
throw new CaMgmtException(msg);
}
}
}
}
use of org.xipki.security.ConcurrentContentSigner in project xipki by xipki.
the class OcspServerImpl method answer.
@Override
public OcspRespWithCacheInfo answer(Responder responder2, byte[] request, boolean viaGet) {
ResponderImpl responder = (ResponderImpl) responder2;
RequestOption reqOpt = responder.getRequestOption();
int version;
try {
version = OcspRequest.readRequestVersion(request);
} catch (EncodingException ex) {
String message = "could not extract version from request";
LOG.warn(message);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
if (!reqOpt.isVersionAllowed(version)) {
String message = "invalid request version " + version;
LOG.warn(message);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
ResponderSigner signer = responder.getSigner();
ResponseOption repOpt = responder.getResponseOption();
try {
Object reqOrRrrorResp = checkSignature(request, reqOpt);
if (reqOrRrrorResp instanceof OcspRespWithCacheInfo) {
return (OcspRespWithCacheInfo) reqOrRrrorResp;
}
OcspRequest req = (OcspRequest) reqOrRrrorResp;
List<CertID> requestList = req.getRequestList();
int requestsSize = requestList.size();
if (requestsSize > reqOpt.getMaxRequestListCount()) {
String message = requestsSize + " entries in RequestList, but maximal " + reqOpt.getMaxRequestListCount() + " is allowed";
LOG.warn(message);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
OcspRespControl repControl = new OcspRespControl();
repControl.canCacheInfo = true;
List<ExtendedExtension> reqExtensions = req.getExtensions();
List<Extension> respExtensions = new LinkedList<>();
ExtendedExtension nonceExtn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_NONCE);
if (nonceExtn != null) {
if (reqOpt.getNonceOccurrence() == TripleState.FORBIDDEN) {
LOG.warn("nonce forbidden, but is present in the request");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
int len = nonceExtn.getExtnValueLength();
int min = reqOpt.getNonceMinLen();
int max = reqOpt.getNonceMaxLen();
if (len < min || len > max) {
LOG.warn("length of nonce {} not within [{},{}]", len, min, max);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
repControl.canCacheInfo = false;
respExtensions.add(nonceExtn);
} else {
if (reqOpt.getNonceOccurrence() == TripleState.REQUIRED) {
LOG.warn("nonce required, but is not present in the request");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
}
ConcurrentContentSigner concurrentSigner = null;
if (responder.getResponderOption().getMode() != OcspMode.RFC2560) {
ExtendedExtension extn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_PREFSIGALGS);
if (extn != null) {
ASN1InputStream asn1Stream = new ASN1InputStream(extn.getExtnValueStream());
List<AlgorithmIdentifier> prefSigAlgs;
try {
ASN1Sequence seq = ASN1Sequence.getInstance(asn1Stream.readObject());
final int size = seq.size();
prefSigAlgs = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
prefSigAlgs.add(AlgorithmIdentifier.getInstance(seq.getObjectAt(i)));
}
} finally {
asn1Stream.close();
}
concurrentSigner = signer.getSignerForPreferredSigAlgs(prefSigAlgs);
}
}
if (!reqExtensions.isEmpty()) {
boolean flag = false;
for (ExtendedExtension m : reqExtensions) {
if (m.isCritical()) {
flag = true;
break;
}
}
if (flag) {
if (LOG.isWarnEnabled()) {
List<OID> oids = new LinkedList<>();
for (ExtendedExtension m : reqExtensions) {
if (m.isCritical()) {
oids.add(m.getExtnType());
}
}
LOG.warn("could not process critial request extensions: {}", oids);
}
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
}
if (concurrentSigner == null) {
concurrentSigner = signer.getFirstSigner();
}
AlgorithmCode cacheDbSigAlgCode = null;
BigInteger cacheDbSerialNumber = null;
Integer cacheDbIssuerId = null;
boolean canCacheDb = (requestsSize == 1) && (responseCacher != null) && (nonceExtn == null) && responseCacher.isOnService();
if (canCacheDb) {
// try to find the cached response
CertID certId = requestList.get(0);
HashAlgo reqHashAlgo = certId.getIssuer().hashAlgorithm();
if (!reqOpt.allows(reqHashAlgo)) {
LOG.warn("CertID.hashAlgorithm {} not allowed", reqHashAlgo != null ? reqHashAlgo : certId.getIssuer().hashAlgorithmOID());
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
cacheDbSigAlgCode = concurrentSigner.getAlgorithmCode();
cacheDbIssuerId = responseCacher.getIssuerId(certId.getIssuer());
cacheDbSerialNumber = certId.getSerialNumber();
if (cacheDbIssuerId != null) {
OcspRespWithCacheInfo cachedResp = responseCacher.getOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, cacheDbSigAlgCode);
if (cachedResp != null) {
return cachedResp;
}
} else if (master) {
// store the issuer certificate in cache database.
X509Certificate issuerCert = null;
for (OcspStore store : responder.getStores()) {
issuerCert = store.getIssuerCert(certId.getIssuer());
if (issuerCert != null) {
break;
}
}
if (issuerCert != null) {
cacheDbIssuerId = responseCacher.storeIssuer(issuerCert);
}
}
if (cacheDbIssuerId == null) {
canCacheDb = false;
}
}
ResponderID responderId = signer.getResponderId(repOpt.isResponderIdByName());
OCSPRespBuilder builder = new OCSPRespBuilder(responderId);
for (int i = 0; i < requestsSize; i++) {
OcspRespWithCacheInfo failureOcspResp = processCertReq(requestList.get(i), builder, responder, reqOpt, repOpt, repControl);
if (failureOcspResp != null) {
return failureOcspResp;
}
}
if (repControl.includeExtendedRevokeExtension) {
respExtensions.add(extension_pkix_ocsp_extendedRevoke);
}
if (!respExtensions.isEmpty()) {
Extensions extns = new Extensions(respExtensions);
builder.setResponseExtensions(extns);
}
TaggedCertSequence certsInResp;
EmbedCertsMode certsMode = repOpt.getEmbedCertsMode();
if (certsMode == EmbedCertsMode.SIGNER) {
certsInResp = signer.getSequenceOfCert();
} else if (certsMode == EmbedCertsMode.NONE) {
certsInResp = null;
} else {
// certsMode == EmbedCertsMode.SIGNER_AND_CA
certsInResp = signer.getSequenceOfCertChain();
}
byte[] encodeOcspResponse;
try {
encodeOcspResponse = builder.buildOCSPResponse(concurrentSigner, certsInResp, new Date());
} catch (NoIdleSignerException ex) {
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.tryLater);
} catch (OCSPException ex) {
LogUtil.error(LOG, ex, "answer() basicOcspBuilder.build");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
}
// cache response in database
if (canCacheDb && repControl.canCacheInfo) {
// Don't cache the response with status UNKNOWN, since this may result in DDoS
// of storage
responseCacher.storeOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, repControl.cacheThisUpdate, repControl.cacheNextUpdate, cacheDbSigAlgCode, encodeOcspResponse);
}
if (viaGet && repControl.canCacheInfo) {
ResponseCacheInfo cacheInfo = new ResponseCacheInfo(repControl.cacheThisUpdate);
if (repControl.cacheNextUpdate != Long.MAX_VALUE) {
cacheInfo.setNextUpdate(repControl.cacheNextUpdate);
}
return new OcspRespWithCacheInfo(encodeOcspResponse, cacheInfo);
} else {
return new OcspRespWithCacheInfo(encodeOcspResponse, null);
}
} catch (Throwable th) {
LogUtil.error(LOG, th);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
}
}
use of org.xipki.security.ConcurrentContentSigner in project xipki by xipki.
the class CaClientImpl method init0.
private synchronized void init0(boolean force) throws CaClientException {
if (confFile == null) {
throw new IllegalStateException("confFile is not set");
}
if (securityFactory == null) {
throw new IllegalStateException("securityFactory is not set");
}
if (!force && initialized.get()) {
return;
}
// reset
this.casMap.clear();
this.autoConfCaNames.clear();
if (this.scheduledThreadPoolExecutor != null) {
this.scheduledThreadPoolExecutor.shutdownNow();
}
this.initialized.set(false);
LOG.info("initializing ...");
File configFile = new File(IoUtil.expandFilepath(confFile));
if (!configFile.exists()) {
throw new CaClientException("could not find configuration file " + confFile);
}
CAClientType config;
try {
config = parse(new FileInputStream(configFile));
} catch (FileNotFoundException ex) {
throw new CaClientException("could not read file " + confFile);
}
int numActiveCAs = 0;
for (CAType caType : config.getCAs().getCA()) {
if (!caType.isEnabled()) {
LOG.info("CA " + caType.getName() + " is disabled");
continue;
}
numActiveCAs++;
}
if (numActiveCAs == 0) {
LOG.warn("no active CA is configured");
}
// responders
Map<String, CmpResponder> responders = new HashMap<>();
for (ResponderType m : config.getResponders().getResponder()) {
X509Certificate cert;
try {
cert = X509Util.parseCert(readData(m.getCert()));
} catch (CertificateException | IOException ex) {
LogUtil.error(LOG, ex, "could not configure responder " + m.getName());
throw new CaClientException(ex.getMessage(), ex);
}
Set<String> algoNames = new HashSet<>();
for (String algo : m.getSignatureAlgos().getSignatureAlgo()) {
algoNames.add(algo);
}
AlgorithmValidator sigAlgoValidator;
try {
sigAlgoValidator = new CollectionAlgorithmValidator(algoNames);
} catch (NoSuchAlgorithmException ex) {
throw new CaClientException(ex.getMessage());
}
responders.put(m.getName(), new CmpResponder(cert, sigAlgoValidator));
}
// CA
Set<CaConf> cas = new HashSet<>();
for (CAType caType : config.getCAs().getCA()) {
if (!caType.isEnabled()) {
continue;
}
String caName = caType.getName();
try {
// responder
CmpResponder responder = responders.get(caType.getResponder());
if (responder == null) {
throw new CaClientException("no responder named " + caType.getResponder() + " is configured");
}
CaConf ca = new CaConf(caName, caType.getUrl(), caType.getHealthUrl(), caType.getRequestor(), responder);
// CA cert
if (caType.getCaCert().getAutoconf() != null) {
ca.setCertAutoconf(true);
} else {
ca.setCertAutoconf(false);
ca.setCert(X509Util.parseCert(readData(caType.getCaCert().getCert())));
}
// CMPControl
CmpControlType cmpCtrlType = caType.getCmpControl();
if (cmpCtrlType.getAutoconf() != null) {
ca.setCmpControlAutoconf(true);
} else {
ca.setCmpControlAutoconf(false);
Boolean tmpBo = cmpCtrlType.isRrAkiRequired();
ClientCmpControl control = new ClientCmpControl((tmpBo == null) ? false : tmpBo.booleanValue());
ca.setCmpControl(control);
}
// Certprofiles
CertprofilesType certprofilesType = caType.getCertprofiles();
if (certprofilesType.getAutoconf() != null) {
ca.setCertprofilesAutoconf(true);
} else {
ca.setCertprofilesAutoconf(false);
List<CertprofileType> types = certprofilesType.getCertprofile();
Set<CertprofileInfo> profiles = new HashSet<>(types.size());
for (CertprofileType m : types) {
String conf = null;
if (m.getConf() != null) {
conf = m.getConf().getValue();
if (conf == null) {
conf = new String(IoUtil.read(m.getConf().getFile()));
}
}
CertprofileInfo profile = new CertprofileInfo(m.getName(), m.getType(), conf);
profiles.add(profile);
}
ca.setCertprofiles(profiles);
}
cas.add(ca);
if (ca.isCertAutoconf() || ca.isCertprofilesAutoconf() || ca.isCmpControlAutoconf()) {
autoConfCaNames.add(caName);
}
} catch (IOException | CertificateException ex) {
LogUtil.error(LOG, ex, "could not configure CA " + caName);
throw new CaClientException(ex.getMessage(), ex);
}
}
// requestors
Map<String, X509Certificate> requestorCerts = new HashMap<>();
Map<String, ConcurrentContentSigner> requestorSigners = new HashMap<>();
Map<String, Boolean> requestorSignRequests = new HashMap<>();
for (RequestorType requestorConf : config.getRequestors().getRequestor()) {
String name = requestorConf.getName();
requestorSignRequests.put(name, requestorConf.isSignRequest());
X509Certificate requestorCert = null;
if (requestorConf.getCert() != null) {
try {
requestorCert = X509Util.parseCert(readData(requestorConf.getCert()));
requestorCerts.put(name, requestorCert);
} catch (Exception ex) {
throw new CaClientException(ex.getMessage(), ex);
}
}
if (requestorConf.getSignerType() != null) {
try {
SignerConf signerConf = new SignerConf(requestorConf.getSignerConf());
ConcurrentContentSigner requestorSigner = securityFactory.createSigner(requestorConf.getSignerType(), signerConf, requestorCert);
requestorSigners.put(name, requestorSigner);
} catch (ObjectCreationException ex) {
throw new CaClientException(ex.getMessage(), ex);
}
} else {
if (requestorConf.isSignRequest()) {
throw new CaClientException("signer of requestor must be configured");
} else if (requestorCert == null) {
throw new CaClientException("at least one of certificate and signer of requestor must be configured");
}
}
}
for (CaConf ca : cas) {
if (this.casMap.containsKey(ca.getName())) {
throw new CaClientException("duplicate CAs with the same name " + ca.getName());
}
String requestorName = ca.getRequestorName();
X509CmpRequestor cmpRequestor;
if (requestorSigners.containsKey(requestorName)) {
cmpRequestor = new DfltHttpX509CmpRequestor(requestorSigners.get(requestorName), ca.getResponder(), ca.getUrl(), securityFactory);
cmpRequestor.setSignRequest(requestorSignRequests.get(requestorName));
} else if (requestorCerts.containsKey(requestorName)) {
cmpRequestor = new DfltHttpX509CmpRequestor(requestorCerts.get(requestorName), ca.getResponder(), ca.getUrl(), securityFactory);
} else {
throw new CaClientException("could not find requestor named " + requestorName + " for CA " + ca.getName());
}
ca.setRequestor(cmpRequestor);
this.casMap.put(ca.getName(), ca);
}
if (!autoConfCaNames.isEmpty()) {
Integer caInfoUpdateInterval = config.getCAs().getCAInfoUpdateInterval();
if (caInfoUpdateInterval == null) {
caInfoUpdateInterval = 10;
} else if (caInfoUpdateInterval <= 0) {
caInfoUpdateInterval = 0;
} else if (caInfoUpdateInterval < 5) {
caInfoUpdateInterval = 5;
}
LOG.info("configuring CAs {}", autoConfCaNames);
Set<String> failedCaNames = autoConfCas(autoConfCaNames);
// try to re-configure the failed CAs
if (CollectionUtil.isNonEmpty(failedCaNames)) {
for (int i = 0; i < 3; i++) {
LOG.info("configuring ({}-th retry) CAs {}", i + 1, failedCaNames);
failedCaNames = autoConfCas(failedCaNames);
if (CollectionUtil.isEmpty(failedCaNames)) {
break;
}
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
LOG.warn("interrupted", ex);
}
}
}
if (CollectionUtil.isNonEmpty(failedCaNames)) {
throw new CaClientException("could not configure following CAs " + failedCaNames);
}
if (caInfoUpdateInterval > 0) {
scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
scheduledThreadPoolExecutor.scheduleAtFixedRate(new ClientConfigUpdater(), caInfoUpdateInterval, caInfoUpdateInterval, TimeUnit.MINUTES);
}
}
initialized.set(true);
LOG.info("initialized");
}
use of org.xipki.security.ConcurrentContentSigner in project xipki by xipki.
the class X509Ca method generateCrl0.
private X509CRL generateCrl0(boolean deltaCrl, Date thisUpdate, Date nextUpdate, AuditEvent event, String msgId) throws OperationException {
X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
if (crlSigner == null) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "CRL generation is not allowed");
}
LOG.info(" START generateCrl: ca={}, deltaCRL={}, nextUpdate={}", caIdent, deltaCrl, nextUpdate);
event.addEventData(CaAuditConstants.NAME_crlType, deltaCrl ? "DELTA_CRL" : "FULL_CRL");
if (nextUpdate == null) {
event.addEventData(CaAuditConstants.NAME_nextUpdate, "null");
} else {
event.addEventData(CaAuditConstants.NAME_nextUpdate, DateUtil.toUtcTimeyyyyMMddhhmmss(nextUpdate));
if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) {
// less than 10 minutes
throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close");
}
}
CrlControl crlControl = crlSigner.getCrlControl();
boolean successful = false;
try {
ConcurrentContentSigner tmpCrlSigner = crlSigner.getSigner();
CrlControl control = crlSigner.getCrlControl();
boolean directCrl;
X500Name crlIssuer;
if (tmpCrlSigner == null) {
directCrl = true;
crlIssuer = caInfo.getPublicCaInfo().getX500Subject();
} else {
directCrl = false;
crlIssuer = X500Name.getInstance(tmpCrlSigner.getCertificate().getSubjectX500Principal().getEncoded());
}
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
if (nextUpdate != null) {
crlBuilder.setNextUpdate(nextUpdate);
}
final int numEntries = 100;
Date notExpireAt;
if (control.isIncludeExpiredCerts()) {
notExpireAt = new Date(0);
} else {
// 10 minutes buffer
notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
}
long startId = 1;
// we have to cache the serial entries to sort them
List<CertRevInfoWithSerial> allRevInfos = new LinkedList<>();
List<CertRevInfoWithSerial> revInfos;
do {
if (deltaCrl) {
revInfos = certstore.getCertsForDeltaCrl(caIdent, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
} else {
revInfos = certstore.getRevokedCerts(caIdent, notExpireAt, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
}
allRevInfos.addAll(revInfos);
long maxId = 1;
for (CertRevInfoWithSerial revInfo : revInfos) {
if (revInfo.getId() > maxId) {
maxId = revInfo.getId();
}
}
// end for
startId = maxId + 1;
} while (// end do
revInfos.size() >= numEntries);
if (revInfos != null) {
// free the memory
revInfos.clear();
}
// sort the list by SerialNumber ASC
Collections.sort(allRevInfos);
boolean isFirstCrlEntry = true;
for (CertRevInfoWithSerial revInfo : allRevInfos) {
CrlReason reason = revInfo.getReason();
if (crlControl.isExcludeReason() && reason != CrlReason.REMOVE_FROM_CRL) {
reason = CrlReason.UNSPECIFIED;
}
Date revocationTime = revInfo.getRevocationTime();
Date invalidityTime = revInfo.getInvalidityTime();
switch(crlControl.getInvalidityDateMode()) {
case FORBIDDEN:
invalidityTime = null;
break;
case OPTIONAL:
break;
case REQUIRED:
if (invalidityTime == null) {
invalidityTime = revocationTime;
}
break;
default:
throw new RuntimeException("unknown TripleState: " + crlControl.getInvalidityDateMode());
}
BigInteger serial = revInfo.getSerial();
LOG.debug("added cert ca={} serial={} to CRL", caIdent, serial);
if (directCrl || !isFirstCrlEntry) {
if (invalidityTime != null) {
crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode(), invalidityTime);
} else {
crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode());
}
continue;
}
List<Extension> extensions = new ArrayList<>(3);
if (reason != CrlReason.UNSPECIFIED) {
Extension ext = createReasonExtension(reason.getCode());
extensions.add(ext);
}
if (invalidityTime != null) {
Extension ext = createInvalidityDateExtension(invalidityTime);
extensions.add(ext);
}
Extension ext = createCertificateIssuerExtension(caInfo.getPublicCaInfo().getX500Subject());
extensions.add(ext);
crlBuilder.addCRLEntry(serial, revocationTime, new Extensions(extensions.toArray(new Extension[0])));
isFirstCrlEntry = false;
}
// free the memory
allRevInfos.clear();
BigInteger crlNumber = caInfo.nextCrlNumber();
event.addEventData(CaAuditConstants.NAME_crlNumber, crlNumber);
boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts();
boolean onlyCaCerts = crlControl.isOnlyContainsCaCerts();
if (onlyUserCerts && onlyCaCerts) {
throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true");
}
try {
// AuthorityKeyIdentifier
byte[] akiValues = directCrl ? caInfo.getPublicCaInfo().getSubjectKeyIdentifer() : crlSigner.getSubjectKeyIdentifier();
AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues);
crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
// add extension CRL Number
crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber));
// IssuingDistributionPoint
if (onlyUserCerts || onlyCaCerts || !directCrl) {
IssuingDistributionPoint idp = new IssuingDistributionPoint(// distributionPoint,
(DistributionPointName) null, // onlyContainsUserCerts,
onlyUserCerts, // onlyContainsCACerts,
onlyCaCerts, // onlySomeReasons,
(ReasonFlags) null, // indirectCRL,
!directCrl, // onlyContainsAttributeCerts
false);
crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
}
// freshestCRL
List<String> deltaCrlUris = getCaInfo().getPublicCaInfo().getDeltaCrlUris();
if (control.getDeltaCrlIntervals() > 0 && CollectionUtil.isNonEmpty(deltaCrlUris)) {
CRLDistPoint cdp = CaUtil.createCrlDistributionPoints(deltaCrlUris, caInfo.getPublicCaInfo().getX500Subject(), crlIssuer);
crlBuilder.addExtension(Extension.freshestCRL, false, cdp);
}
} catch (CertIOException ex) {
LogUtil.error(LOG, ex, "crlBuilder.addExtension");
throw new OperationException(ErrorCode.INVALID_EXTENSION, ex);
}
addXipkiCertset(crlBuilder, deltaCrl, control, notExpireAt, onlyCaCerts, onlyUserCerts);
ConcurrentContentSigner concurrentSigner = (tmpCrlSigner == null) ? caInfo.getSigner(null) : tmpCrlSigner;
ConcurrentBagEntrySigner signer0;
try {
signer0 = concurrentSigner.borrowSigner();
} catch (NoIdleSignerException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + ex.getMessage());
}
X509CRLHolder crlHolder;
try {
crlHolder = crlBuilder.build(signer0.value());
} finally {
concurrentSigner.requiteSigner(signer0);
}
try {
X509CRL crl = X509Util.toX509Crl(crlHolder.toASN1Structure());
caInfo.getCaEntry().setNextCrlNumber(crlNumber.longValue() + 1);
caManager.commitNextCrlNo(caIdent, caInfo.getCaEntry().getNextCrlNumber());
publishCrl(crl);
successful = true;
LOG.info("SUCCESSFUL generateCrl: ca={}, crlNumber={}, thisUpdate={}", caIdent, crlNumber, crl.getThisUpdate());
if (!deltaCrl) {
// clean up the CRL
cleanupCrlsWithoutException(msgId);
}
return crl;
} catch (CRLException | CertificateException ex) {
throw new OperationException(ErrorCode.CRL_FAILURE, ex);
}
} finally {
if (!successful) {
LOG.info(" FAILED generateCrl: ca={}", caIdent);
}
}
}
use of org.xipki.security.ConcurrentContentSigner in project xipki by xipki.
the class X509Ca method healthCheck.
// method removeExpirtedCerts
public HealthCheckResult healthCheck() {
HealthCheckResult result = new HealthCheckResult("X509CA");
boolean healthy = true;
ConcurrentContentSigner signer = caInfo.getSigner(null);
if (signer != null) {
boolean caSignerHealthy = signer.isHealthy();
healthy &= caSignerHealthy;
HealthCheckResult signerHealth = new HealthCheckResult("Signer");
signerHealth.setHealthy(caSignerHealthy);
result.addChildCheck(signerHealth);
}
boolean databaseHealthy = certstore.isHealthy();
healthy &= databaseHealthy;
HealthCheckResult databaseHealth = new HealthCheckResult("Database");
databaseHealth.setHealthy(databaseHealthy);
result.addChildCheck(databaseHealth);
X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
if (crlSigner != null && crlSigner.getSigner() != null) {
boolean crlSignerHealthy = crlSigner.getSigner().isHealthy();
healthy &= crlSignerHealthy;
HealthCheckResult crlSignerHealth = new HealthCheckResult("CRLSigner");
crlSignerHealth.setHealthy(crlSignerHealthy);
result.addChildCheck(crlSignerHealth);
}
for (IdentifiedX509CertPublisher publisher : publishers()) {
boolean ph = publisher.isHealthy();
healthy &= ph;
HealthCheckResult publisherHealth = new HealthCheckResult("Publisher");
publisherHealth.setHealthy(publisher.isHealthy());
result.addChildCheck(publisherHealth);
}
result.setHealthy(healthy);
return result;
}
Aggregations