Search in sources :

Example 1 with CSR

use of de.trustable.ca3s.core.domain.CSR in project ca3sCore by kuehne-trustable-de.

the class CSRResourceIT method updateCSR.

@Test
@Transactional
public void updateCSR() throws Exception {
    // Initialize the database
    cSRService.save(cSR);
    int databaseSizeBeforeUpdate = cSRRepository.findAll().size();
    // Update the cSR
    CSR updatedCSR = cSRRepository.findById(cSR.getId()).get();
    // Disconnect from session so that the updates on updatedCSR are not directly saved in db
    em.detach(updatedCSR);
    updatedCSR.csrBase64(UPDATED_CSR_BASE_64).subject(UPDATED_SUBJECT).sans(UPDATED_SANS).requestedOn(UPDATED_REQUESTED_ON).requestedBy(UPDATED_REQUESTED_BY).pipelineType(UPDATED_PIPELINE_TYPE).status(UPDATED_STATUS).administeredBy(UPDATED_ADMINISTERED_BY).approvedOn(UPDATED_APPROVED_ON).rejectedOn(UPDATED_REJECTED_ON).rejectionReason(UPDATED_REJECTION_REASON).processInstanceId(UPDATED_PROCESS_INSTANCE_ID).signingAlgorithm(UPDATED_SIGNING_ALGORITHM).isCSRValid(UPDATED_IS_CSR_VALID).x509KeySpec(UPDATED_X_509_KEY_SPEC).publicKeyAlgorithm(UPDATED_PUBLIC_KEY_ALGORITHM).keyAlgorithm(UPDATED_KEY_ALGORITHM).keyLength(UPDATED_KEY_LENGTH).publicKeyHash(UPDATED_PUBLIC_KEY_HASH).serversideKeyGeneration(UPDATED_SERVERSIDE_KEY_GENERATION).subjectPublicKeyInfoBase64(UPDATED_SUBJECT_PUBLIC_KEY_INFO_BASE_64).requestorComment(UPDATED_REQUESTOR_COMMENT).administrationComment(UPDATED_ADMINISTRATION_COMMENT);
    restCSRMockMvc.perform(put("/api/csrs").contentType(TestUtil.APPLICATION_JSON_UTF8).content(TestUtil.convertObjectToJsonBytes(updatedCSR))).andExpect(status().isOk());
    // Validate the CSR in the database
    List<CSR> cSRList = cSRRepository.findAll();
    assertThat(cSRList).hasSize(databaseSizeBeforeUpdate);
    CSR testCSR = cSRList.get(cSRList.size() - 1);
    assertThat(testCSR.getCsrBase64()).isEqualTo(UPDATED_CSR_BASE_64);
    assertThat(testCSR.getSubject()).isEqualTo(UPDATED_SUBJECT);
    assertThat(testCSR.getSans()).isEqualTo(UPDATED_SANS);
    assertThat(testCSR.getRequestedOn()).isEqualTo(UPDATED_REQUESTED_ON);
    assertThat(testCSR.getRequestedBy()).isEqualTo(UPDATED_REQUESTED_BY);
    assertThat(testCSR.getPipelineType()).isEqualTo(UPDATED_PIPELINE_TYPE);
    assertThat(testCSR.getStatus()).isEqualTo(UPDATED_STATUS);
    assertThat(testCSR.getAdministeredBy()).isEqualTo(UPDATED_ADMINISTERED_BY);
    assertThat(testCSR.getApprovedOn()).isEqualTo(UPDATED_APPROVED_ON);
    assertThat(testCSR.getRejectedOn()).isEqualTo(UPDATED_REJECTED_ON);
    assertThat(testCSR.getRejectionReason()).isEqualTo(UPDATED_REJECTION_REASON);
    assertThat(testCSR.getProcessInstanceId()).isEqualTo(UPDATED_PROCESS_INSTANCE_ID);
    assertThat(testCSR.getSigningAlgorithm()).isEqualTo(UPDATED_SIGNING_ALGORITHM);
    assertThat(testCSR.isIsCSRValid()).isEqualTo(UPDATED_IS_CSR_VALID);
    assertThat(testCSR.getx509KeySpec()).isEqualTo(UPDATED_X_509_KEY_SPEC);
    assertThat(testCSR.getPublicKeyAlgorithm()).isEqualTo(UPDATED_PUBLIC_KEY_ALGORITHM);
    assertThat(testCSR.getKeyAlgorithm()).isEqualTo(UPDATED_KEY_ALGORITHM);
    assertThat(testCSR.getKeyLength()).isEqualTo(UPDATED_KEY_LENGTH);
    assertThat(testCSR.getPublicKeyHash()).isEqualTo(UPDATED_PUBLIC_KEY_HASH);
    assertThat(testCSR.isServersideKeyGeneration()).isEqualTo(UPDATED_SERVERSIDE_KEY_GENERATION);
    assertThat(testCSR.getSubjectPublicKeyInfoBase64()).isEqualTo(UPDATED_SUBJECT_PUBLIC_KEY_INFO_BASE_64);
    assertThat(testCSR.getRequestorComment()).isEqualTo(UPDATED_REQUESTOR_COMMENT);
    assertThat(testCSR.getAdministrationComment()).isEqualTo(UPDATED_ADMINISTRATION_COMMENT);
}
Also used : CSR(de.trustable.ca3s.core.domain.CSR) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with CSR

use of de.trustable.ca3s.core.domain.CSR in project ca3sCore by kuehne-trustable-de.

the class UnauthorizedException method buildPKCS12Response.

private ResponseEntity<byte[]> buildPKCS12Response(Certificate certDao, final String alias, final HttpHeaders headers) throws GeneralSecurityException {
    LOG.info("building PKCS12 container response");
    String entryAlias = "entry";
    if (alias != null && !alias.trim().isEmpty()) {
        entryAlias = alias;
    }
    CSR csr = certDao.getCsr();
    if (csr == null) {
        throw new GeneralSecurityException("problem downloading keystore content for cert id " + certDao.getId() + ": no csr object available ");
    }
    if (SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN) || SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.RA_OFFICER)) {
        LOG.debug("Admins and RA Officers are allowed to download P12 files");
    } else if (SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.DOMAIN_RA_OFFICER)) {
        LOG.debug("Admins and RA Officers are allowed to download P12 files");
    } else {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String userName = auth.getName();
        if (userName == null) {
            throw new GeneralSecurityException("problem downloading keystore content for csr id " + csr.getId() + ":  user name not available");
        }
        if (!userName.equals(csr.getRequestedBy())) {
            throw new AccessControlException("problem downloading keystore content for csr id " + csr.getId() + ": user does not match initial requestor");
        }
    }
    if (!csr.isServersideKeyGeneration()) {
        throw new GeneralSecurityException("problem downloading keystore content for csr id " + csr.getId() + ": key not generated serverside");
    }
    List<ProtectedContent> protContentList = protContentUtil.retrieveProtectedContent(ProtectedContentType.PASSWORD, ContentRelationType.CSR, csr.getId());
    if (protContentList.size() == 0) {
        throw new GeneralSecurityException("problem downloading keystore content for csr id " + csr.getId() + ": no keystore passphrase available ");
    }
    PrivateKey key = certUtil.getPrivateKey(ProtectedContentType.KEY, ContentRelationType.CSR, csr.getId());
    boolean keyEx = false;
    List<String> keyExHeaderList = headers.get("X_keyEx");
    if (keyExHeaderList != null && !keyExHeaderList.isEmpty()) {
        keyEx = Boolean.parseBoolean(keyExHeaderList.get(0));
    }
    LOG.info("PKCS12: keyEx flag: {} ", keyEx);
    String passwordProtectionAlgo = cryptoConfiguration.getDefaultPBEAlgo();
    List<String> algoHeaderList = headers.get("X_pbeAlgo");
    if (algoHeaderList != null && !algoHeaderList.isEmpty()) {
        String reqAlgo = algoHeaderList.get(0).trim();
        if (cryptoConfiguration.isPBEAlgoAllowed(reqAlgo)) {
            passwordProtectionAlgo = reqAlgo;
        } else {
            LOG.info("requested PKCS12 pbe algo '{}' not in list of valid algos, using default '{}' ", reqAlgo, passwordProtectionAlgo);
        }
    }
    LOG.info("PKCS12: using algo {} ", passwordProtectionAlgo);
    byte[] salt = new byte[20];
    new SecureRandom().nextBytes(salt);
    char[] passphraseChars = protContentUtil.unprotectString(protContentList.get(0).getContentBase64()).toCharArray();
    try {
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, passphraseChars);
        X509Certificate[] chain = certUtil.getX509CertificateChain(certDao);
        Set<KeyStore.Entry.Attribute> privateKeyAttributes = new HashSet<>();
        p12.setEntry(entryAlias, new KeyStore.PrivateKeyEntry(key, chain, privateKeyAttributes), new KeyStore.PasswordProtection(passphraseChars, passwordProtectionAlgo, new PBEParameterSpec(salt, 100000)));
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            p12.store(baos, passphraseChars);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            KeyStore store = KeyStore.getInstance("pkcs12");
            store.load(bais, passphraseChars);
            java.security.cert.Certificate cert = store.getCertificate(entryAlias);
            LOG.debug("retrieved cert " + cert);
            byte[] contentBytes = baos.toByteArray();
            headers.set("content-length", String.valueOf(contentBytes.length));
            return ResponseEntity.ok().contentType(ACMEController.APPLICATION_PKCS12).headers(headers).body(contentBytes);
        }
    } catch (IOException gse) {
        throw new GeneralSecurityException("problem downloading keystore content for cert id " + certDao.getId());
    }
}
Also used : ProtectedContent(de.trustable.ca3s.core.domain.ProtectedContent) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) CSR(de.trustable.ca3s.core.domain.CSR) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Authentication(org.springframework.security.core.Authentication)

Example 3 with CSR

use of de.trustable.ca3s.core.domain.CSR in project ca3sCore by kuehne-trustable-de.

the class OrderController method startCertificateCreationProcess.

private Certificate startCertificateCreationProcess(AcmeOrder orderDao, Pipeline pipeline, final String requestorName, final String csrAsPem) {
    List<String> messageList = new ArrayList<>();
    NamedValues[] nvArr = new NamedValues[0];
    CSR csr = cpUtil.buildCSR(csrAsPem, requestorName, AuditService.AUDIT_ACME_CERTIFICATE_REQUESTED, "", pipeline, nvArr, messageList);
    if (csr == null) {
        LOG.info("building CSR failed");
        String msg = "";
        if (!messageList.isEmpty()) {
            msg = messageList.get(0);
        }
        final ProblemDetail problem = new ProblemDetail(ACMEUtil.BAD_CSR, msg, BAD_REQUEST, "", ACMEController.NO_INSTANCE);
        throw new AcmeProblemException(problem);
    }
    orderDao.setCsr(csr);
    Certificate cert = cpUtil.processCertificateRequest(csr, requestorName, AuditService.AUDIT_ACME_CERTIFICATE_CREATED, pipeline);
    if (cert == null) {
        orderDao.setCertificate(cert);
        orderDao.setStatus(AcmeOrderStatus.INVALID);
        LOG.warn("creation of certificate by ACME order {} failed ", orderDao.getOrderId());
    } else {
        LOG.debug("updating order id {} with new certificate id {}", orderDao.getOrderId(), cert.getId());
        orderDao.setCertificate(cert);
        orderDao.setStatus(AcmeOrderStatus.VALID);
        LOG.debug("adding certificate attribute 'ACME_ACCOUNT_ID' {} for certificate id {}", orderDao.getAccount().getAccountId(), cert.getId());
        certUtil.setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ACME_ACCOUNT_ID, orderDao.getAccount().getAccountId());
        certUtil.setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ACME_ORDER_ID, orderDao.getOrderId());
    }
    return cert;
}
Also used : ProblemDetail(de.trustable.ca3s.core.service.dto.acme.problem.ProblemDetail) CSR(de.trustable.ca3s.core.domain.CSR) AcmeProblemException(de.trustable.ca3s.core.service.dto.acme.problem.AcmeProblemException) ArrayList(java.util.ArrayList) NamedValues(de.trustable.ca3s.core.service.dto.NamedValues) Certificate(de.trustable.ca3s.core.domain.Certificate)

Example 4 with CSR

use of de.trustable.ca3s.core.domain.CSR in project ca3sCore by kuehne-trustable-de.

the class CSRAdministration method withdrawOwnRequest.

/**
 * {@code POST  /withdrawOwnRequest} : Withdraw own request .
 *
 * @param adminData a structure holding some crypto-related content, e.g. CSR, certificate, P12 container
 * @return the {@link ResponseEntity} .
 */
@PostMapping("/withdrawOwnRequest")
@Transactional
public ResponseEntity<Long> withdrawOwnRequest(@Valid @RequestBody CSRAdministrationData adminData) {
    LOG.debug("REST request to withdraw CSR : {}", adminData);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String userName = auth.getName();
    Optional<CSR> optCSR = csrRepository.findById(adminData.getCsrId());
    if (optCSR.isPresent()) {
        CSR csr = optCSR.get();
        if (userName == null || !userName.equals(csr.getRequestedBy())) {
            LOG.debug("REST request by '{}' to withdraw CSR '{}' rejected ", userName, adminData.getCsrId());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        csr.setAdministeredBy(userName);
        updateComment(adminData, csr);
        csrUtil.setStatusAndRejectionReason(csr, CsrStatus.REJECTED, adminData.getRejectionReason());
        csrRepository.save(csr);
        auditService.saveAuditTrace(auditService.createAuditTraceCsrRejected(csr));
        return new ResponseEntity<>(adminData.getCsrId(), HttpStatus.OK);
    } else {
        return ResponseEntity.notFound().build();
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) CSR(de.trustable.ca3s.core.domain.CSR) Authentication(org.springframework.security.core.Authentication) PostMapping(org.springframework.web.bind.annotation.PostMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with CSR

use of de.trustable.ca3s.core.domain.CSR in project ca3sCore by kuehne-trustable-de.

the class CSRAdministration method selfAdministerRequest.

/**
 * {@code POST  /selfAdministerRequest} : update own request .
 *
 * @param adminData a structure holding some crypto-related content, e.g. CSR, certificate, P12 container
 * @return the {@link ResponseEntity} .
 */
@PostMapping("/selfAdministerRequest")
@Transactional
public ResponseEntity<Long> selfAdministerRequest(@Valid @RequestBody CSRAdministrationData adminData) {
    LOG.debug("REST request to update CSR : {}", adminData);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String userName = auth.getName();
    Optional<CSR> optCSR = csrRepository.findById(adminData.getCsrId());
    if (optCSR.isPresent()) {
        CSR csr = optCSR.get();
        if (userName == null || !userName.equals(csr.getRequestedBy())) {
            LOG.debug("REST request by '{}' to update CSR '{}' rejected ", userName, adminData.getCsrId());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        csr.setAdministeredBy(userName);
        updateComment(adminData, csr);
        updateARAttributes(adminData, csr);
        csrRepository.save(csr);
        return new ResponseEntity<>(adminData.getCsrId(), HttpStatus.OK);
    } else {
        return ResponseEntity.notFound().build();
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) CSR(de.trustable.ca3s.core.domain.CSR) Authentication(org.springframework.security.core.Authentication) PostMapping(org.springframework.web.bind.annotation.PostMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

CSR (de.trustable.ca3s.core.domain.CSR)15 Transactional (org.springframework.transaction.annotation.Transactional)7 User (de.trustable.ca3s.core.domain.User)6 Authentication (org.springframework.security.core.Authentication)5 PostMapping (org.springframework.web.bind.annotation.PostMapping)5 Certificate (de.trustable.ca3s.core.domain.Certificate)4 ArrayList (java.util.ArrayList)4 ResponseEntity (org.springframework.http.ResponseEntity)4 Transactional (javax.transaction.Transactional)3 CAConnectorConfig (de.trustable.ca3s.core.domain.CAConnectorConfig)2 ProtectedContent (de.trustable.ca3s.core.domain.ProtectedContent)2 Instant (java.time.Instant)2 Locale (java.util.Locale)2 Test (org.junit.jupiter.api.Test)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 Context (org.thymeleaf.context.Context)2 CsrAttribute (de.trustable.ca3s.core.domain.CsrAttribute)1 CSRView (de.trustable.ca3s.core.service.dto.CSRView)1 NamedValues (de.trustable.ca3s.core.service.dto.NamedValues)1