Search in sources :

Example 1 with CertificateProfileInfo

use of ee.ria.xroad.common.certificateprofile.CertificateProfileInfo in project X-Road by nordic-institute.

the class TokenCertificateService method generateCertRequest.

/**
 * Create a CSR
 * @param keyId
 * @param memberId
 * @param keyUsage
 * @param caName
 * @param subjectFieldValues user-submitted parameters for subject DN
 * @param format
 * @return GeneratedCertRequestInfo containing details and bytes of the cert request
 * @throws CertificateAuthorityNotFoundException if ca authority with name {@code caName} does not exist
 * @throws ClientNotFoundException if client with {@code memberId} id was not found
 * @throws KeyNotFoundException if key with {@code keyId} was not found
 * @throws WrongKeyUsageException if keyUsage param did not match the key's usage type
 * @throws DnFieldHelper.InvalidDnParameterException if required dn parameters were missing, or if there
 * were some extra parameters
 * @throws ActionNotPossibleException if generate csr was not possible for this key
 */
public GeneratedCertRequestInfo generateCertRequest(String keyId, ClientId memberId, KeyUsageInfo keyUsage, String caName, Map<String, String> subjectFieldValues, CertificateRequestFormat format) throws CertificateAuthorityNotFoundException, ClientNotFoundException, WrongKeyUsageException, KeyNotFoundException, DnFieldHelper.InvalidDnParameterException, ActionNotPossibleException {
    // validate key and memberId existence
    TokenInfo tokenInfo = tokenService.getTokenForKeyId(keyId);
    auditDataHelper.put(tokenInfo);
    KeyInfo key = keyService.getKey(tokenInfo, keyId);
    auditDataHelper.put(key);
    auditDataHelper.put(RestApiAuditProperty.KEY_USAGE, keyUsage);
    auditDataHelper.put(memberId);
    if (keyUsage == KeyUsageInfo.SIGNING) {
        // validate that the member exists or has a subsystem on this server
        if (!clientService.getLocalClientMemberIds().contains(memberId)) {
            throw new ClientNotFoundException("client with id " + memberId + ", or subsystem for it, " + NOT_FOUND);
        }
    }
    // check that keyUsage is allowed
    if (key.getUsage() != null) {
        if (key.getUsage() != keyUsage) {
            throw new WrongKeyUsageException();
        }
    }
    // validate that generate csr is possible
    if (keyUsage == KeyUsageInfo.SIGNING) {
        possibleActionsRuleEngine.requirePossibleKeyAction(PossibleActionEnum.GENERATE_SIGN_CSR, tokenInfo, key);
    } else {
        possibleActionsRuleEngine.requirePossibleKeyAction(PossibleActionEnum.GENERATE_AUTH_CSR, tokenInfo, key);
    }
    CertificateProfileInfo profile = null;
    try {
        profile = certificateAuthorityService.getCertificateProfile(caName, keyUsage, memberId, false);
    } catch (CertificateProfileInstantiationException e) {
        throw new DeviationAwareRuntimeException(e, e.getErrorDeviation());
    }
    List<DnFieldValue> dnFieldValues = dnFieldHelper.processDnParameters(profile, subjectFieldValues);
    String subjectName = dnFieldHelper.createSubjectName(dnFieldValues);
    auditDataHelper.put(RestApiAuditProperty.SUBJECT_NAME, subjectName);
    auditDataHelper.put(RestApiAuditProperty.CERTIFICATION_SERVICE_NAME, caName);
    auditDataHelper.put(RestApiAuditProperty.CSR_FORMAT, format);
    try {
        return signerProxyFacade.generateCertRequest(keyId, memberId, keyUsage, subjectName, format);
    } catch (CodedException e) {
        throw e;
    } catch (Exception e) {
        throw new SignerNotReachableException("Generate cert request failed", e);
    }
}
Also used : DnFieldValue(ee.ria.xroad.common.certificateprofile.DnFieldValue) DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) CertificateProfileInfo(ee.ria.xroad.common.certificateprofile.CertificateProfileInfo) 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) CodedException(ee.ria.xroad.common.CodedException) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) TokenInfo(ee.ria.xroad.signer.protocol.dto.TokenInfo) SignerNotReachableException(org.niis.xroad.restapi.service.SignerNotReachableException)

Example 2 with CertificateProfileInfo

use of ee.ria.xroad.common.certificateprofile.CertificateProfileInfo 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 3 with CertificateProfileInfo

use of ee.ria.xroad.common.certificateprofile.CertificateProfileInfo in project X-Road by nordic-institute.

the class CertificateAuthoritiesApiControllerTest method setUp.

@Before
public void setUp() throws Exception {
    KeyInfo signKeyInfo = new TokenTestUtils.KeyInfoBuilder().id(GOOD_SIGN_KEY_ID).keyUsageInfo(KeyUsageInfo.SIGNING).build();
    KeyInfo authKeyInfo = new TokenTestUtils.KeyInfoBuilder().id(GOOD_AUTH_KEY_ID).keyUsageInfo(KeyUsageInfo.AUTHENTICATION).build();
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        String keyId = (String) args[0];
        if (keyId.equals(GOOD_AUTH_KEY_ID)) {
            return authKeyInfo;
        } else if (keyId.equals(GOOD_SIGN_KEY_ID)) {
            return signKeyInfo;
        } else {
            throw new KeyNotFoundException("foo");
        }
    }).when(keyService).getKey(any());
    List<ApprovedCaDto> approvedCAInfos = new ArrayList<>();
    approvedCAInfos.add(ApprovedCaDto.builder().name(GENERAL_PURPOSE_CA_NAME).authenticationOnly(false).build());
    when(certificateAuthorityService.getCertificateAuthorities(any())).thenReturn(approvedCAInfos);
    when(certificateAuthorityService.getCertificateProfile(any(), any(), any(), anyBoolean())).thenReturn(new CertificateProfileInfo() {

        @Override
        public DnFieldDescription[] getSubjectFields() {
            return new DnFieldDescription[0];
        }

        @Override
        public X500Principal createSubjectDn(DnFieldValue[] values) {
            return null;
        }

        @Override
        public void validateSubjectField(DnFieldValue field) throws Exception {
        }
    });
}
Also used : DnFieldValue(ee.ria.xroad.common.certificateprofile.DnFieldValue) ApprovedCaDto(org.niis.xroad.securityserver.restapi.dto.ApprovedCaDto) ArrayList(java.util.ArrayList) TokenTestUtils(org.niis.xroad.securityserver.restapi.util.TokenTestUtils) CertificateProfileInfo(ee.ria.xroad.common.certificateprofile.CertificateProfileInfo) AccessDeniedException(org.springframework.security.access.AccessDeniedException) KeyNotFoundException(org.niis.xroad.securityserver.restapi.service.KeyNotFoundException) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) X500Principal(javax.security.auth.x500.X500Principal) KeyNotFoundException(org.niis.xroad.securityserver.restapi.service.KeyNotFoundException) Before(org.junit.Before)

Example 4 with CertificateProfileInfo

use of ee.ria.xroad.common.certificateprofile.CertificateProfileInfo in project X-Road by nordic-institute.

the class CertificateAuthorityServiceTest method getCertificateProfile.

@Test
public void getCertificateProfile() throws Exception {
    ClientType client = new ClientType();
    client.setIdentifier(COMMON_OWNER_ID);
    when(clientRepository.getAllLocalClients()).thenReturn(Collections.singletonList(client));
    // test handling of profile info parameters:
    // private final SecurityServerId serverId;
    // private final ClientId clientId; (sign only)
    // private final String memberName;
    CertificateProfileInfo profile = certificateAuthorityService.getCertificateProfile("fi-not-auth-only", KeyUsageInfo.SIGNING, COMMON_OWNER_ID, false);
    assertTrue(profile instanceof FiVRKSignCertificateProfileInfo);
    assertEquals("FI/SS1/GOV", profile.getSubjectFields()[2].getDefaultValue());
    assertEquals("M1", profile.getSubjectFields()[3].getDefaultValue());
    assertTrue(profile.getSubjectFields()[3].isReadOnly());
    profile = certificateAuthorityService.getCertificateProfile("fi-not-auth-only", KeyUsageInfo.AUTHENTICATION, COMMON_OWNER_ID, false);
    assertTrue(profile instanceof FiVRKAuthCertificateProfileInfo);
    assertEquals("FI/SS1/GOV", profile.getSubjectFields()[2].getDefaultValue());
    assertEquals("", profile.getSubjectFields()[3].getDefaultValue());
    assertFalse(profile.getSubjectFields()[3].isReadOnly());
    profile = certificateAuthorityService.getCertificateProfile("est-auth-only", KeyUsageInfo.AUTHENTICATION, COMMON_OWNER_ID, false);
    assertTrue(profile instanceof AuthCertificateProfileInfo);
    assertEquals(0, profile.getSubjectFields().length);
    // exceptions
    try {
        certificateAuthorityService.getCertificateProfile("est-auth-only", KeyUsageInfo.SIGNING, COMMON_OWNER_ID, false);
        fail("should have thrown exception");
    } catch (WrongKeyUsageException expected) {
    }
    try {
        certificateAuthorityService.getCertificateProfile("this-does-not-exist", KeyUsageInfo.SIGNING, COMMON_OWNER_ID, false);
        fail("should have thrown exception");
    } catch (CertificateAuthorityNotFoundException expected) {
    }
    // cant instantiate
    List<ApprovedCAInfo> approvedCAInfos = new ArrayList<>();
    approvedCAInfos.add(new ApprovedCAInfo("provider-class-does-not-exist", false, "ee.ria.xroad.common.certificateprofile.impl.NonExistentProvider"));
    when(globalConfFacade.getApprovedCAs(any())).thenReturn(approvedCAInfos);
    try {
        certificateAuthorityService.getCertificateProfile("provider-class-does-not-exist", KeyUsageInfo.SIGNING, COMMON_OWNER_ID, false);
        fail("should have thrown exception");
    } catch (CertificateProfileInstantiationException expected) {
    }
}
Also used : ClientType(ee.ria.xroad.common.conf.serverconf.model.ClientType) ApprovedCAInfo(ee.ria.xroad.common.conf.globalconf.ApprovedCAInfo) ArrayList(java.util.ArrayList) AuthCertificateProfileInfo(ee.ria.xroad.common.certificateprofile.AuthCertificateProfileInfo) FiVRKSignCertificateProfileInfo(ee.ria.xroad.common.certificateprofile.impl.FiVRKSignCertificateProfileInfo) CertificateProfileInfo(ee.ria.xroad.common.certificateprofile.CertificateProfileInfo) FiVRKAuthCertificateProfileInfo(ee.ria.xroad.common.certificateprofile.impl.FiVRKAuthCertificateProfileInfo) FiVRKSignCertificateProfileInfo(ee.ria.xroad.common.certificateprofile.impl.FiVRKSignCertificateProfileInfo) FiVRKAuthCertificateProfileInfo(ee.ria.xroad.common.certificateprofile.impl.FiVRKAuthCertificateProfileInfo) AuthCertificateProfileInfo(ee.ria.xroad.common.certificateprofile.AuthCertificateProfileInfo) FiVRKAuthCertificateProfileInfo(ee.ria.xroad.common.certificateprofile.impl.FiVRKAuthCertificateProfileInfo) Test(org.junit.Test)

Aggregations

CertificateProfileInfo (ee.ria.xroad.common.certificateprofile.CertificateProfileInfo)4 KeyInfo (ee.ria.xroad.signer.protocol.dto.KeyInfo)3 DnFieldValue (ee.ria.xroad.common.certificateprofile.DnFieldValue)2 ArrayList (java.util.ArrayList)2 KeyNotFoundException (org.niis.xroad.securityserver.restapi.service.KeyNotFoundException)2 AccessDeniedException (org.springframework.security.access.AccessDeniedException)2 CodedException (ee.ria.xroad.common.CodedException)1 AuthCertificateProfileInfo (ee.ria.xroad.common.certificateprofile.AuthCertificateProfileInfo)1 FiVRKAuthCertificateProfileInfo (ee.ria.xroad.common.certificateprofile.impl.FiVRKAuthCertificateProfileInfo)1 FiVRKSignCertificateProfileInfo (ee.ria.xroad.common.certificateprofile.impl.FiVRKSignCertificateProfileInfo)1 ApprovedCAInfo (ee.ria.xroad.common.conf.globalconf.ApprovedCAInfo)1 ClientType (ee.ria.xroad.common.conf.serverconf.model.ClientType)1 ClientId (ee.ria.xroad.common.identifier.ClientId)1 KeyUsageInfo (ee.ria.xroad.signer.protocol.dto.KeyUsageInfo)1 TokenInfo (ee.ria.xroad.signer.protocol.dto.TokenInfo)1 X500Principal (javax.security.auth.x500.X500Principal)1 Before (org.junit.Before)1 Test (org.junit.Test)1 DeviationAwareRuntimeException (org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException)1 ErrorDeviation (org.niis.xroad.restapi.exceptions.ErrorDeviation)1