Search in sources :

Example 21 with CertificateInfo

use of ee.ria.xroad.signer.protocol.dto.CertificateInfo 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)

Example 22 with CertificateInfo

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

the class TokenCertificateService method changeCertificateActivation.

/**
 * Deactivates or activates certificate
 */
private void changeCertificateActivation(String hash, boolean activate) throws CertificateNotFoundException, AccessDeniedException, ActionNotPossibleException {
    // verify correct authority
    CertificateInfo certificateInfo = getCertificateInfo(hash);
    try {
        verifyActivateDisableAuthority(certificateInfo.getCertificateBytes());
    } catch (InvalidCertificateException e) {
        // cert from signer proxy was invalid, should not be possible
        throw new RuntimeException(e);
    }
    // verify possible actions
    EnumSet<PossibleActionEnum> possibleActions = getPossibleActionsForCertificateInternal(hash, certificateInfo, null, null);
    PossibleActionEnum activationAction = null;
    if (activate) {
        activationAction = PossibleActionEnum.ACTIVATE;
    } else {
        activationAction = PossibleActionEnum.DISABLE;
    }
    possibleActionsRuleEngine.requirePossibleAction(activationAction, possibleActions);
    // audit log data
    auditLogTokenKeyAndCert(hash, certificateInfo, true);
    try {
        if (activate) {
            signerProxyFacade.activateCert(certificateInfo.getId());
        } else {
            signerProxyFacade.deactivateCert(certificateInfo.getId());
        }
    } catch (CodedException e) {
        if (isCausedByCertNotFound(e)) {
            throw new CertificateNotFoundException("Certificate with id " + certificateInfo.getId() + " " + NOT_FOUND);
        } else {
            throw e;
        }
    } catch (Exception e) {
        throw new SignerNotReachableException("certificate " + (activate ? "activation" : "deactivation") + " failed", e);
    }
}
Also used : DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) CodedException(ee.ria.xroad.common.CodedException) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) 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) SignerNotReachableException(org.niis.xroad.restapi.service.SignerNotReachableException)

Example 23 with CertificateInfo

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

the class ClientsApiControllerIntegrationTest method getClientSignCertificates.

@Test
@WithMockUser(authorities = "VIEW_CLIENT_DETAILS")
public void getClientSignCertificates() throws Exception {
    ResponseEntity<Set<TokenCertificate>> certificates = clientsApiController.getClientSignCertificates("FI:GOV:M1");
    assertEquals(HttpStatus.OK, certificates.getStatusCode());
    assertEquals(0, certificates.getBody().size());
    CertificateInfo mockCertificate = new CertificateInfo(ClientId.create("FI", "GOV", "M1"), true, true, CertificateInfo.STATUS_REGISTERED, "id", CertificateTestUtils.getMockCertificateBytes(), null);
    doReturn(Collections.singletonList(mockCertificate)).when(tokenService).getSignCertificates(any());
    certificates = clientsApiController.getClientSignCertificates("FI:GOV:M1");
    assertEquals(HttpStatus.OK, certificates.getStatusCode());
    assertEquals(1, certificates.getBody().size());
    Set<TokenCertificate> onlyCertificateSet = certificates.getBody();
    TokenCertificate onlyCertificate = onlyCertificateSet.stream().findFirst().orElse(null);
    assertEquals("N/A", onlyCertificate.getCertificateDetails().getIssuerCommonName());
    assertEquals(OffsetDateTime.parse("1970-01-01T00:00:00Z"), onlyCertificate.getCertificateDetails().getNotBefore());
    assertEquals(OffsetDateTime.parse("2038-01-01T00:00:00Z"), onlyCertificate.getCertificateDetails().getNotAfter());
    assertEquals("1", onlyCertificate.getCertificateDetails().getSerial());
    assertEquals(new Integer(3), onlyCertificate.getCertificateDetails().getVersion());
    assertEquals("SHA512withRSA", onlyCertificate.getCertificateDetails().getSignatureAlgorithm());
    assertEquals("RSA", onlyCertificate.getCertificateDetails().getPublicKeyAlgorithm());
    assertEquals("A2293825AA82A5429EC32803847E2152A303969C", onlyCertificate.getCertificateDetails().getHash());
    assertTrue(onlyCertificate.getCertificateDetails().getSignature().startsWith("314b7a50a09a9b74322671"));
    assertTrue(onlyCertificate.getCertificateDetails().getRsaPublicKeyModulus().startsWith("9d888fbe089b32a35f58"));
    assertEquals(new Integer(65537), onlyCertificate.getCertificateDetails().getRsaPublicKeyExponent());
    assertEquals(new ArrayList<>(Arrays.asList(org.niis.xroad.securityserver.restapi.openapi.model.KeyUsage.NON_REPUDIATION)), new ArrayList<>(onlyCertificate.getCertificateDetails().getKeyUsages()));
    try {
        certificates = clientsApiController.getClientSignCertificates("FI:GOV:M2");
        fail("should throw ResourceNotFoundException for 404");
    } catch (ResourceNotFoundException expected) {
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) TokenCertificate(org.niis.xroad.securityserver.restapi.openapi.model.TokenCertificate) ResourceNotFoundException(org.niis.xroad.restapi.openapi.ResourceNotFoundException) WithMockUser(org.springframework.security.test.context.support.WithMockUser) WsdlValidatorTest(org.niis.xroad.securityserver.restapi.wsdl.WsdlValidatorTest) Test(org.junit.Test)

Example 24 with CertificateInfo

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

the class TokenCertificatesApiControllerIntegrationTest method importAuthCertificate.

@Test
@WithMockUser(authorities = "IMPORT_AUTH_CERT")
public void importAuthCertificate() throws Exception {
    X509Certificate mockAuthCert = getMockAuthCertificate();
    CertificateInfo certificateInfo = new CertificateTestUtils.CertificateInfoBuilder().certificate(mockAuthCert).certificateStatus(CertificateInfo.STATUS_SAVED).build();
    doAnswer(answer -> certificateInfo).when(signerProxyFacade).getCertForHash(any());
    Resource body = CertificateTestUtils.getResource(mockAuthCert.getEncoded());
    ResponseEntity<TokenCertificate> response = tokenCertificatesApiController.importCertificate(body);
    TokenCertificate addedCert = response.getBody();
    assertEquals(HttpStatus.CREATED, response.getStatusCode());
    assertAuthCertificateDetails(addedCert);
    assertLocationHeader("/api/token-certificates/" + addedCert.getCertificateDetails().getHash(), response);
}
Also used : CertificateInfoBuilder(org.niis.xroad.securityserver.restapi.util.CertificateTestUtils.CertificateInfoBuilder) CertificateTestUtils(org.niis.xroad.securityserver.restapi.util.CertificateTestUtils) Resource(org.springframework.core.io.Resource) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) TokenCertificate(org.niis.xroad.securityserver.restapi.openapi.model.TokenCertificate) X509Certificate(java.security.cert.X509Certificate) WithMockUser(org.springframework.security.test.context.support.WithMockUser) Test(org.junit.Test)

Example 25 with CertificateInfo

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

the class TokenCertificatesApiControllerIntegrationTest method setup.

@Before
public void setup() throws Exception {
    doAnswer(answer -> "key-id").when(signerProxyFacade).importCert(any(), any(), any());
    doAnswer(answer -> null).when(globalConfFacade).verifyValidity();
    doAnswer(answer -> TestUtils.INSTANCE_FI).when(globalConfFacade).getInstanceIdentifier();
    doAnswer(answer -> TestUtils.getM1Ss1ClientId()).when(globalConfFacade).getSubjectName(any(), any());
    CertificateInfo signCertificateInfo = new CertificateInfoBuilder().certificate(getMockCertificate()).certificateStatus("SAVED").build();
    CertificateInfo authCertificateInfo = new CertificateInfoBuilder().certificate(getMockAuthCertificate()).certificateStatus("SAVED").build();
    CertificateInfo unknownCertificateInfo = new CertificateInfoBuilder().certificate(getMockCertificateWithoutExtensions()).certificateStatus("SAVED").build();
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        String certId = (String) args[0];
        if (AUTH_CERT_HASH.equals(certId)) {
            return authCertificateInfo;
        } else if (UNKNOWN_CERT_HASH.equals(certId)) {
            return unknownCertificateInfo;
        } else {
            return signCertificateInfo;
        }
    }).when(signerProxyFacade).getCertForHash(any());
    doAnswer(answer -> "key-id").when(signerProxyFacade).getKeyIdForCertHash(any());
    TokenInfo tokenInfo = new TokenTestUtils.TokenInfoBuilder().build();
    KeyInfo keyInfo = new TokenTestUtils.KeyInfoBuilder().id("key-id").build();
    tokenInfo.getKeyInfo().add(keyInfo);
    doAnswer(answer -> Collections.singletonList(tokenInfo)).when(signerProxyFacade).getTokens();
    TokenInfoAndKeyId tokenInfoAndKeyId = new TokenInfoAndKeyId(tokenInfo, keyInfo.getId());
    doAnswer(answer -> tokenInfoAndKeyId).when(signerProxyFacade).getTokenAndKeyIdForCertRequestId(any());
    doAnswer(answer -> tokenInfoAndKeyId).when(signerProxyFacade).getTokenAndKeyIdForCertHash(any());
    // by default all actions are possible
    doReturn(EnumSet.allOf(PossibleActionEnum.class)).when(possibleActionsRuleEngine).getPossibleCertificateActions(any(), any(), any());
}
Also used : TokenInfoAndKeyId(ee.ria.xroad.signer.protocol.dto.TokenInfoAndKeyId) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) PossibleActionEnum(org.niis.xroad.securityserver.restapi.service.PossibleActionEnum) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) TokenInfo(ee.ria.xroad.signer.protocol.dto.TokenInfo) TokenTestUtils(org.niis.xroad.securityserver.restapi.util.TokenTestUtils) CertificateInfoBuilder(org.niis.xroad.securityserver.restapi.util.CertificateTestUtils.CertificateInfoBuilder) Before(org.junit.Before)

Aggregations

CertificateInfo (ee.ria.xroad.signer.protocol.dto.CertificateInfo)39 KeyInfo (ee.ria.xroad.signer.protocol.dto.KeyInfo)16 Test (org.junit.Test)12 TokenInfo (ee.ria.xroad.signer.protocol.dto.TokenInfo)11 TokenCertificate (org.niis.xroad.securityserver.restapi.openapi.model.TokenCertificate)9 X509Certificate (java.security.cert.X509Certificate)8 CertificateTestUtils (org.niis.xroad.securityserver.restapi.util.CertificateTestUtils)8 ClientId (ee.ria.xroad.common.identifier.ClientId)7 CodedException (ee.ria.xroad.common.CodedException)6 SignerNotReachableException (org.niis.xroad.restapi.service.SignerNotReachableException)5 CertRequestInfo (ee.ria.xroad.signer.protocol.dto.CertRequestInfo)4 KeyUsageInfo (ee.ria.xroad.signer.protocol.dto.KeyUsageInfo)4 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 HashSet (java.util.HashSet)4 RevokedStatus (org.bouncycastle.cert.ocsp.RevokedStatus)4 DeviationAwareRuntimeException (org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException)4 ServiceException (org.niis.xroad.restapi.service.ServiceException)4 InternalServerErrorException (org.niis.xroad.securityserver.restapi.openapi.InternalServerErrorException)4 TokenTestUtils (org.niis.xroad.securityserver.restapi.util.TokenTestUtils)4