Search in sources :

Example 6 with KeyEncryptor

use of com.quorum.tessera.config.keys.KeyEncryptor in project tessera by ConsenSys.

the class EnclaveFactoryImpl method createServer.

static Enclave createServer(Config config) {
    LOGGER.info("Creating enclave server");
    EncryptorConfig encryptorConfig = config.getEncryptor();
    EncryptorFactory encryptorFactory = EncryptorFactory.newFactory(encryptorConfig.getType().name());
    Encryptor encryptor = encryptorFactory.create(encryptorConfig.getProperties());
    KeyEncryptor keyEncryptor = KeyEncryptorFactory.newFactory().create(encryptorConfig);
    final KeyPairConverter keyPairConverter = new KeyPairConverter(config, new EnvironmentVariableProvider());
    final Collection<KeyPair> keys = keyPairConverter.convert(config.getKeys().getKeyData().stream().map(kd -> KeyDataUtil.unmarshal(kd, keyEncryptor)).collect(Collectors.toList()));
    final Collection<PublicKey> forwardKeys = keyPairConverter.convert(config.getAlwaysSendTo());
    LOGGER.debug("Creating enclave");
    Enclave enclave = new EnclaveImpl(encryptor, new KeyManagerImpl(keys, forwardKeys));
    LOGGER.debug("Created enclave {}", enclave);
    return enclave;
}
Also used : EncryptorConfig(com.quorum.tessera.config.EncryptorConfig) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) EnvironmentVariableProvider(com.quorum.tessera.config.util.EnvironmentVariableProvider) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) KeyEncryptorFactory(com.quorum.tessera.config.keys.KeyEncryptorFactory)

Example 7 with KeyEncryptor

use of com.quorum.tessera.config.keys.KeyEncryptor in project tessera by ConsenSys.

the class CliKeyPasswordResolverTest method lockedKeyWithInvalidPasswordRequestsPassword.

@Test
public void lockedKeyWithInvalidPasswordRequestsPassword() {
    when(passwordReader.readPasswordFromConsole()).thenReturn("a".toCharArray());
    final char[] validPassword = "a".toCharArray();
    final char[] invalidPassword = "invalidPassword".toCharArray();
    byte[] privateKeyBytes = Base64.getDecoder().decode("w+itzh2vfuGjiGYEVJtqpiJVUmI5vGUK4CzMErxa+GY=");
    final PrivateKey unlockedKey = PrivateKey.from(privateKeyBytes);
    final KeyDataConfig privKeyDataConfig = new KeyDataConfig(new PrivateKeyData("Wl+xSyXVuuqzpvznOS7dOobhcn4C5auxkFRi7yLtgtA=", "yb7M8aRJzgxoJM2NecAPcmSVWDW1tRjv", "MIqkFlgR2BWEpx2U0rObGg==", "Gtvp1t6XZEiFVyaE/LHiP1+yvOIBBoiOL+bKeqcKgpiNt4j1oDDoqCC47UJpmQRC", new ArgonOptions("i", 10, 1048576, 4)), PrivateKeyType.LOCKED);
    KeyEncryptor keyEncryptor = mock(KeyEncryptor.class);
    when(keyEncryptor.decryptPrivateKey(any(PrivateKeyData.class), eq(invalidPassword))).thenThrow(new EncryptorException("decrypt failed"));
    when(keyEncryptor.decryptPrivateKey(any(PrivateKeyData.class), eq(validPassword))).thenReturn(unlockedKey);
    KeyData keyPair = new KeyData();
    keyPair.setPublicKey("public");
    keyPair.setConfig(privKeyDataConfig);
    this.cliKeyPasswordResolver.getSingleKeyPassword(0, keyPair, keyEncryptor);
    assertThat(systemOutRule.getLog()).containsOnlyOnce("Password for key[0] missing or invalid.\nAttempt 1 of 2. Enter a password for the key");
}
Also used : PrivateKey(com.quorum.tessera.encryption.PrivateKey) EncryptorException(com.quorum.tessera.encryption.EncryptorException) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) Test(org.junit.Test)

Example 8 with KeyEncryptor

use of com.quorum.tessera.config.keys.KeyEncryptor in project tessera by ConsenSys.

the class DefaultKeyGeneratorFactory method create.

@Override
public KeyGenerator create(KeyVaultConfig keyVaultConfig, EncryptorConfig encryptorConfig) {
    Objects.requireNonNull(encryptorConfig, "No encryptor config defined. ");
    final EncryptorFactory encryptorFactory = EncryptorFactory.newFactory(encryptorConfig.getType().name());
    final Encryptor encryptor = encryptorFactory.create(encryptorConfig.getProperties());
    if (keyVaultConfig != null) {
        final KeyVaultServiceFactory keyVaultServiceFactory = KeyVaultServiceFactory.getInstance(keyVaultConfig.getKeyVaultType());
        final Config config = new Config();
        final KeyConfiguration keyConfiguration = new KeyConfiguration();
        if (keyVaultConfig.getKeyVaultType().equals(KeyVaultType.AZURE)) {
            keyConfiguration.addKeyVaultConfig(keyVaultConfig);
            config.setKeys(keyConfiguration);
            final KeyVaultService keyVaultService = keyVaultServiceFactory.create(config, new EnvironmentVariableProvider());
            return new AzureVaultKeyGenerator(encryptor, keyVaultService);
        } else if (keyVaultConfig.getKeyVaultType().equals(KeyVaultType.AWS)) {
            if (!(keyVaultConfig instanceof DefaultKeyVaultConfig)) {
                throw new IllegalArgumentException("AWS key vault config not instance of DefaultKeyVaultConfig");
            }
            keyConfiguration.addKeyVaultConfig(keyVaultConfig);
            config.setKeys(keyConfiguration);
            final KeyVaultService keyVaultService = keyVaultServiceFactory.create(config, new EnvironmentVariableProvider());
            return new AWSSecretManagerKeyGenerator(encryptor, keyVaultService);
        } else {
            keyConfiguration.addKeyVaultConfig(keyVaultConfig);
            config.setKeys(keyConfiguration);
            final KeyVaultService keyVaultService = keyVaultServiceFactory.create(config, new EnvironmentVariableProvider());
            return new HashicorpVaultKeyGenerator(encryptor, keyVaultService);
        }
    }
    KeyEncryptor keyEncyptor = KeyEncryptorFactory.newFactory().create(encryptorConfig);
    return new FileKeyGenerator(encryptor, keyEncyptor, PasswordReaderFactory.create());
}
Also used : KeyVaultService(com.quorum.tessera.key.vault.KeyVaultService) Encryptor(com.quorum.tessera.encryption.Encryptor) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) EnvironmentVariableProvider(com.quorum.tessera.config.util.EnvironmentVariableProvider) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) KeyVaultServiceFactory(com.quorum.tessera.key.vault.KeyVaultServiceFactory) KeyEncryptorFactory(com.quorum.tessera.config.keys.KeyEncryptorFactory) EncryptorFactory(com.quorum.tessera.encryption.EncryptorFactory)

Example 9 with KeyEncryptor

use of com.quorum.tessera.config.keys.KeyEncryptor in project tessera by ConsenSys.

the class RuntimeContextProvider method provider.

public static RuntimeContext provider() {
    LOGGER.debug("Providing RuntimeContext");
    RuntimeContextHolder contextHolder = RuntimeContextHolder.INSTANCE;
    if (contextHolder.getContext().isPresent()) {
        LOGGER.debug("Found stored RuntimeContext instance");
        return contextHolder.getContext().get();
    }
    Config config = ConfigFactory.create().getConfig();
    EncryptorConfig encryptorConfig = Optional.ofNullable(config.getEncryptor()).orElse(new EncryptorConfig() {

        {
            setType(EncryptorType.NACL);
        }
    });
    KeyEncryptor keyEncryptor = KeyEncryptorFactory.newFactory().create(encryptorConfig);
    final KeyVaultConfigValidations vaultConfigValidation = KeyVaultConfigValidations.create();
    final RuntimeContextBuilder runtimeContextBuilder = RuntimeContextBuilder.create();
    if (Objects.nonNull(config.getKeys())) {
        List<ConfigKeyPair> configKeyPairs = config.getKeys().getKeyData().stream().map(o -> KeyDataUtil.unmarshal(o, keyEncryptor)).collect(Collectors.toList());
        Set<ConstraintViolation<?>> violations = vaultConfigValidation.validate(config.getKeys(), configKeyPairs);
        if (!violations.isEmpty()) {
            LOGGER.debug("Constraint violations {}", violations);
            throw new ConstraintViolationException(violations);
        }
        final Enclave enclave = Enclave.create();
        runtimeContextBuilder.withKeys(enclave.getPublicKeys());
    }
    List<ServerConfig> servers = config.getServerConfigs();
    ServerConfig p2pServerContext = servers.stream().filter(s -> s.getApp() == AppType.P2P).findFirst().orElseThrow(() -> new IllegalStateException("No P2P server configured"));
    Client p2pClient = RestClientFactory.create().buildFrom(p2pServerContext);
    List<PublicKey> alwaysSendTo = Stream.of(config).map(Config::getAlwaysSendTo).filter(Objects::nonNull).flatMap(List::stream).map(Base64.getDecoder()::decode).map(PublicKey::from).collect(Collectors.toList());
    RuntimeContext context = runtimeContextBuilder.withP2pServerUri(config.getP2PServerConfig().getServerUri()).withP2pClient(p2pClient).withKeyEncryptor(keyEncryptor).withDisablePeerDiscovery(config.isDisablePeerDiscovery()).withRemoteKeyValidation(config.getFeatures().isEnableRemoteKeyValidation()).withEnhancedPrivacy(config.getFeatures().isEnablePrivacyEnhancements()).withPeers(config.getPeers().stream().map(Peer::getUrl).map(URI::create).collect(Collectors.toList())).withAlwaysSendTo(alwaysSendTo).withUseWhiteList(config.isUseWhiteList()).withRecoveryMode(config.isRecoveryMode()).withMultiplePrivateStates(config.getFeatures().isEnableMultiplePrivateStates()).withClientMode(config.getClientMode()).build();
    contextHolder.setContext(context);
    return context;
}
Also used : ConstraintViolation(jakarta.validation.ConstraintViolation) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) PublicKey(com.quorum.tessera.encryption.PublicKey) Client(jakarta.ws.rs.client.Client) java.util(java.util) Logger(org.slf4j.Logger) KeyEncryptorFactory(com.quorum.tessera.config.keys.KeyEncryptorFactory) LoggerFactory(org.slf4j.LoggerFactory) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) ConstraintViolationException(jakarta.validation.ConstraintViolationException) Collectors(java.util.stream.Collectors) RestClientFactory(com.quorum.tessera.context.RestClientFactory) KeyDataUtil(com.quorum.tessera.config.util.KeyDataUtil) Stream(java.util.stream.Stream) com.quorum.tessera.config(com.quorum.tessera.config) RuntimeContext(com.quorum.tessera.context.RuntimeContext) Enclave(com.quorum.tessera.enclave.Enclave) URI(java.net.URI) KeyVaultConfigValidations(com.quorum.tessera.context.KeyVaultConfigValidations) KeyVaultConfigValidations(com.quorum.tessera.context.KeyVaultConfigValidations) PublicKey(com.quorum.tessera.encryption.PublicKey) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) URI(java.net.URI) Enclave(com.quorum.tessera.enclave.Enclave) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException) Client(jakarta.ws.rs.client.Client) RuntimeContext(com.quorum.tessera.context.RuntimeContext)

Example 10 with KeyEncryptor

use of com.quorum.tessera.config.keys.KeyEncryptor in project tessera by ConsenSys.

the class PicoCliDelegateTest method keygenUpdateConfig.

@Test
public void keygenUpdateConfig() throws Exception {
    Path publicKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
    Path privateKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
    Files.write(privateKeyPath, Arrays.asList("SOMEDATA"));
    Files.write(publicKeyPath, Arrays.asList("SOMEDATA"));
    KeyEncryptor keyEncryptor = mock(KeyEncryptor.class);
    FilesystemKeyPair keypair = new FilesystemKeyPair(publicKeyPath, privateKeyPath, keyEncryptor);
    when(keyGenerator.generate(anyString(), eq(null), eq(null))).thenReturn(keypair);
    Path unixSocketPath = Files.createTempFile(UUID.randomUUID().toString(), ".ipc");
    Map<String, Object> params = new HashMap<>();
    params.put("unixSocketPath", unixSocketPath.toString());
    Path configFile = Paths.get(getClass().getResource("/keygen-sample.json").toURI());
    Path keyOutputPath = configFile.resolveSibling(UUID.randomUUID().toString());
    Path configOutputPath = configFile.resolveSibling(UUID.randomUUID().toString() + ".json");
    assertThat(Files.exists(configOutputPath)).isFalse();
    CliResult result = cliDelegate.execute("-keygen", "-filename", keyOutputPath.toString(), "-output", configOutputPath.toString(), "-configfile", configFile.toString());
    assertThat(result).isNotNull();
    assertThat(result.getStatus()).isEqualTo(0);
    assertThat(result.getConfig()).isNotNull();
    assertThat(result.isSuppressStartup()).isTrue();
    assertThat(Files.exists(configOutputPath)).isTrue();
    configOutputPath.toFile().deleteOnExit();
    verify(keyGenerator).generate(anyString(), eq(null), eq(null));
    verifyNoMoreInteractions(keyGenerator);
    try {
        cliDelegate.execute("-keygen", "-filename", UUID.randomUUID().toString(), "-output", configOutputPath.toString(), "-configfile", configFile.toString());
        failBecauseExceptionWasNotThrown(Exception.class);
    } catch (Exception ex) {
        assertThat(ex).isInstanceOf(UncheckedIOException.class);
        assertThat(ex.getCause()).isExactlyInstanceOf(FileAlreadyExistsException.class);
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FilesystemKeyPair(com.quorum.tessera.config.keypairs.FilesystemKeyPair) HashMap(java.util.HashMap) CliResult(com.quorum.tessera.cli.CliResult) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) UncheckedIOException(java.io.UncheckedIOException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CliException(com.quorum.tessera.cli.CliException) ConstraintViolationException(jakarta.validation.ConstraintViolationException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) UncheckedIOException(java.io.UncheckedIOException) Test(org.junit.Test)

Aggregations

KeyEncryptor (com.quorum.tessera.config.keys.KeyEncryptor)20 Test (org.junit.Test)15 KeyData (com.quorum.tessera.config.KeyData)10 PrivateKeyData (com.quorum.tessera.config.PrivateKeyData)10 Path (java.nio.file.Path)5 FilesystemKeyPair (com.quorum.tessera.config.keypairs.FilesystemKeyPair)4 KeyEncryptorFactory (com.quorum.tessera.config.keys.KeyEncryptorFactory)4 CliResult (com.quorum.tessera.cli.CliResult)3 KeyDataConfig (com.quorum.tessera.config.KeyDataConfig)3 ConstraintViolationException (jakarta.validation.ConstraintViolationException)3 HashMap (java.util.HashMap)3 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)3 CliException (com.quorum.tessera.cli.CliException)2 EncryptorConfig (com.quorum.tessera.config.EncryptorConfig)2 ConfigKeyPair (com.quorum.tessera.config.keypairs.ConfigKeyPair)2 EnvironmentVariableProvider (com.quorum.tessera.config.util.EnvironmentVariableProvider)2 KeyDataUtil (com.quorum.tessera.config.util.KeyDataUtil)2 Encryptor (com.quorum.tessera.encryption.Encryptor)2 PublicKey (com.quorum.tessera.encryption.PublicKey)2 Client (jakarta.ws.rs.client.Client)2