use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.
the class PossibleActionsRuleEngineTest method createTestToken.
/**
* Create a specific token-key combination
*/
private TokenInfo createTestToken(boolean tokenSaved, boolean tokenReadOnly, boolean tokenActive, boolean keyNotSupported) {
CertificateInfo cert = new CertificateTestUtils.CertificateInfoBuilder().savedToConfiguration(tokenSaved).build();
String tokenId;
KeyUsageInfo usage;
if (keyNotSupported) {
tokenId = PossibleActionsRuleEngine.SOFTWARE_TOKEN_ID + 1;
usage = KeyUsageInfo.AUTHENTICATION;
} else {
tokenId = PossibleActionsRuleEngine.SOFTWARE_TOKEN_ID;
usage = KeyUsageInfo.AUTHENTICATION;
}
KeyInfo key = new TokenTestUtils.KeyInfoBuilder().keyUsageInfo(usage).cert(cert).build();
TokenInfo tokenInfo = new TokenTestUtils.TokenInfoBuilder().readOnly(tokenReadOnly).active(tokenActive).key(key).id(tokenId).build();
return tokenInfo;
}
use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.
the class SignerCLI method generateCertRequest.
/**
* Generate certificate request.
*
* @param keyId key id
* @param memberId member id
* @param usage usage
* @param subjectName subject name
* @param format request format
* @throws Exception if an error occurs
*/
@Command(description = "Generate certificate request")
public void generateCertRequest(@Param(name = "keyId", description = "Key ID") String keyId, @Param(name = "memberId", description = "Member identifier") ClientId memberId, @Param(name = "usage", description = "Key usage (a - auth, s - sign)") String usage, @Param(name = "subjectName", description = "Subject name") String subjectName, @Param(name = "format", description = "Format of request (der/pem)") String format) throws Exception {
KeyUsageInfo keyUsage = "a".equals(usage) ? KeyUsageInfo.AUTHENTICATION : KeyUsageInfo.SIGNING;
CertificateRequestFormat requestFormat = format.equalsIgnoreCase("der") ? CertificateRequestFormat.DER : CertificateRequestFormat.PEM;
Map<String, Object> logData = new LinkedHashMap<>();
logData.put(KEY_ID_PARAM, keyId);
logData.put(CLIENT_IDENTIFIER_PARAM, memberId);
logData.put(KEY_USAGE_PARAM, keyUsage.name());
logData.put(SUBJECT_NAME_PARAM, subjectName);
logData.put(CSR_FORMAT_PARAM, requestFormat.name());
GenerateCertRequestResponse response;
try {
GenerateCertRequest request = new GenerateCertRequest(keyId, memberId, keyUsage, subjectName, requestFormat);
response = SignerClient.execute(request);
AuditLogger.log(GENERATE_A_CERT_REQUEST_EVENT, XROAD_USER, logData);
} catch (Exception e) {
AuditLogger.log(GENERATE_A_CERT_REQUEST_EVENT, XROAD_USER, e.getMessage(), logData);
throw e;
}
bytesToFile(keyId + ".csr", response.getCertRequest());
}
use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.
the class CertificateAuthoritiesApiController method getSubjectFieldDescriptions.
// see reason below
@SuppressWarnings("squid:S3655")
@Override
@PreAuthorize("(hasAuthority('GENERATE_AUTH_CERT_REQ') and " + " (#keyUsageType == T(org.niis.xroad.securityserver.restapi.openapi.model.KeyUsageType).AUTHENTICATION))" + " or (hasAuthority('GENERATE_SIGN_CERT_REQ') and " + "(#keyUsageType == T(org.niis.xroad.securityserver.restapi.openapi.model.KeyUsageType).SIGNING))")
public ResponseEntity<Set<CsrSubjectFieldDescription>> getSubjectFieldDescriptions(String caName, KeyUsageType keyUsageType, String keyId, String encodedMemberId, Boolean isNewMember) {
// squid:S3655 throwing NoSuchElementException if there is no value present is
// fine since keyUsageInfo is mandatory parameter
KeyUsageInfo keyUsageInfo = KeyUsageTypeMapping.map(keyUsageType).get();
// memberId is mandatory for sign csrs
if (keyUsageInfo == KeyUsageInfo.SIGNING) {
if (StringUtils.isBlank(encodedMemberId)) {
throw new BadRequestException("memberId is mandatory for sign csrs");
}
}
try {
if (!StringUtils.isBlank(keyId)) {
// validate that key.usage matches keyUsageType
KeyInfo keyInfo = keyService.getKey(keyId);
if (keyInfo.getUsage() != null) {
if (keyInfo.getUsage() != keyUsageInfo) {
throw new BadRequestException("key is for different usage", new ErrorDeviation("wrong_key_usage"));
}
}
}
ClientId memberId = null;
if (!StringUtils.isBlank(encodedMemberId)) {
memberId = clientConverter.convertId(encodedMemberId);
}
CertificateProfileInfo profileInfo;
profileInfo = certificateAuthorityService.getCertificateProfile(caName, keyUsageInfo, memberId, isNewMember);
Set<CsrSubjectFieldDescription> converted = subjectConverter.convert(profileInfo.getSubjectFields());
return new ResponseEntity<>(converted, HttpStatus.OK);
} catch (WrongKeyUsageException | KeyNotFoundException | ClientNotFoundException e) {
throw new BadRequestException(e);
} catch (CertificateAuthorityNotFoundException e) {
throw new ResourceNotFoundException(e);
} catch (CertificateProfileInstantiationException e) {
throw new InternalServerErrorException(e);
}
}
use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.
the class KeysApiController method generateCsr.
// squid: see reason below. checkstyle: for readability
@SuppressWarnings({ "squid:S3655", "checkstyle:LineLength" })
@Override
@PreAuthorize("(hasAuthority('GENERATE_AUTH_CERT_REQ') and " + "#csrGenerate.keyUsageType == T(org.niis.xroad.securityserver.restapi.openapi.model.KeyUsageType).AUTHENTICATION)" + " or (hasAuthority('GENERATE_SIGN_CERT_REQ') and " + "#csrGenerate.keyUsageType == T(org.niis.xroad.securityserver.restapi.openapi.model.KeyUsageType).SIGNING)")
@AuditEventMethod(event = RestApiAuditEvent.GENERATE_CSR)
public ResponseEntity<Resource> generateCsr(String keyId, CsrGenerate csrGenerate) {
// squid:S3655 throwing NoSuchElementException if there is no value present is
// fine since keyUsageInfo is mandatory parameter
KeyUsageInfo keyUsageInfo = KeyUsageTypeMapping.map(csrGenerate.getKeyUsageType()).get();
ClientId memberId = null;
if (KeyUsageInfo.SIGNING == keyUsageInfo) {
// memberId not used for authentication csrs
memberId = clientConverter.convertId(csrGenerate.getMemberId());
}
// squid:S3655 throwing NoSuchElementException if there is no value present is
// fine since csr format is mandatory parameter
CertificateRequestFormat csrFormat = CsrFormatMapping.map(csrGenerate.getCsrFormat()).get();
byte[] csr;
try {
csr = tokenCertificateService.generateCertRequest(keyId, memberId, keyUsageInfo, csrGenerate.getCaName(), csrGenerate.getSubjectFieldValues(), csrFormat).getCertRequest();
} catch (WrongKeyUsageException | DnFieldHelper.InvalidDnParameterException | ClientNotFoundException | CertificateAuthorityNotFoundException e) {
throw new BadRequestException(e);
} catch (KeyNotFoundException e) {
throw new ResourceNotFoundException(e);
} catch (ActionNotPossibleException e) {
throw new ConflictException(e);
}
String filename = csrFilenameCreator.createCsrFilename(keyUsageInfo, csrFormat, memberId, serverConfService.getSecurityServerId());
return ControllerUtil.createAttachmentResourceResponse(csr, filename);
}
use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.
the class TokenCertificateService method importCertificate.
/**
* Import a cert that is found from a token by it's bytes.
* Adds audit log properties for
* - clientId (if sign cert),
* - cert hash and cert hash algo
* - key usage
* @param certificateBytes
* @param isFromToken whether the cert was read from a token or not
* @return CertificateType
* @throws GlobalConfOutdatedException
* @throws KeyNotFoundException
* @throws InvalidCertificateException other general import failure
* @throws CertificateAlreadyExistsException
* @throws WrongCertificateUsageException
* @throws AuthCertificateNotSupportedException if trying to import an auth cert from a token
*/
private CertificateInfo importCertificate(byte[] certificateBytes, boolean isFromToken) throws GlobalConfOutdatedException, KeyNotFoundException, InvalidCertificateException, CertificateAlreadyExistsException, WrongCertificateUsageException, CsrNotFoundException, AuthCertificateNotSupportedException, ClientNotFoundException {
globalConfService.verifyGlobalConfValidity();
X509Certificate x509Certificate = convertToX509Certificate(certificateBytes);
CertificateInfo certificateInfo = null;
KeyUsageInfo keyUsageInfo = null;
try {
String certificateState;
ClientId clientId = null;
boolean isAuthCert = CertUtils.isAuthCert(x509Certificate);
if (isAuthCert) {
keyUsageInfo = KeyUsageInfo.AUTHENTICATION;
securityHelper.verifyAuthority(IMPORT_AUTH_CERT);
if (isFromToken) {
throw new AuthCertificateNotSupportedException("auth cert cannot be imported from a token");
}
certificateState = CertificateInfo.STATUS_SAVED;
} else {
keyUsageInfo = KeyUsageInfo.SIGNING;
securityHelper.verifyAuthority(IMPORT_SIGN_CERT);
String xroadInstance = globalConfFacade.getInstanceIdentifier();
clientId = getClientIdForSigningCert(xroadInstance, x509Certificate);
auditDataHelper.put(clientId);
boolean clientExists = clientRepository.clientExists(clientId, true);
if (!clientExists) {
throw new ClientNotFoundException("client " + clientId.toShortString() + " " + NOT_FOUND, FormatUtils.xRoadIdToEncodedId(clientId));
}
certificateState = CertificateInfo.STATUS_REGISTERED;
}
byte[] certBytes = x509Certificate.getEncoded();
String hash = CryptoUtils.calculateCertHexHash(certBytes);
auditDataHelper.putCertificateHash(hash);
signerProxyFacade.importCert(certBytes, certificateState, clientId);
certificateInfo = getCertificateInfo(hash);
} catch (ClientNotFoundException | AccessDeniedException | AuthCertificateNotSupportedException e) {
throw e;
} catch (CodedException e) {
translateCodedExceptions(e);
} catch (Exception e) {
// something went really wrong
throw new RuntimeException("error importing certificate", e);
}
auditDataHelper.put(RestApiAuditProperty.KEY_USAGE, keyUsageInfo);
return certificateInfo;
}
Aggregations