Search in sources :

Example 1 with DeviationAwareRuntimeException

use of org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException in project X-Road by nordic-institute.

the class SystemService method generateInternalCsr.

/**
 * Generate internal auth cert CSR
 * @param distinguishedName
 * @return
 * @throws InvalidDistinguishedNameException if {@code distinguishedName} does not conform to
 * <a href="http://www.ietf.org/rfc/rfc1779.txt">RFC 1779</a> or
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 */
public byte[] generateInternalCsr(String distinguishedName) throws InvalidDistinguishedNameException {
    auditDataHelper.put(RestApiAuditProperty.SUBJECT_NAME, distinguishedName);
    byte[] csrBytes = null;
    try {
        KeyPair keyPair = CertUtils.readKeyPairFromPemFile(internalKeyPath);
        csrBytes = CertUtils.generateCertRequest(keyPair.getPrivate(), keyPair.getPublic(), distinguishedName);
    } catch (IllegalArgumentException e) {
        throw new InvalidDistinguishedNameException(e);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | OperatorCreationException e) {
        throw new DeviationAwareRuntimeException(e);
    }
    return csrBytes;
}
Also used : KeyPair(java.security.KeyPair) DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 2 with DeviationAwareRuntimeException

use of org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException 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 3 with DeviationAwareRuntimeException

use of org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException in project X-Road by nordic-institute.

the class BackupService method generateBackup.

/**
 * Generate a new backup file
 * @return
 * @throws InterruptedException if the thread the backup process is interrupted and the backup fails. <b>The
 * interrupted thread has already been handled with so you can choose to ignore this exception if you
 * so please.</b>
 */
public BackupFile generateBackup() throws InterruptedException {
    SecurityServerId securityServerId = serverConfService.getSecurityServerId();
    String filename = generateBackupFileName();
    auditDataHelper.putBackupFilename(backupRepository.getFilePath(filename));
    String fullPath = backupRepository.getConfigurationBackupPath() + filename;
    String[] args = new String[] { "-s", securityServerId.toShortString(), "-f", fullPath };
    try {
        log.info("Run configuration backup with command '" + generateBackupScriptPath + " " + Arrays.toString(args) + "'");
        ExternalProcessRunner.ProcessResult processResult = externalProcessRunner.executeAndThrowOnFailure(generateBackupScriptPath, args);
        log.info(" --- Backup script console output - START --- ");
        log.info(String.join("\n", processResult.getProcessOutput()));
        log.info(" --- Backup script console output - END --- ");
    } catch (ProcessNotExecutableException | ProcessFailedException e) {
        throw new DeviationAwareRuntimeException(e, new ErrorDeviation(ERROR_BACKUP_GENERATION_FAILED));
    }
    Optional<BackupFile> backupFile = getBackup(filename);
    if (!backupFile.isPresent()) {
        throw new DeviationAwareRuntimeException(getFileNotFoundExceptionMessage(filename), new ErrorDeviation(ERROR_BACKUP_GENERATION_FAILED));
    }
    return backupFile.get();
}
Also used : BackupFile(org.niis.xroad.securityserver.restapi.dto.BackupFile) DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) SecurityServerId(ee.ria.xroad.common.identifier.SecurityServerId) ErrorDeviation(org.niis.xroad.restapi.exceptions.ErrorDeviation)

Example 4 with DeviationAwareRuntimeException

use of org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException in project X-Road by nordic-institute.

the class GlobalConfService method executeDownloadConfigurationFromAnchor.

/**
 * Sends an http request to configuration-client in order to trigger the downloading of the global conf
 * @throws ConfigurationDownloadException if the request succeeds but configuration-client returns an error
 * @throws DeviationAwareRuntimeException if the request fails
 */
public void executeDownloadConfigurationFromAnchor() throws ConfigurationDownloadException {
    log.info("Starting to download GlobalConf");
    ResponseEntity<String> response = null;
    try {
        response = restTemplate.getForEntity(downloadConfigurationAnchorUrl, String.class);
    } catch (RestClientException e) {
        throw new DeviationAwareRuntimeException(e, new ErrorDeviation(ERROR_GLOBAL_CONF_DOWNLOAD_REQUEST));
    }
    if (response != null && response.getStatusCode() != HttpStatus.OK) {
        throw new ConfigurationDownloadException(response.getBody());
    }
}
Also used : DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) RestClientException(org.springframework.web.client.RestClientException) ErrorDeviation(org.niis.xroad.restapi.exceptions.ErrorDeviation)

Example 5 with DeviationAwareRuntimeException

use of org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException in project X-Road by nordic-institute.

the class InitializationService method generateGPGKeyPair.

private void generateGPGKeyPair(String nameReal) throws InterruptedException {
    String[] args = new String[] { gpgHome, nameReal };
    try {
        log.info("Generationg GPG keypair with command '" + generateKeypairScriptPath + " " + Arrays.toString(args) + "'");
        ExternalProcessRunner.ProcessResult processResult = externalProcessRunner.executeAndThrowOnFailure(generateKeypairScriptPath, args);
        log.info(" --- Generate GPG keypair script console output - START --- ");
        log.info(String.join("\n", processResult.getProcessOutput()));
        log.info(" --- Generate GPG keypair script console output - END --- ");
    } catch (ProcessNotExecutableException | ProcessFailedException e) {
        throw new DeviationAwareRuntimeException(e, new ErrorDeviation(ERROR_GPG_KEY_GENERATION_FAILED));
    }
// todo check the keypair is really created? how?
}
Also used : DeviationAwareRuntimeException(org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException) ErrorDeviation(org.niis.xroad.restapi.exceptions.ErrorDeviation)

Aggregations

DeviationAwareRuntimeException (org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException)18 ErrorDeviation (org.niis.xroad.restapi.exceptions.ErrorDeviation)6 ClientId (ee.ria.xroad.common.identifier.ClientId)5 ClientType (ee.ria.xroad.common.conf.serverconf.model.ClientType)4 Date (java.util.Date)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 ServiceDescriptionType (ee.ria.xroad.common.conf.serverconf.model.ServiceDescriptionType)3 CodedException (ee.ria.xroad.common.CodedException)2 KeyInfo (ee.ria.xroad.signer.protocol.dto.KeyInfo)2 IOException (java.io.IOException)2 X509Certificate (java.security.cert.X509Certificate)2 JsonObject (com.google.gson.JsonObject)1 CertificateProfileInfo (ee.ria.xroad.common.certificateprofile.CertificateProfileInfo)1 DnFieldValue (ee.ria.xroad.common.certificateprofile.DnFieldValue)1 AccessRightType (ee.ria.xroad.common.conf.serverconf.model.AccessRightType)1 DescriptionType (ee.ria.xroad.common.conf.serverconf.model.DescriptionType)1 EndpointType (ee.ria.xroad.common.conf.serverconf.model.EndpointType)1 ServiceType (ee.ria.xroad.common.conf.serverconf.model.ServiceType)1 SecurityServerId (ee.ria.xroad.common.identifier.SecurityServerId)1 EncodedIdentifierValidator (ee.ria.xroad.common.validation.EncodedIdentifierValidator)1