public static void Init(VaultConfig config, AcmeClient client)
        {
            client.Init();

            if (config.GetInitialDirectory)
                client.GetDirectory(config.UseRelativeInitialDirectory);
        }
        public void can_set()
        {
            var         host         = "localhost:8080";
            var         scheme       = "http";
            var         path         = "api/v2";
            var         token        = "12345";
            var         vaultId      = "vaultId";
            var         vaultKeyFile = "vault_key";
            VaultConfig config       = new VaultConfig();

            config.Enabled.Should().BeFalse();
            config.Enabled = true;
            config.Enabled.Should().BeTrue();
            config.Enabled = false;
            config.Enabled.Should().BeFalse();
            config.Host = host;
            config.Host.Should().Be(host);
            config.Scheme = scheme;
            config.Scheme.Should().Be(scheme);
            config.Path = path;
            config.Path.Should().Be(path);
            config.Token = token;
            config.Token.Should().Be(token);
            config.VaultId = vaultId;
            config.VaultId.Should().Be(vaultId);
            config.VaultKeyFile = vaultKeyFile;
            config.VaultKeyFile.Should().Be(vaultKeyFile);
        }
        public static AcmeClient GetClient(VaultConfig config, RegistrationInfo reg)
        {
            var c = GetClient(config);

            c.Signer = GetSigner(reg.SignerProvider);
            c.Signer.Init();
            c.Registration = reg.Registration;

            if (reg.SignerState != null)
            {
                using (var s = new MemoryStream(Convert.FromBase64String(
                        reg.SignerState)))
                {
                    c.Signer.Load(s);
                }
            }
            else
            {
                using (var s = new MemoryStream())
                {
                    c.Signer.Save(s);
                    reg.SignerState = Convert.ToBase64String(s.ToArray());
                }
            }

            return c;
        }
        public static AcmeClient GetClient(VaultConfig config, RegistrationInfo reg)
        {
            var c = GetClient(config);

            c.Signer = GetSigner(reg.SignerProvider);
            c.Signer.Init();
            c.Registration = reg.Registration;

            if (reg.SignerState != null)
            {
                using (var s = new MemoryStream(Convert.FromBase64String(
                                                    reg.SignerState)))
                {
                    c.Signer.Load(s);
                }
            }
            else
            {
                using (var s = new MemoryStream())
                {
                    c.Signer.Save(s);
                    reg.SignerState = Convert.ToBase64String(s.ToArray());
                }
            }

            return(c);
        }
Beispiel #5
0
        public async Task SetUp()
        {
            VaultConfig config = new VaultConfig();

            config.Host   = "localhost:8082";
            config.Scheme = "http";
            config.Path   = "api/v1";
            config.Token  = $"bearer  {TestContext.Parameters["token"]}";

            _vaultService = new VaultService(
                config,
                new TestLogManager(LogLevel.Trace)
                );

            provide.Model.Vault.Vault vault = new provide.Model.Vault.Vault();
            vault.Name        = "Name";
            vault.Description = "Description";

            // Create a single Vault instance
            provide.Model.Vault.Vault response = await _vaultService.CreateVault(vault);

            response.Id.Should().NotBeNull();

            _vaultId = response.Id !.Value;
            _wallet  = new VaultWallet(_vaultService, _vaultId.ToString(), LimboLogs.Instance);
        }
Beispiel #6
0
        protected override void ProcessRecord()
        {
            var baseUri = BaseUri;

            if (string.IsNullOrEmpty(baseUri))
            {
                if (!string.IsNullOrEmpty(BaseService) &&
                    WELL_KNOWN_BASE_SERVICES.ContainsKey(BaseService))
                {
                    baseUri = WELL_KNOWN_BASE_SERVICES[BaseService];
                }
                else
                {
                    throw new PSInvalidOperationException("either a base service or URI is required");
                }
            }

            using (var vp = GetVaultProvider(VaultProfile))
            {
                vp.InitStorage(Force);
                var v = new VaultConfig
                {
                    Id              = EntityHelper.NewId(),
                    Alias           = Alias,
                    Label           = Label,
                    Memo            = Memo,
                    BaseService     = BaseService,
                    BaseUri         = baseUri,
                    ServerDirectory = new AcmeServerDirectory()
                };

                vp.SaveVault(v);
            }
        }
        public static void Init(VaultConfig config, AcmeClient client)
        {
            client.Init();

            if (config.GetInitialDirectory)
            {
                client.GetDirectory(config.UseRelativeInitialDirectory);
            }
        }
Beispiel #8
0
 /// <inheritdoc/>
 public ApiConfig(IConfiguration configuration) :
     base(configuration)
 {
     _twin      = new TwinConfig(configuration);
     _registry  = new RegistryConfig(configuration);
     _vault     = new VaultConfig(configuration);
     _history   = new HistoryConfig(configuration);
     _publisher = new PublisherConfig(configuration);
     _events    = new EventsConfig(configuration);
 }
Beispiel #9
0
        public AuthConfig GetAuthConfig(VaultConfig vaultConfig)
        {
            if (vaultConfig == null)
            {
                throw new ArgumentNullException(nameof(vaultConfig));
            }

            return(Configuration.Authentication
                   .FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Key, vaultConfig.Url) || Regex.IsMatch(vaultConfig.Url, x.Key))
                   .Value);
        }
Beispiel #10
0
 /// <inheritdoc/>
 public ApiConfig(IConfiguration configuration) :
     base(configuration)
 {
     _twin      = new TwinConfig(configuration);
     _registry  = new RegistryConfig(configuration);
     _jobs      = new JobsServiceConfig(configuration);
     _vault     = new VaultConfig(configuration);
     _history   = new HistoryConfig(configuration);
     _publisher = new PublisherConfig(configuration);
     _signalR   = new SignalRClientConfig(configuration);
 }
Beispiel #11
0
        public CertificateStorageTestFixture()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("testsettings.json", false, true)
                          .AddJsonFile("testsettings.Development.json", true, true)
                          .AddFromDotEnvFile()
                          .AddEnvironmentVariables();
            var configuration = builder.Build();

            _serviceConfig = new VaultConfig(configuration);
            _clientConfig  = new ClientConfig(configuration);
            _vaultConfig   = new KeyVaultConfig(configuration);
            _logger        = SerilogTestLogger.Create <CertificateStorageTestFixture>();
            if (!InvalidConfiguration())
            {
                RandomGenerator = new ApplicationTestDataGenerator();
                var timeid = DateTime.UtcNow.ToFileTimeUtc() / 1000 % 10000;

                // Create registry
                GroupId = "test";

                Registry = new TrustGroupDatabase(new ItemContainerFactory(
                                                      new CosmosDbServiceClient(_serviceConfig, _logger)), _logger);

                // Registry.CreateGroupAsync(new CertificateGroupCreateRequestModel {
                //     Name = "GroupTestIssuerCA" + timeid.ToString(),
                //     SubjectName = "CN=OPC Vault Cert Request Test CA, O=Microsoft, OU=Azure IoT",
                //     CertificateType = CertificateType.ApplicationInstanceCertificate
                // }, CancellationToken.None).Result.Id

                // Create client
                var serializer = new KeyVaultKeyHandleSerializer();
                var repo       = new CertificateDatabase(new ItemContainerFactory(
                                                             new CosmosDbServiceClient(_serviceConfig, _logger)), serializer);
                _keyVaultServiceClient = new KeyVaultServiceClient(_vaultConfig,
                                                                   new AppAuthenticationProvider(_clientConfig), repo, _logger);

                // Create services
                Services = new RequestDatabase(
                    repo,
                    _keyVaultServiceClient,  // keystore
                    Registry,
                    _keyVaultServiceClient,  // issuer
                    new CertificateRevoker(repo, _keyVaultServiceClient, _keyVaultServiceClient),
                    new EntityExtensionFactory(_keyVaultServiceClient),
                    _serviceConfig);

                // Clear
                _keyVaultServiceClient.PurgeAsync("groups", GroupId, CancellationToken.None).Wait();
            }
            KeyVaultInitOk = false;
        }
Beispiel #12
0
        public void Can_Initialize_VaultTxSender_without_exceptions()
        {
            var vaultConfig = new VaultConfig();

            vaultConfig.VaultId = "1b16996e-3595-4985-816c-043345d22f8c";
            var _vaultService = new VaultService(vaultConfig, LimboLogs.Instance);

            IVaultWallet wallet      = new VaultWallet(_vaultService, vaultConfig.VaultId, LimboLogs.Instance);
            ITxSigner    vaultSigner = new VaultTxSigner(wallet, 1);

            Assert.DoesNotThrow(() => { new VaultTxSender(vaultSigner, vaultConfig, 1); });
        }
Beispiel #13
0
        public void Initialize()
        {
            var config = new VaultConfig();

            _keyStoreConfig             = new KeyStoreConfig();
            _keyStoreIOSettingsProvider = new VaultKeyStoreIOSettingsProvider(config);

            ILogManager logger = LimboLogs.Instance;

            _serializer   = new EthereumJsonSerializer();
            _cryptoRandom = new CryptoRandom();
            _store        = new FileKeyStore(_keyStoreConfig, _serializer, new AesEncrypter(_keyStoreConfig, logger), _cryptoRandom, logger, _keyStoreIOSettingsProvider);
        }
        public static AcmeClient GetClient(VaultConfig Config)
        {
            var p = Config.Proxy;
            var _Client = new AcmeClient();

            _Client.RootUrl = new Uri(Config.BaseURI);
            _Client.Directory = Config.ServerDirectory;

            if (Config.Proxy != null)
                _Client.Proxy = Config.Proxy.GetWebProxy();

            return _Client;
        }
Beispiel #15
0
 /// <summary>
 /// Configuration constructor
 /// </summary>
 /// <param name="configuration"></param>
 internal Config(IConfiguration configuration) :
     base(configuration)
 {
     _vault    = new VaultConfig(configuration);
     _keyVault = new KeyVaultConfig(configuration);
     _cosmos   = new CosmosDbConfig(configuration);
     _openApi  = new OpenApiConfig(configuration);
     _host     = new WebHostConfig(configuration);
     _cors     = new CorsConfig(configuration);
     _sb       = new ServiceBusConfig(configuration);
     _hub      = new IoTHubConfig(configuration);
     _registry = new RegistryConfig(configuration);
     _fh       = new ForwardedHeadersConfig(configuration);
 }
Beispiel #16
0
 public Config(NetworkConfig network, GenesisConfig genesis, RpcConfig rpc, VaultConfig vault,
               StorageConfig storage, BlockchainConfig blockchain, HardforkConfig hardfork, VersionConfig version,
               CacheConfig cache)
 {
     Network       = network;
     Genesis       = genesis;
     Rpc           = rpc;
     Vault         = vault;
     Storage       = storage;
     Blockchain    = blockchain;
     Hardfork      = hardfork;
     ConfigVersion = version;
     Cache         = cache;
 }
Beispiel #17
0
 /// <summary>
 /// Configuration constructor
 /// </summary>
 /// <param name="configuration"></param>
 internal Config(IConfigurationRoot configuration) :
     base(configuration)
 {
     _vault    = new VaultConfig(configuration);
     _keyVault = new KeyVaultConfig(configuration);
     _cosmos   = new CosmosDbConfig(configuration);
     _swagger  = new SwaggerConfig(configuration);
     _auth     = new AuthConfig(configuration);
     _cors     = new CorsConfig(configuration);
     _sb       = new ServiceBusConfig(configuration);
     _hub      = new IoTHubConfig(configuration);
     _registry = new ApiConfig(configuration);
     _ai       = new ApplicationInsightsConfig(configuration);
 }
        public static AcmeClient GetClient(VaultConfig Config)
        {
            var p       = Config.Proxy;
            var _Client = new AcmeClient();

            _Client.RootUrl   = new Uri(Config.BaseURI);
            _Client.Directory = Config.ServerDirectory;

            if (Config.Proxy != null)
            {
                _Client.Proxy = Config.Proxy.GetWebProxy();
            }

            return(_Client);
        }
        protected override void ProcessRecord()
        {
            using (var vp = GetVaultProvider())
            {
                vp.InitStorage(Force);
                var v = new VaultConfig
                {
                    Id = EntityHelper.NewId(),
                    Alias = Alias,
                    Label = Label,
                    Memo = Memo,
                    BaseURI = BaseURI,
                    ServerDirectory = new AcmeServerDirectory()
                };

                vp.SaveVault(v);
            }
        }
        public void defaults_are_fine()
        {
            VaultConfig config  = new VaultConfig();
            var         host    = ((ConfigItemAttribute)(typeof(IVaultConfig).GetProperty("Host").GetCustomAttribute(typeof(ConfigItemAttribute)))).DefaultValue;
            var         scheme  = ((ConfigItemAttribute)(typeof(IVaultConfig).GetProperty("Scheme").GetCustomAttribute(typeof(ConfigItemAttribute)))).DefaultValue;
            var         path    = ((ConfigItemAttribute)(typeof(IVaultConfig).GetProperty("Path").GetCustomAttribute(typeof(ConfigItemAttribute)))).DefaultValue;
            var         token   = ((ConfigItemAttribute)(typeof(IVaultConfig).GetProperty("Token").GetCustomAttribute(typeof(ConfigItemAttribute)))).DefaultValue;
            var         vaultId = ((ConfigItemAttribute)(typeof(IVaultConfig).GetProperty("VaultId").GetCustomAttribute(typeof(ConfigItemAttribute)))).DefaultValue;

            config.Host   = "vault.provide.services";
            config.Scheme = "https";
            config.Path   = "api/v1";
            config.Host.Should().Be(host);
            config.Scheme.Should().Be(scheme);
            config.Path.Should().Be(path);
            config.Token.Should().BeNull();
            config.VaultId.Should().BeNull();
        }
        protected override void ProcessRecord()
        {
            using (var vp = GetVaultProvider())
            {
                vp.InitStorage(Force);
                var v = new VaultConfig
                {
                    Id              = EntityHelper.NewId(),
                    Alias           = Alias,
                    Label           = Label,
                    Memo            = Memo,
                    BaseURI         = BaseURI,
                    ServerDirectory = new AcmeServerDirectory()
                };

                vp.SaveVault(v);
            }
        }
Beispiel #22
0
        public CertificateAuthorityTestFixture()
        {
            RandomGenerator = new ApplicationTestDataGenerator(kRandomStart);
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("testsettings.json", false, true)
                          .AddJsonFile("testsettings.Development.json", true, true)
                          .AddFromDotEnvFile()
                          .AddEnvironmentVariables();
            var configuration = builder.Build();

            _serviceConfig = new VaultConfig(configuration);
            _clientConfig  = new ClientConfig(configuration);
            _vaultConfig   = new KeyVaultConfig(configuration);
            _logger        = SerilogTestLogger.Create <CertificateAuthorityTestFixture>();
            if (!InvalidConfiguration())
            {
                ApplicationsDatabase = new ApplicationRegistry(new ApplicationDatabase(
                                                                   new ItemContainerFactory(new CosmosDbServiceClient(_serviceConfig, _logger)), _logger),
                                                               new EndpointRegistryStub(), new EndpointRegistryStub(),
                                                               new ApplicationEventBrokerStub(), _logger);

                var timeid = DateTime.UtcNow.ToFileTimeUtc() / 1000 % 10000;

                // Create group registry
                Registry = new TrustGroupDatabase(new ItemContainerFactory(
                                                      new CosmosDbServiceClient(_serviceConfig, _logger)), _logger);
                _groupId = Registry.CreateGroupAsync(new Models.TrustGroupRegistrationRequestModel {
                    Name        = "CertReqConfig" + timeid.ToString(),
                    SubjectName = "CN=OPC Vault Cert Request Test CA, O=Microsoft, OU=Azure IoT",
                }).Result.Id;

                // Create client
                var serializer = new KeyVaultKeyHandleSerializer();
                var repo       = new CertificateDatabase(new ItemContainerFactory(
                                                             new CosmosDbServiceClient(_serviceConfig, _logger)), serializer);
                _keyVaultServiceClient = new KeyVaultServiceClient(_vaultConfig,
                                                                   new AppAuthenticationProvider(_clientConfig), repo, _logger);

                // Create services
                _keyVaultCertificateGroup = new RequestDatabase(
                    repo,
                    _keyVaultServiceClient,  // keystore
                    Registry,
                    _keyVaultServiceClient,  // issuer
                    new CertificateRevoker(repo, _keyVaultServiceClient, _keyVaultServiceClient),
                    new EntityExtensionFactory(_keyVaultServiceClient),
                    _serviceConfig);
                _keyVaultServiceClient.PurgeAsync("groups", _groupId, CancellationToken.None).Wait();
                Services = _keyVaultCertificateGroup;

                CertificateAuthority = new CertificateRequestManager(ApplicationsDatabase, Services,
                                                                     new ItemContainerFactory(new CosmosDbServiceClient(_serviceConfig, _logger)), _logger);
                RequestManagement = (IRequestManagement)CertificateAuthority;

                // create test set
                ApplicationTestSet = new List <ApplicationTestData>();
                for (var i = 0; i < kTestSetSize; i++)
                {
                    var randomApp = RandomGenerator.RandomApplicationTestData();
                    ApplicationTestSet.Add(randomApp);
                }
            }
            RegistrationOk = false;
        }
Beispiel #23
0
        public static void CloudKeygen(int n, int f, IEnumerable <string> ips, ushort basePort, ushort target, ulong chainId, ulong cycleDuration, ulong validatorsCount, string networkName,
                                       string feedAddress, string feedBalance, string stakeAmount, IEnumerable <ulong> hardforks)
        {
            if (n <= 3 * f)
            {
                throw new Exception("N must be >= 3 * F + 1");
            }
            var tpkeKeyGen = new Crypto.TPKE.TrustedKeyGen(n, f);
            var tpkePubKey = tpkeKeyGen.GetPubKey();

            var sigKeyGen  = new Crypto.ThresholdSignature.TrustedKeyGen(n, f);
            var privShares = sigKeyGen.GetPrivateShares().ToArray();
            var pubShares  = sigKeyGen.GetPrivateShares()
                             .Select(s => s.GetPublicKeyShare())
                             .Select(s => s.ToHex())
                             .ToArray();

            var ecdsaPrivateKeys = new string[n];
            var ecdsaPublicKeys  = new string[n];
            var addresses        = new string[n];
            var crypto           = CryptoProvider.GetCrypto();

            for (var i = 0; i < n; ++i)
            {
                ecdsaPrivateKeys[i] = crypto.GenerateRandomBytes(32).ToHex(false);
                ecdsaPublicKeys[i]  = crypto.ComputePublicKey(ecdsaPrivateKeys[i].HexToBytes(), true).ToHex(false);
                addresses[i]        = ecdsaPrivateKeys[i].HexToBytes().ToPrivateKey().GetPublicKey().GetAddress().ToHex();
            }

            var hubPublicKeys            = new string[n];
            var serializedHubPrivateKeys = new string[n];

            for (var i = 0; i < n; ++i)
            {
                (serializedHubPrivateKeys[i], hubPublicKeys[i]) = PrivateWallet.GenerateHubKey();
            }

            var bootstraps = ips
                             .Zip(hubPublicKeys, (ip, id) => $"{id}@{ip}")
                             .Select((x, i) => $"{x}:{41011 + i}")
                             .ToArray();

            var peers = ecdsaPublicKeys.ToArray();

            for (var i = 0; i < n; ++i)
            {
                var net = new NetworkConfig
                {
                    Peers              = peers,
                    MaxPeers           = 100,
                    ForceIPv6          = false,
                    BootstrapAddresses = bootstraps,
                    HubLogLevel        = "Trace",
                    HubMetricsPort     = basePort + 2,
                    NetworkName        = networkName,
                    ChainId            = (int)chainId,
                    CycleDuration      = cycleDuration,
                    ValidatorsCount    = validatorsCount,
                };
                var genesis = new GenesisConfig(tpkePubKey.ToHex(), "5.000000000000000000", "0.000000100000000000")
                {
                    Balances = new Dictionary <string, string>
                    {
                        {
                            feedAddress, feedBalance
                        }
                    },
                    Validators = Enumerable.Range(0, n).Select(j => new ValidatorInfo(
                                                                   ecdsaPublicKeys[j], pubShares[j], feedAddress, stakeAmount
                                                                   )).ToList()
                };
                for (var j = 0; j < n; ++j)
                {
                    genesis.Balances[addresses[j]] = "100";
                }

                var secp256K1  = new Secp256k1();
                var privateKey = new byte[32];
                var rnd        = System.Security.Cryptography.RandomNumberGenerator.Create();
                do
                {
                    rnd.GetBytes(privateKey);
                }while (!secp256K1.SecretKeyVerify(privateKey));

                var privateKeyHex = privateKey.ToHex();
                var publicKey     = new byte[64];
                Debug.Assert(secp256K1.PublicKeyCreate(publicKey, privateKey));
                var publicKeyHex = publicKey.ToHex();

                System.Console.WriteLine($"Loop {i + 1:D2}: private key [{privateKeyHex}] associated with public key [{publicKeyHex}]");

                var rpc = new RpcConfig
                {
                    Hosts       = new[] { "+" },
                    Port        = basePort,
                    MetricsPort = (ushort)(basePort + 1),
                    // ApiKey = "0x2e917846fe7487a4ea3a765473a3fc9b2d9227a4d312bc77fb9de357cf73d7e52b771d537394336e9eb2cb4838138f668f4bd7d8cf7e04d9242a42c71b99f166",
                    ApiKey = publicKeyHex
                };
                var walletPath = "wallet.json";
                var vault      = new VaultConfig
                {
                    Path     = walletPath,
                    Password = getRandomPassword()
                };
                var storage = new StorageConfig
                {
                    Path     = "ChainLachain",
                    Provider = "RocksDB",
                };
                var blockchain = new BlockchainConfig
                {
                    TargetBlockTime = target,
                };
                List <ulong> hardforkHeights = hardforks.ToList();
                var          hardfork        = new HardforkConfig
                {
                    Hardfork_1 = hardforkHeights[0],
                    Hardfork_2 = hardforkHeights[1],
                    Hardfork_3 = hardforkHeights[2],
                    Hardfork_4 = hardforkHeights[3],
                };
                var version = new VersionConfig
                {
                    Version = 2
                };

                var blockHeight = new CacheOptions
                {
                    SizeLimit = 100
                };

                var cache = new CacheConfig
                {
                    BlockHeight = blockHeight
                };

                var config = new Config(net, genesis, rpc, vault, storage, blockchain, hardfork, version, cache);
                File.WriteAllText($"config{i + 1:D2}.json", JsonConvert.SerializeObject(config, Formatting.Indented));
                GenWallet(
                    $"wallet{i + 1:D2}.json",
                    ecdsaPrivateKeys[i],
                    serializedHubPrivateKeys[i],
                    tpkeKeyGen.GetPrivKey(i).ToHex(),
                    privShares[i].ToHex(),
                    vault.Password
                    );
            }

            var tpkePrivKeys = string.Join(
                ", ",
                Enumerable.Range(0, n)
                .Select(idx => tpkeKeyGen.GetPrivKey(idx))
                .Select(x => $"\"{x.ToHex()}\""));
            var tsKeys = string.Join(
                ", ",
                sigKeyGen.GetPrivateShares()
                .Select(x => $"(\"{x.GetPublicKeyShare().ToHex()}\", \"{x.ToHex()}\")")
                );

            System.Console.WriteLine(
                $"{n}: " + "{" +
                "  \"tpke\": (" +
                $"    \"{tpkePubKey.ToHex()}\"," +
                $"    [{tpkePrivKeys}]" +
                "  )," +
                $"  \"ts\": [{tsKeys}]," +
                "}");
            System.Console.WriteLine(
                string.Join(", ", ecdsaPrivateKeys.Zip(ecdsaPublicKeys).Zip(addresses)
                            .Select(t => $"(\"{t.First.Second}\", \"{t.First.First}\", \"{t.Second}\")"))
                );
        }