Search in sources :

Example 11 with KeyInfo

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

the class KeyService method deleteKey.

/**
 * Deletes one key, and related CSRs and certificates. If the key is an authentication key with a registered
 * certificate and ignoreWarnings = false, an UnhandledWarningsException is thrown and the key is not deleted. If
 * ignoreWarnings = true, the authentication certificate is first unregistered, and the key and certificate are
 * deleted after that.
 * @param keyId
 * @param ignoreWarnings
 * @throws ActionNotPossibleException if delete was not possible for the key
 * @throws KeyNotFoundException if key with given id was not found
 * @throws GlobalConfOutdatedException if global conf was outdated
 * @throws UnhandledWarningsException if the key is an authentication key, it has a registered certificate,
 * and ignoreWarnings was false
 */
public void deleteKey(String keyId, Boolean ignoreWarnings) throws KeyNotFoundException, ActionNotPossibleException, GlobalConfOutdatedException, UnhandledWarningsException {
    TokenInfo tokenInfo = tokenService.getTokenForKeyId(keyId);
    auditDataHelper.put(tokenInfo);
    KeyInfo keyInfo = getKey(tokenInfo, keyId);
    auditDataHelper.put(keyInfo);
    // verify permissions
    if (keyInfo.getUsage() == null) {
        securityHelper.verifyAuthority("DELETE_KEY");
    } else if (keyInfo.getUsage() == KeyUsageInfo.AUTHENTICATION) {
        securityHelper.verifyAuthority("DELETE_AUTH_KEY");
    } else if (keyInfo.getUsage() == KeyUsageInfo.SIGNING) {
        securityHelper.verifyAuthority("DELETE_SIGN_KEY");
    }
    // verify that action is possible
    possibleActionsRuleEngine.requirePossibleKeyAction(PossibleActionEnum.DELETE, tokenInfo, keyInfo);
    // unregister possible auth certs
    if (keyInfo.getUsage() == KeyUsageInfo.AUTHENTICATION) {
        // get list of auth certs to be unregistered
        List<CertificateInfo> unregister = keyInfo.getCerts().stream().filter(this::shouldUnregister).collect(Collectors.toList());
        if (!unregister.isEmpty() && !ignoreWarnings) {
            throw new UnhandledWarningsException(new WarningDeviation(WARNING_AUTH_KEY_REGISTERED_CERT_DETECTED, keyId));
        }
        for (CertificateInfo certificateInfo : unregister) {
            unregisterAuthCert(certificateInfo);
        }
    }
    if (!auditDataHelper.dataIsForEvent(RestApiAuditEvent.DELETE_ORPHANS)) {
        auditEventHelper.changeRequestScopedEvent(RestApiAuditEvent.DELETE_KEY_FROM_TOKEN_AND_CONFIG);
    }
    // delete key needs to be done twice. First call deletes the certs & csrs
    try {
        signerProxyFacade.deleteKey(keyId, false);
        signerProxyFacade.deleteKey(keyId, true);
    } catch (CodedException e) {
        throw e;
    } catch (Exception other) {
        throw new SignerNotReachableException("delete key failed", other);
    }
}
Also used : WarningDeviation(org.niis.xroad.restapi.exceptions.WarningDeviation) CodedException(ee.ria.xroad.common.CodedException) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) UnhandledWarningsException(org.niis.xroad.restapi.service.UnhandledWarningsException) CertificateInfo(ee.ria.xroad.signer.protocol.dto.CertificateInfo) TokenInfo(ee.ria.xroad.signer.protocol.dto.TokenInfo) SignerNotReachableException(org.niis.xroad.restapi.service.SignerNotReachableException) NoSuchElementException(java.util.NoSuchElementException) UnhandledWarningsException(org.niis.xroad.restapi.service.UnhandledWarningsException) CodedException(ee.ria.xroad.common.CodedException) SignerNotReachableException(org.niis.xroad.restapi.service.SignerNotReachableException)

Example 12 with KeyInfo

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

the class TokenManagerMergeTest method shouldAddCertToCorrectKey.

@Test
public void shouldAddCertToCorrectKey() throws IOException {
    assertTrue("test setup failure", Files.exists(ADDED_KEY_CERT_FILE_PATH));
    final String testKeyId = "70726f6475636572";
    KeyInfo beforeKeyInfo = TokenManager.getKeyInfo(testKeyId);
    assertNotNull("test setup failure", beforeKeyInfo);
    final int beforeCount = beforeKeyInfo.getCerts().size();
    Files.copy(ADDED_KEY_CERT_FILE_PATH, testingFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    TokenManager.merge(addedCerts -> {
    });
    assertEquals("cert amount for key should be original + 1", beforeCount + 1, TokenManager.getKeyInfo(testKeyId).getCerts().size());
}
Also used : KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) Test(org.junit.Test)

Example 13 with KeyInfo

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

the class TokenManagerMergeTest method shouldMergeKeyAvailability.

@Test
public void shouldMergeKeyAvailability() throws Exception {
    final String testKeyId = "636f6e73756d6574";
    KeyInfo beforeKeyInfo = TokenManager.getKeyInfo(testKeyId);
    assertNotNull("test setup failure", beforeKeyInfo);
    assertFalse(TokenManager.isKeyAvailable(testKeyId));
    TokenManager.setKeyAvailable(testKeyId, true);
    Files.copy(ADDED_KEY_FILE_PATH, testingFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    TokenManager.merge(addedCerts -> {
    });
    assertTrue("key availability was not merged", TokenManager.isKeyAvailable(testKeyId));
}
Also used : KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) Test(org.junit.Test)

Example 14 with KeyInfo

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

the class HardwareTokenWorker method findCertificatesNotInConf.

private void findCertificatesNotInConf() throws Exception {
    log.trace("findCertificatesNotInConf()");
    try {
        List<X509PublicKeyCertificate> certsOnModule = findPublicKeyCertificates(activeSession);
        List<KeyInfo> existingKeys = listKeys(tokenId);
        for (X509PublicKeyCertificate certOnModule : certsOnModule) {
            byte[] certBytes = certOnModule.getValue().getByteArrayValue();
            for (KeyInfo key : existingKeys) {
                if (key.getId().equals(keyId(certOnModule)) && !hasCert(key, certBytes)) {
                    log.debug("Found new certificate for key '{}'", key.getId());
                    addCert(key.getId(), certBytes);
                    putCert(key.getId(), certOnModule);
                }
            }
        }
    } catch (Exception e) {
        if (e instanceof PKCS11Exception) {
            throw e;
        } else {
            log.error("Failed to find certificates not in conf", e);
        }
    }
}
Also used : PKCS11Exception(iaik.pkcs.pkcs11.wrapper.PKCS11Exception) TokenManager.getKeyInfo(ee.ria.xroad.signer.tokenmanager.TokenManager.getKeyInfo) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) X509PublicKeyCertificate(iaik.pkcs.pkcs11.objects.X509PublicKeyCertificate) PKCS11Exception(iaik.pkcs.pkcs11.wrapper.PKCS11Exception) CodedException(ee.ria.xroad.common.CodedException)

Example 15 with KeyInfo

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

the class HardwareTokenWorker method loadPrivateKeys.

private void loadPrivateKeys() throws Exception {
    if (activeSession == null) {
        return;
    }
    privateKeys.clear();
    List<RSAPrivateKey> keysOnToken = findPrivateKeys(activeSession, tokenType.getPrivKeyAttributes().getAllowedMechanisms());
    log.trace("Found {} private key(s) on token '{}'", keysOnToken.size(), getWorkerId());
    for (RSAPrivateKey keyOnToken : keysOnToken) {
        String keyId = keyId(keyOnToken);
        if (keyId == null) {
            log.debug("Ignoring private key with no ID");
            continue;
        }
        privateKeys.put(keyId, keyOnToken);
        log.trace("Private key '{}' added to token '{}'", keyId, getWorkerId());
        if (!hasKey(keyId)) {
            addKey(tokenId, keyId, null);
        } else {
            log.debug("Private key ({}) found in token '{}'", keyId, getWorkerId());
        }
        setKeyAvailable(keyId, true);
    }
    for (KeyInfo keyInfo : listKeys(tokenId)) {
        String keyId = keyInfo.getId();
        if (!privateKeys.containsKey(keyId)) {
            setKeyAvailable(keyId, false);
            log.debug("Private key ({}) not found in token '{}'", keyId, getWorkerId());
        }
    }
    if (privateKeys.isEmpty()) {
        log.warn("No private key(s) found in token '{}'", getWorkerId());
    }
}
Also used : TokenManager.getKeyInfo(ee.ria.xroad.signer.tokenmanager.TokenManager.getKeyInfo) KeyInfo(ee.ria.xroad.signer.protocol.dto.KeyInfo) RSAPrivateKey(iaik.pkcs.pkcs11.objects.RSAPrivateKey)

Aggregations

KeyInfo (ee.ria.xroad.signer.protocol.dto.KeyInfo)58 TokenInfo (ee.ria.xroad.signer.protocol.dto.TokenInfo)32 CertificateInfo (ee.ria.xroad.signer.protocol.dto.CertificateInfo)17 Test (org.junit.Test)16 CodedException (ee.ria.xroad.common.CodedException)12 TokenTestUtils (org.niis.xroad.securityserver.restapi.util.TokenTestUtils)12 CertRequestInfo (ee.ria.xroad.signer.protocol.dto.CertRequestInfo)9 TokenInfoAndKeyId (ee.ria.xroad.signer.protocol.dto.TokenInfoAndKeyId)9 Before (org.junit.Before)9 ArrayList (java.util.ArrayList)7 ClientId (ee.ria.xroad.common.identifier.ClientId)6 DeviationAwareRuntimeException (org.niis.xroad.restapi.exceptions.DeviationAwareRuntimeException)6 SignerNotReachableException (org.niis.xroad.restapi.service.SignerNotReachableException)6 KeyUsageInfo (ee.ria.xroad.signer.protocol.dto.KeyUsageInfo)5 HashMap (java.util.HashMap)5 ResourceNotFoundException (org.niis.xroad.restapi.openapi.ResourceNotFoundException)5 AuthKeyInfo (ee.ria.xroad.signer.protocol.dto.AuthKeyInfo)4 TokenManager.getKeyInfo (ee.ria.xroad.signer.tokenmanager.TokenManager.getKeyInfo)4 CertificateTestUtils (org.niis.xroad.securityserver.restapi.util.CertificateTestUtils)4 GeneratedCertRequestInfo (ee.ria.xroad.commonui.SignerProxy.GeneratedCertRequestInfo)3