private ISet <string> ExtractValidShortKeys()
        {
            ISet <string> validSettingNames = new HashSet <string>();

            string policyName   = "example";
            int    prefixLength = GroupPrefix().Length + 1 + policyName.Length + 1;            // dbms.ssl.policy.example.

            SslPolicyConfig examplePolicy = new SslPolicyConfig(policyName);

            System.Reflection.FieldInfo[] fields = examplePolicy.GetType().GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            foreach (System.Reflection.FieldInfo field in fields)
            {
                if (Modifier.isStatic(field.Modifiers))
                {
                    continue;
                }

                try
                {
                    object obj = field.get(examplePolicy);
                    if (obj is Setting)
                    {
                        string longKey  = (( Setting )obj).name();
                        string shortKey = longKey.Substring(prefixLength);
                        validSettingNames.Add(shortKey);
                    }
                }
                catch (IllegalAccessException e)
                {
                    throw new Exception(e);
                }
            }
            return(validSettingNames);
        }
        private void ShouldComplainIfMissingFile(File file)
        {
            // given
            FileUtils.deleteFile(file);

            IDictionary <string, string> @params = stringMap();

            SslPolicyConfig policyConfig = new SslPolicyConfig("default");

            @params[neo4j_home.name()] = _home.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()] = "certificates/default";

            Config config = Config.defaults(@params);

            // when
            try
            {
                SslPolicyLoader.Create(config, NullLogProvider.Instance);
                fail();
            }
            catch (Exception e)
            {
                assertTrue(e.InnerException is FileNotFoundException);
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFindPolicyOverrides()
        public virtual void ShouldFindPolicyOverrides()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            string          policyName   = "XYZ";
            SslPolicyConfig policyConfig = new SslPolicyConfig(policyName);

            File homeDir = TestDirectory.directory("home");

            @params[GraphDatabaseSettings.neo4j_home.name()] = homeDir.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()]       = "certificates/XYZ";

            File privateKey        = TestDirectory.directory("/path/to/my.key");
            File publicCertificate = TestDirectory.directory("/path/to/my.crt");
            File trustedDir        = TestDirectory.directory("/some/other/path/to/trusted");
            File revokedDir        = TestDirectory.directory("/some/other/path/to/revoked");

            @params[policyConfig.PrivateKey.name()]        = privateKey.AbsolutePath;
            @params[policyConfig.PublicCertificate.name()] = publicCertificate.AbsolutePath;
            @params[policyConfig.TrustedDir.name()]        = trustedDir.AbsolutePath;
            @params[policyConfig.RevokedDir.name()]        = revokedDir.AbsolutePath;

            @params[policyConfig.AllowKeyGeneration.name()] = "true";
            @params[policyConfig.TrustAll.name()]           = "true";

            @params[policyConfig.PrivateKeyPassword.name()] = "setecastronomy";
            @params[policyConfig.TlsVersions.name()]        = "TLSv1.1,TLSv1.2";
            @params[policyConfig.Ciphers.name()]            = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384";
            @params[policyConfig.ClientAuth.name()]         = "optional";

            Config config = Config.defaults(@params);

            // when
            File privateKeyFromConfig        = config.Get(policyConfig.PrivateKey);
            File publicCertificateFromConfig = config.Get(policyConfig.PublicCertificate);
            File trustedDirFromConfig        = config.Get(policyConfig.TrustedDir);
            File revokedDirFromConfig        = config.Get(policyConfig.RevokedDir);

            string         privateKeyPassword = config.Get(policyConfig.PrivateKeyPassword);
            bool           allowKeyGeneration = config.Get(policyConfig.AllowKeyGeneration);
            bool           trustAll           = config.Get(policyConfig.TrustAll);
            IList <string> tlsVersions        = config.Get(policyConfig.TlsVersions);
            IList <string> ciphers            = config.Get(policyConfig.Ciphers);
            ClientAuth     clientAuth         = config.Get(policyConfig.ClientAuth);

            // then
            assertEquals(privateKey, privateKeyFromConfig);
            assertEquals(publicCertificate, publicCertificateFromConfig);
            assertEquals(trustedDir, trustedDirFromConfig);
            assertEquals(revokedDir, revokedDirFromConfig);

            assertTrue(allowKeyGeneration);
            assertTrue(trustAll);
            assertEquals("setecastronomy", privateKeyPassword);
            assertEquals(asList("TLSv1.1", "TLSv1.2"), tlsVersions);
            assertEquals(asList("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"), ciphers);
            assertEquals(ClientAuth.OPTIONAL, clientAuth);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFindPolicyDefaults()
        public virtual void ShouldFindPolicyDefaults()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            string          policyName   = "XYZ";
            SslPolicyConfig policyConfig = new SslPolicyConfig(policyName);

            File homeDir = TestDirectory.directory("home");

            @params[GraphDatabaseSettings.neo4j_home.name()] = homeDir.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()]       = "certificates/XYZ";
            Config config = Config.defaults(@params);

            // derived defaults
            File privateKey        = new File(homeDir, "certificates/XYZ/private.key");
            File publicCertificate = new File(homeDir, "certificates/XYZ/public.crt");
            File trustedDir        = new File(homeDir, "certificates/XYZ/trusted");
            File revokedDir        = new File(homeDir, "certificates/XYZ/revoked");

            // when
            File           privateKeyFromConfig        = config.Get(policyConfig.PrivateKey);
            File           publicCertificateFromConfig = config.Get(policyConfig.PublicCertificate);
            File           trustedDirFromConfig        = config.Get(policyConfig.TrustedDir);
            File           revokedDirFromConfig        = config.Get(policyConfig.RevokedDir);
            string         privateKeyPassword          = config.Get(policyConfig.PrivateKeyPassword);
            bool           allowKeyGeneration          = config.Get(policyConfig.AllowKeyGeneration);
            bool           trustAll    = config.Get(policyConfig.TrustAll);
            IList <string> tlsVersions = config.Get(policyConfig.TlsVersions);
            IList <string> ciphers     = config.Get(policyConfig.Ciphers);
            ClientAuth     clientAuth  = config.Get(policyConfig.ClientAuth);

            // then
            assertEquals(privateKey, privateKeyFromConfig);
            assertEquals(publicCertificate, publicCertificateFromConfig);
            assertEquals(trustedDir, trustedDirFromConfig);
            assertEquals(revokedDir, revokedDirFromConfig);
            assertNull(privateKeyPassword);
            assertFalse(allowKeyGeneration);
            assertFalse(trustAll);
            assertEquals(singletonList("TLSv1.2"), tlsVersions);
            assertNull(ciphers);
            assertEquals(ClientAuth.REQUIRE, clientAuth);
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public java.util.Map<String,String> validate(java.util.Map<String,String> params, System.Action<String> warningConsumer) throws org.neo4j.graphdb.config.InvalidSettingException
        public override IDictionary <string, string> Validate(IDictionary <string, string> @params, System.Action <string> warningConsumer)
        {
            IDictionary <string, string> validatedParams = new Dictionary <string, string>();

            ISet <string> validShortKeys     = ExtractValidShortKeys();
            string        groupSettingPrefix = GroupPrefix();

            Pattern groupSettingPattern = Pattern.compile(Pattern.quote(groupSettingPrefix) + "\\.([^.]+)\\.?(.+)?");

            ISet <string> policyNames = new HashSet <string>();

            foreach (KeyValuePair <string, string> paramsEntry in @params.SetOfKeyValuePairs())
            {
                string  settingName = paramsEntry.Key;
                Matcher matcher     = groupSettingPattern.matcher(settingName);
                if (!matcher.matches())
                {
                    continue;
                }

                policyNames.Add(matcher.group(1));
                string shortKey = matcher.group(2);

                if (!validShortKeys.Contains(shortKey))
                {
                    throw new InvalidSettingException("Invalid setting name: " + settingName);
                }

                validatedParams[settingName] = paramsEntry.Value;
            }

            foreach (string policyName in policyNames)
            {
                SslPolicyConfig policy = new SslPolicyConfig(policyName);

                if ([email protected](policy.BaseDirectory.name()))
                {
                    throw new InvalidSettingException("Missing mandatory setting: " + policy.BaseDirectory.name());
                }
            }

            return(validatedParams);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotAllowLegacyPolicyToBeConfigured()
        public virtual void ShouldNotAllowLegacyPolicyToBeConfigured()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            SslPolicyConfig policyConfig = new SslPolicyConfig(LegacySslPolicyConfig.LEGACY_POLICY_NAME);

            @params[neo4j_home.name()] = _home.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()] = "certificates/default";
            Config config = Config.defaults(@params);

            try
            {
                // when
                SslPolicyLoader.Create(config, NullLogProvider.Instance);
                fail();
            }
            catch (System.ArgumentException)
            {
                // expected
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFailWithIncompletePathOverrides()
        public virtual void ShouldFailWithIncompletePathOverrides()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            string          policyName   = "XYZ";
            SslPolicyConfig policyConfig = new SslPolicyConfig(policyName);

            File homeDir = TestDirectory.directory("home");

            @params[GraphDatabaseSettings.neo4j_home.name()] = homeDir.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()]       = "certificates";

            @params[policyConfig.PrivateKey.name()]        = "my.key";
            @params[policyConfig.PublicCertificate.name()] = "path/to/my.crt";

            Config config = Config.defaults(@params);

            // when/then
            try
            {
                config.Get(policyConfig.PrivateKey);
                fail();
            }
            catch (System.ArgumentException)
            {
                // expected
            }

            try
            {
                config.Get(policyConfig.PublicCertificate);
                fail();
            }
            catch (System.ArgumentException)
            {
                // expected
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldLoadBaseCryptographicObjects() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldLoadBaseCryptographicObjects()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            SslPolicyConfig policyConfig = new SslPolicyConfig("default");

            @params[neo4j_home.name()] = _home.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()] = "certificates/default";
            Config config = Config.defaults(@params);

            // when
            SslPolicyLoader sslPolicyLoader = SslPolicyLoader.Create(config, NullLogProvider.Instance);

            // then
            SslPolicy sslPolicy = sslPolicyLoader.GetPolicy("default");

            assertNotNull(sslPolicy);
            assertNotNull(sslPolicy.PrivateKey());
            assertNotNull(sslPolicy.CertificateChain());
            assertNotNull(sslPolicy.NettyClientContext());
            assertNotNull(sslPolicy.NettyServerContext());
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldThrowIfPolicyNameDoesNotExist()
        public virtual void ShouldThrowIfPolicyNameDoesNotExist()
        {
            // given
            IDictionary <string, string> @params = stringMap();

            SslPolicyConfig policyConfig = new SslPolicyConfig("default");

            @params[neo4j_home.name()] = _home.AbsolutePath;
            @params[policyConfig.BaseDirectory.name()] = "certificates/default";
            Config config = Config.defaults(@params);

            SslPolicyLoader sslPolicyLoader = SslPolicyLoader.Create(config, NullLogProvider.Instance);

            // when
            try
            {
                sslPolicyLoader.GetPolicy("unknown");
                fail();
            }
            catch (System.ArgumentException)
            {
                // expected
            }
        }
Exemple #10
0
        private void Load(Config config, Log log)
        {
            ISet <string> policyNames = config.IdentifiersFromGroup(typeof(SslPolicyConfig));

            foreach (string policyName in policyNames)
            {
                if (policyName.Equals(LEGACY_POLICY_NAME))
                {
                    // the legacy policy name is reserved for the legacy policy which derives its configuration from legacy settings
                    throw new System.ArgumentException("Legacy policy cannot be configured. Please migrate to new SSL policy system.");
                }

                SslPolicyConfig policyConfig           = new SslPolicyConfig(policyName);
                File            baseDirectory          = config.Get(policyConfig.BaseDirectory);
                File            trustedCertificatesDir = config.Get(policyConfig.TrustedDir);
                File            revokedCertificatesDir = config.Get(policyConfig.RevokedDir);

                if (!baseDirectory.exists())
                {
                    throw new System.ArgumentException(format("Base directory '%s' for SSL policy with name '%s' does not exist.", baseDirectory, policyName));
                }

                bool allowKeyGeneration = config.Get(policyConfig.AllowKeyGeneration);

                File       privateKeyFile     = config.Get(policyConfig.PrivateKey);
                string     privateKeyPassword = config.Get(policyConfig.PrivateKeyPassword);
                PrivateKey privateKey;

                X509Certificate[] keyCertChain;
                File keyCertChainFile = config.Get(policyConfig.PublicCertificate);

                if (allowKeyGeneration && !privateKeyFile.exists() && !keyCertChainFile.exists())
                {
                    GeneratePrivateKeyAndCertificate(log, policyName, keyCertChainFile, privateKeyFile, trustedCertificatesDir, revokedCertificatesDir);
                }

                privateKey   = LoadPrivateKey(privateKeyFile, privateKeyPassword);
                keyCertChain = LoadCertificateChain(keyCertChainFile);

                ClientAuth          clientAuth     = config.Get(policyConfig.ClientAuth);
                bool                trustAll       = config.Get(policyConfig.TrustAll);
                bool                verifyHostname = config.Get(policyConfig.VerifyHostname);
                TrustManagerFactory trustManagerFactory;

                ICollection <X509CRL> crls = GetCRLs(revokedCertificatesDir);

                try
                {
                    trustManagerFactory = CreateTrustManagerFactory(trustAll, trustedCertificatesDir, crls, clientAuth);
                }
                catch (Exception e)
                {
                    throw new Exception("Failed to create trust manager based on: " + trustedCertificatesDir, e);
                }

                IList <string> tlsVersions = config.Get(policyConfig.TlsVersions);
                IList <string> ciphers     = config.Get(policyConfig.Ciphers);

                SslPolicy sslPolicy = new SslPolicy(privateKey, keyCertChain, tlsVersions, ciphers, clientAuth, trustManagerFactory, _sslProvider, verifyHostname, _logProvider);
                log.Info(format("Loaded SSL policy '%s' = %s", policyName, sslPolicy));
                _policies[policyName] = sslPolicy;
            }
        }