Search in sources :

Example 1 with KeyUsageInfo

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;
}
Also used : KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) TokenTestUtils(org.niis.xroad.securityserver.restapi.util.TokenTestUtils) TokenInfo(ee.ria.xroad.signer.protocol.dto.TokenInfo) KeyUsageInfo(ee.ria.xroad.signer.protocol.dto.KeyUsageInfo)

Example 2 with KeyUsageInfo

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());
}
Also used : GenerateCertRequestResponse(ee.ria.xroad.signer.protocol.message.GenerateCertRequestResponse) CertificateRequestFormat(ee.ria.xroad.signer.protocol.message.CertificateRequestFormat) GenerateCertRequest(ee.ria.xroad.signer.protocol.message.GenerateCertRequest) KeyUsageInfo(ee.ria.xroad.signer.protocol.dto.KeyUsageInfo) IOException(java.io.IOException) CLIException(asg.cliche.CLIException) LinkedHashMap(java.util.LinkedHashMap) Command(asg.cliche.Command)

Example 3 with KeyUsageInfo

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);
    }
}
Also used : ClientNotFoundException(org.niis.xroad.securityserver.restapi.service.ClientNotFoundException) CertificateAuthorityNotFoundException(org.niis.xroad.securityserver.restapi.service.CertificateAuthorityNotFoundException) CertificateProfileInfo(ee.ria.xroad.common.certificateprofile.CertificateProfileInfo) ErrorDeviation(org.niis.xroad.restapi.exceptions.ErrorDeviation) ResponseEntity(org.springframework.http.ResponseEntity) CertificateProfileInstantiationException(org.niis.xroad.securityserver.restapi.service.CertificateProfileInstantiationException) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) WrongKeyUsageException(org.niis.xroad.securityserver.restapi.service.WrongKeyUsageException) BadRequestException(org.niis.xroad.restapi.openapi.BadRequestException) ClientId(ee.ria.xroad.common.identifier.ClientId) CsrSubjectFieldDescription(org.niis.xroad.securityserver.restapi.openapi.model.CsrSubjectFieldDescription) ResourceNotFoundException(org.niis.xroad.restapi.openapi.ResourceNotFoundException) KeyUsageInfo(ee.ria.xroad.signer.protocol.dto.KeyUsageInfo) KeyNotFoundException(org.niis.xroad.securityserver.restapi.service.KeyNotFoundException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 4 with KeyUsageInfo

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);
}
Also used : ClientNotFoundException(org.niis.xroad.securityserver.restapi.service.ClientNotFoundException) ActionNotPossibleException(org.niis.xroad.securityserver.restapi.service.ActionNotPossibleException) CertificateAuthorityNotFoundException(org.niis.xroad.securityserver.restapi.service.CertificateAuthorityNotFoundException) CertificateRequestFormat(ee.ria.xroad.signer.protocol.message.CertificateRequestFormat) WrongKeyUsageException(org.niis.xroad.securityserver.restapi.service.WrongKeyUsageException) ClientId(ee.ria.xroad.common.identifier.ClientId) BadRequestException(org.niis.xroad.restapi.openapi.BadRequestException) ResourceNotFoundException(org.niis.xroad.restapi.openapi.ResourceNotFoundException) KeyUsageInfo(ee.ria.xroad.signer.protocol.dto.KeyUsageInfo) KeyNotFoundException(org.niis.xroad.securityserver.restapi.service.KeyNotFoundException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) AuditEventMethod(org.niis.xroad.restapi.config.audit.AuditEventMethod)

Example 5 with KeyUsageInfo

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;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) X509Certificate(java.security.cert.X509Certificate) InternalServerErrorException(org.niis.xroad.securityserver.restapi.openapi.InternalServerErrorException) SignerNotReachableException(org.niis.xroad.restapi.service.SignerNotReachableException) ServiceException(org.niis.xroad.restapi.service.ServiceException) DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) CodedException(ee.ria.xroad.common.CodedException) DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) CodedException(ee.ria.xroad.common.CodedException) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) ClientId(ee.ria.xroad.common.identifier.ClientId) KeyUsageInfo(ee.ria.xroad.signer.protocol.dto.KeyUsageInfo)

Aggregations

KeyUsageInfo (ee.ria.xroad.signer.protocol.dto.KeyUsageInfo)13 ClientId (ee.ria.xroad.common.identifier.ClientId)8 CertificateInfo (ee.ria.xroad.signer.protocol.dto.CertificateInfo)5 KeyInfo (ee.ria.xroad.signer.protocol.dto.KeyInfo)5 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)5 TokenInfo (ee.ria.xroad.signer.protocol.dto.TokenInfo)4 TokenTestUtils (org.niis.xroad.securityserver.restapi.util.TokenTestUtils)4 SecurityServerId (ee.ria.xroad.common.identifier.SecurityServerId)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 Before (org.junit.Before)3 Test (org.junit.Test)3 ResponseEntity (org.springframework.http.ResponseEntity)3 CertificateProfileInfo (ee.ria.xroad.common.certificateprofile.CertificateProfileInfo)2 ApprovedCAInfo (ee.ria.xroad.common.conf.globalconf.ApprovedCAInfo)2 ClientType (ee.ria.xroad.common.conf.serverconf.model.ClientType)2 CertificateRequestFormat (ee.ria.xroad.signer.protocol.message.CertificateRequestFormat)2 X509Certificate (java.security.cert.X509Certificate)2