Search in sources :

Example 11 with KeyUsageInfo

use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.

the class OrphanRemovalServiceTest method setup.

@Before
public void setup() throws Exception {
    KeyInfo key01 = new TokenTestUtils.KeyInfoBuilder().id(KEY_01_ID).keyUsageInfo(KeyUsageInfo.SIGNING).csr(new CertificateTestUtils.CertRequestInfoBuilder().clientId(NON_DELETED_CLIENT_ID_O1).id(ORPHAN_CSR_01_ID).build()).build();
    KeyInfo key05 = new TokenTestUtils.KeyInfoBuilder().id(KEY_05_ID).keyUsageInfo(KeyUsageInfo.SIGNING).csr(new CertificateTestUtils.CertRequestInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_ORPHAN_CSR_O5).id(ORPHAN_CSR_05_ID).build()).build();
    KeyInfo key06 = new TokenTestUtils.KeyInfoBuilder().id(KEY_06_ID).keyUsageInfo(KeyUsageInfo.SIGNING).cert(new CertificateTestUtils.CertificateInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_ORPHAN_CERT_O6).id(ORPHAN_CERT_06_HASH).build()).build();
    KeyInfo key071 = new TokenTestUtils.KeyInfoBuilder().id(KEY_07_SIGN_ORPHAN_1_ID).keyUsageInfo(KeyUsageInfo.SIGNING).cert(new CertificateTestUtils.CertificateInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_MULTIPLE_KEYS_07).id(ORPHAN_CERT_07_1_HASH).build()).build();
    KeyInfo key072 = new TokenTestUtils.KeyInfoBuilder().id(KEY_07_SIGN_ORPHAN_2_ID).keyUsageInfo(KeyUsageInfo.SIGNING).cert(new CertificateTestUtils.CertificateInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_MULTIPLE_KEYS_07).id(ORPHAN_CERT_07_2_HASH).build()).csr(new CertificateTestUtils.CertRequestInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_MULTIPLE_KEYS_07).id(ORPHAN_CSR_07_2_ID).build()).build();
    KeyInfo key073 = new TokenTestUtils.KeyInfoBuilder().id(KEY_07_SIGN_SHARED_ID).keyUsageInfo(KeyUsageInfo.SIGNING).cert(new CertificateTestUtils.CertificateInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_MULTIPLE_KEYS_07).id(SHARED_KEY_CERT_07_1_HASH).build()).cert(new CertificateTestUtils.CertificateInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_MULTIPLE_KEYS_07).id(SHARED_KEY_CERT_07_2_HASH).build()).csr(new CertificateTestUtils.CertRequestInfoBuilder().clientId(DELETED_CLIENT_ID_WITH_MULTIPLE_KEYS_07).id(SHARED_KEY_CSR_07_ID).build()).csr(new CertificateTestUtils.CertRequestInfoBuilder().clientId(KEY_SHARING_CLIENT_07_08).id(SHARED_KEY_CSR_08_ID).build()).build();
    KeyInfo key074 = new TokenTestUtils.KeyInfoBuilder().id(KEY_07_AUTH_ID).keyUsageInfo(KeyUsageInfo.AUTHENTICATION).cert(new CertificateTestUtils.CertificateInfoBuilder().id(AUTH_CERT_07_HASH).build()).build();
    TokenInfo tokenInfo = new TokenTestUtils.TokenInfoBuilder().friendlyName("fubar").key(key01).key(key05).key(key06).key(key071).key(key072).key(key073).key(key074).build();
    Map<String, KeyInfo> certCsrIdentifierToKey = new HashMap<>();
    // certs and csrs should not have duplicate ids/hashes
    tokenInfo.getKeyInfo().forEach(key -> key.getCerts().forEach(cert -> {
        if (certCsrIdentifierToKey.containsKey(cert.getId()))
            throw new RuntimeException("duplicate");
        certCsrIdentifierToKey.put(cert.getId(), key);
    }));
    tokenInfo.getKeyInfo().forEach(key -> key.getCertRequests().forEach(csr -> {
        if (certCsrIdentifierToKey.containsKey(csr.getId()))
            throw new RuntimeException("duplicate");
        certCsrIdentifierToKey.put(csr.getId(), key);
    }));
    doReturn(Collections.singletonList(tokenInfo)).when(signerProxyFacade).getTokens();
    Map<ClientId, ClientType> localClients = new HashMap<>();
    ALL_LOCAL_CLIENTS.forEach(id -> {
        ClientType clientType = new ClientType();
        clientType.setIdentifier(id);
        localClients.put(id, clientType);
    });
    doReturn(new ArrayList(localClients.values())).when(clientRepository).getAllLocalClients();
    doAnswer(invocation -> {
        ClientId clientId = (ClientId) invocation.getArguments()[0];
        return localClients.get(clientId);
    }).when(clientRepository).getClient(any());
    doReturn(tokenInfo).when(signerProxyFacade).getTokenForKeyId(any());
    doAnswer(invocation -> {
        String certHash = (String) invocation.getArguments()[0];
        return new TokenInfoAndKeyId(tokenInfo, certCsrIdentifierToKey.get(certHash).getId());
    }).when(signerProxyFacade).getTokenAndKeyIdForCertHash(any());
    doAnswer(invocation -> {
        String csrId = (String) invocation.getArguments()[0];
        return new TokenInfoAndKeyId(tokenInfo, certCsrIdentifierToKey.get(csrId).getId());
    }).when(signerProxyFacade).getTokenAndKeyIdForCertRequestId(any());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CertRequestInfo(ee.ria.xroad.signer.protocol.dto.CertRequestInfo) Arrays(java.util.Arrays) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) TokenInfoAndKeyId(ee.ria.xroad.signer.protocol.dto.TokenInfoAndKeyId) ArrayList(java.util.ArrayList) KeyUsageInfo(ee.ria.xroad.signer.protocol.dto.KeyUsageInfo) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Mockito.atLeast(org.mockito.Mockito.atLeast) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) Assert.fail(org.junit.Assert.fail) ClientType(ee.ria.xroad.common.conf.serverconf.model.ClientType) Mockito.doReturn(org.mockito.Mockito.doReturn) Before(org.junit.Before) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) TokenInfo(ee.ria.xroad.signer.protocol.dto.TokenInfo) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) Mockito.verify(org.mockito.Mockito.verify) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) WithMockUser(org.springframework.security.test.context.support.WithMockUser) TestUtils(org.niis.xroad.securityserver.restapi.util.TestUtils) TokenTestUtils(org.niis.xroad.securityserver.restapi.util.TokenTestUtils) Assert.assertFalse(org.junit.Assert.assertFalse) ClientId(ee.ria.xroad.common.identifier.ClientId) Collections(java.util.Collections) CertificateTestUtils(org.niis.xroad.securityserver.restapi.util.CertificateTestUtils) Assert.assertEquals(org.junit.Assert.assertEquals) TokenInfoAndKeyId(ee.ria.xroad.signer.protocol.dto.TokenInfoAndKeyId) ClientType(ee.ria.xroad.common.conf.serverconf.model.ClientType) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TokenTestUtils(org.niis.xroad.securityserver.restapi.util.TokenTestUtils) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) CertificateTestUtils(org.niis.xroad.securityserver.restapi.util.CertificateTestUtils) ClientId(ee.ria.xroad.common.identifier.ClientId) TokenInfo(ee.ria.xroad.signer.protocol.dto.TokenInfo) Before(org.junit.Before)

Example 12 with KeyUsageInfo

use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.

the class CertificateAuthorityService method getCertificateAuthorities.

/**
 * Return approved certificate authorities
 * @param keyUsageInfo list CAs for this type of key usage. If null, list all.
 * @param includeIntermediateCas true = also include intermediate CAs.
 *                               false = only include top CAs
 * @throws InconsistentCaDataException if required CA data could not be extracted, for example due to OCSP
 * responses not being valid
 * @return list of approved CAs
 */
@Cacheable(GET_CERTIFICATE_AUTHORITIES_CACHE)
public List<ApprovedCaDto> getCertificateAuthorities(KeyUsageInfo keyUsageInfo, boolean includeIntermediateCas) throws InconsistentCaDataException {
    log.debug("getCertificateAuthorities");
    List<X509Certificate> caCerts = new ArrayList<>(globalConfService.getAllCaCertsForThisInstance());
    List<ApprovedCaDto> dtos = new ArrayList<>();
    // map of each subject - issuer DN pair for easy lookups
    Map<String, String> subjectsToIssuers = caCerts.stream().collect(Collectors.toMap(x509 -> x509.getSubjectDN().getName(), x509 -> x509.getIssuerDN().getName()));
    // we only fetch ocsp responses for intermediate approved CAs
    // configured as approved CA and its issuer cert is also an approved CA
    List<X509Certificate> filteredCerts = caCerts.stream().filter(cert -> subjectsToIssuers.containsKey(cert.getIssuerDN().getName())).collect(Collectors.toList());
    String[] base64EncodedOcspResponses;
    try {
        String[] certHashes = CertUtils.getCertHashes(new ArrayList<>(filteredCerts));
        base64EncodedOcspResponses = signerProxyFacade.getOcspResponses(certHashes);
    } catch (Exception e) {
        throw new InconsistentCaDataException("failed to get read CA OCSP responses", e);
    }
    if (filteredCerts.size() != base64EncodedOcspResponses.length) {
        throw new InconsistentCaDataException(String.format("ocsp responses do not match ca certs %d vs %d", filteredCerts.size(), base64EncodedOcspResponses.length));
    }
    // build dtos
    for (X509Certificate cert : caCerts) {
        int idx = filteredCerts.indexOf(cert);
        dtos.add(buildCertificateAuthorityDto(cert, (idx != -1) ? base64EncodedOcspResponses[idx] : null, subjectsToIssuers));
    }
    if (keyUsageInfo == KeyUsageInfo.SIGNING) {
        // remove "authentication only" CAs
        dtos = dtos.stream().filter(dto -> !(Boolean.TRUE.equals(dto.isAuthenticationOnly()))).collect(Collectors.toList());
    }
    if (!includeIntermediateCas) {
        // remove intermediate CAs
        dtos = dtos.stream().filter(dto -> dto.isTopCa()).collect(Collectors.toList());
    }
    return dtos;
}
Also used : X509Certificate(java.security.cert.X509Certificate) ApprovedCAInfo(ee.ria.xroad.common.conf.globalconf.ApprovedCAInfo) CertUtils(ee.ria.xroad.common.util.CertUtils) Cacheable(org.springframework.cache.annotation.Cacheable) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequiredArgsConstructor(lombok.RequiredArgsConstructor) CertificateProfileInfoProvider(ee.ria.xroad.common.certificateprofile.CertificateProfileInfoProvider) ArrayList(java.util.ArrayList) FormatUtils(org.niis.xroad.restapi.util.FormatUtils) SignCertificateProfileInfoParameters(ee.ria.xroad.common.certificateprofile.impl.SignCertificateProfileInfoParameters) KeyUsageInfo(ee.ria.xroad.signer.protocol.dto.KeyUsageInfo) Service(org.springframework.stereotype.Service) Map(java.util.Map) ERROR_CA_CERT_PROCESSING(org.niis.xroad.restapi.exceptions.DeviationCodes.ERROR_CA_CERT_PROCESSING) SignerProxyFacade(org.niis.xroad.securityserver.restapi.facade.SignerProxyFacade) CurrentSecurityServerId(org.niis.xroad.securityserver.restapi.cache.CurrentSecurityServerId) CertificateProfileInfo(ee.ria.xroad.common.certificateprofile.CertificateProfileInfo) Collection(java.util.Collection) ErrorDeviation(org.niis.xroad.restapi.exceptions.ErrorDeviation) ApprovedCaDto(org.niis.xroad.securityserver.restapi.dto.ApprovedCaDto) OcspUtils(org.niis.xroad.securityserver.restapi.util.OcspUtils) Collectors(java.util.stream.Collectors) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) AuthCertificateProfileInfoParameters(ee.ria.xroad.common.certificateprofile.impl.AuthCertificateProfileInfoParameters) ServiceException(org.niis.xroad.restapi.service.ServiceException) SecurityServerId(ee.ria.xroad.common.identifier.SecurityServerId) GlobalConfFacade(org.niis.xroad.securityserver.restapi.facade.GlobalConfFacade) Optional(java.util.Optional) GetCertificateProfile(ee.ria.xroad.common.certificateprofile.GetCertificateProfile) ClientId(ee.ria.xroad.common.identifier.ClientId) Transactional(org.springframework.transaction.annotation.Transactional) ApprovedCaDto(org.niis.xroad.securityserver.restapi.dto.ApprovedCaDto) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) ServiceException(org.niis.xroad.restapi.service.ServiceException) Cacheable(org.springframework.cache.annotation.Cacheable)

Example 13 with KeyUsageInfo

use of ee.ria.xroad.signer.protocol.dto.KeyUsageInfo in project X-Road by nordic-institute.

the class TokensApiController method addKeyAndCsr.

@Override
@PreAuthorize("hasAuthority('GENERATE_KEY') " + " and (hasAuthority('GENERATE_AUTH_CERT_REQ') or hasAuthority('GENERATE_SIGN_CERT_REQ'))")
@AuditEventMethod(event = RestApiAuditEvent.GENERATE_KEY_AND_CSR)
public ResponseEntity<KeyWithCertificateSigningRequestId> addKeyAndCsr(String tokenId, KeyLabelWithCsrGenerate keyLabelWithCsrGenerate) {
    // squid:S3655 throwing NoSuchElementException if there is no value present is
    // fine since keyUsageInfo is mandatory parameter
    CsrGenerate csrGenerate = keyLabelWithCsrGenerate.getCsrGenerateRequest();
    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();
    KeyAndCertificateRequestService.KeyAndCertRequestInfo keyAndCertRequest;
    try {
        keyAndCertRequest = keyAndCertificateRequestService.addKeyAndCertRequest(tokenId, keyLabelWithCsrGenerate.getKeyLabel(), memberId, keyUsageInfo, csrGenerate.getCaName(), csrGenerate.getSubjectFieldValues(), csrFormat);
    } catch (ClientNotFoundException | CertificateAuthorityNotFoundException | DnFieldHelper.InvalidDnParameterException e) {
        throw new BadRequestException(e);
    } catch (ActionNotPossibleException e) {
        throw new ConflictException(e);
    } catch (TokenNotFoundException e) {
        throw new ResourceNotFoundException(e);
    }
    KeyWithCertificateSigningRequestId result = new KeyWithCertificateSigningRequestId();
    Key key = keyConverter.convert(keyAndCertRequest.getKeyInfo());
    result.setKey(key);
    result.setCsrId(keyAndCertRequest.getCertReqId());
    return new ResponseEntity<>(result, HttpStatus.OK);
}
Also used : KeyAndCertificateRequestService(org.niis.xroad.securityserver.restapi.service.KeyAndCertificateRequestService) CsrGenerate(org.niis.xroad.securityserver.restapi.openapi.model.CsrGenerate) KeyLabelWithCsrGenerate(org.niis.xroad.securityserver.restapi.openapi.model.KeyLabelWithCsrGenerate) 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) TokenNotFoundException(org.niis.xroad.securityserver.restapi.service.TokenNotFoundException) ResponseEntity(org.springframework.http.ResponseEntity) KeyWithCertificateSigningRequestId(org.niis.xroad.securityserver.restapi.openapi.model.KeyWithCertificateSigningRequestId) 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) Key(org.niis.xroad.securityserver.restapi.openapi.model.Key) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) AuditEventMethod(org.niis.xroad.restapi.config.audit.AuditEventMethod)

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