Exemplo n.º 1
0
        private void PrintTLSIdentity(TLSIdentity id)
        {
            var certs = id.Certs;

            if (certs == null)
            {
                Debug.WriteLine("No certs to print.");
                return;
            }

            foreach (var x509 in certs)
            {
                //Print to console information contained in the certificate.
                Debug.WriteLine("{0}Subject: {1}{0}", Environment.NewLine, x509.Subject);
                Debug.WriteLine("{0}Issuer: {1}{0}", Environment.NewLine, x509.Issuer);
                Debug.WriteLine("{0}Version: {1}{0}", Environment.NewLine, x509.Version);
                Debug.WriteLine("{0}Valid Date: {1}{0}", Environment.NewLine, x509.NotBefore);
                Debug.WriteLine("{0}Expiry Date: {1}{0}", Environment.NewLine, x509.NotAfter);
                Debug.WriteLine("{0}Thumbprint: {1}{0}", Environment.NewLine, x509.Thumbprint);
                Debug.WriteLine("{0}Serial Number: {1}{0}", Environment.NewLine, x509.SerialNumber);
                Debug.WriteLine("{0}Friendly Name: {1}{0}", Environment.NewLine, x509.PublicKey.Oid.FriendlyName);
                Debug.WriteLine("{0}Public Key Format: {1}{0}", Environment.NewLine, x509.PublicKey.EncodedKeyValue.Format(true));
                Debug.WriteLine("{0}Raw Data Length: {1}{0}", Environment.NewLine, x509.RawData.Length);
                Debug.WriteLine("{0}Certificate to string: {1}{0}", Environment.NewLine, x509.ToString(true));
                //Debug.WriteLine("{0}Certificate to XML String: {1}{0}", Environment.NewLine, x509.PublicKey.Key.ToXmlString(false));
            }
        }
Exemplo n.º 2
0
        internal TLSIdentity CreateIdentityWithCertLabel(string label)
        {
            using (_store = new X509Store(StoreName.My)) {
                // Check if identity exists, use the id if it is.
                var id = TLSIdentity.GetIdentity(_store, label, null);
                if (id != null)
                {
                    return(id);
                }

                try {
                    id = TLSIdentity.CreateIdentity(true,
                                                    new Dictionary <string, string>()
                    {
                        { Certificate.CommonNameAttribute, ListenerCommonName }
                    },
                                                    null,
                                                    _store,
                                                    label,
                                                    null);
                } catch (Exception ex) {
                    Debug.WriteLine($"Error while creating self signed cert : {ex}");
                }

                return(id);
            }
        }
        public void TestTLSIdentity()
        {
            // TLS is disabled
            _listener = CreateListener(false);
            _listener.TlsIdentity.Should().BeNull();
            _listener.Stop();
            _listener.TlsIdentity.Should().BeNull();

            // Anonymous Identity
            _listener = CreateListener(true);
            _listener.TlsIdentity.Should().NotBeNull();
            _listener.Stop();
            _listener.TlsIdentity.Should().BeNull();

            // User Identity
            TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);
            var id = TLSIdentity.CreateIdentity(false,
                                                new Dictionary <string, string>()
            {
                { Certificate.CommonNameAttribute, "CBL-Server" }
            },
                                                null,
                                                _store,
                                                ServerCertLabel,
                                                null);
            var config = CreateListenerConfig(true, true, null, id);

            _listener = new URLEndpointListener(config);
            _listener.TlsIdentity.Should().BeNull();
            _listener.Start();
            _listener.TlsIdentity.Should().NotBeNull();
            _listener.TlsIdentity.Should().BeEquivalentTo(config.TlsIdentity);
            _listener.Stop();
            _listener.TlsIdentity.Should().BeNull();
        }
Exemplo n.º 4
0
        public TLSIdentityTest()
#endif
        {
            _store = new X509Store(StoreName.My);
            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);
        }
Exemplo n.º 5
0
        public void TestCertificateExpiration()
        {
            TLSIdentity id;

            // Delete
            TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);

            //Get
            id = TLSIdentity.GetIdentity(_store, ServerCertLabel, null);
            id.Should().BeNull();

            var fiveMinToExpireCert = DateTimeOffset.UtcNow.AddMinutes(5);

            id = TLSIdentity.CreateIdentity(true,
                                            new Dictionary <string, string>()
            {
                { Certificate.CommonNameAttribute, "CA-P2PTest" }
            },
                                            fiveMinToExpireCert,
                                            _store,
                                            ServerCertLabel,
                                            null);

            (id.Expiration - DateTimeOffset.UtcNow).Should().BeGreaterThan(TimeSpan.MinValue);
            (id.Expiration - DateTimeOffset.UtcNow).Should().BeLessOrEqualTo(TimeSpan.FromMinutes(5));

            // Delete
            TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);
        }
Exemplo n.º 6
0
        public void TestCreateIdentityWithNoAttributesOrEmptyAttributes()
        {
            // Delete
            TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);

            //Get
            var id = TLSIdentity.GetIdentity(_store, ServerCertLabel, null);

            id.Should().BeNull();

            // Create id with empty Attributes
            Action badAction = (() => TLSIdentity.CreateIdentity(true,
                                                                 new Dictionary <string, string>()
            {
            },
                                                                 null,
                                                                 _store,
                                                                 ServerCertLabel,
                                                                 null));

            badAction.Should().Throw <CouchbaseLiteException>(CouchbaseLiteErrorMessage.CreateCertAttributeEmpty);

            // Create id with null Attributes
            badAction = (() => TLSIdentity.CreateIdentity(true,
                                                          null,
                                                          null,
                                                          _store,
                                                          ServerCertLabel,
                                                          null));
            badAction.Should().Throw <CouchbaseLiteException>(CouchbaseLiteErrorMessage.CreateCertAttributeEmpty);
        }
Exemplo n.º 7
0
        internal TLSIdentity ImportTLSIdentityFromPkc12(string label)
        {
            using (_store = new X509Store(StoreName.My)) {
                // Check if identity exists, use the id if it is.
                var id = TLSIdentity.GetIdentity(_store, label, null);
                if (id != null)
                {
                    return(id);
                }

                try {
                    byte[] data = null;
                    using (var stream = ResourceLoader.GetEmbeddedResourceStream(typeof(ListenerViewModel).GetTypeInfo().Assembly, $"{ListenerCertKeyP12File}.p12")) {
                        using (var reader = new BinaryReader(stream)) {
                            data = reader.ReadBytes((int)stream.Length);
                        }
                    }

                    id = TLSIdentity.ImportIdentity(_store, data, ListenerCertKeyExportPassword, label, null);
                } catch (Exception ex) {
                    Debug.WriteLine($"Error while loading self signed cert : {ex}");
                }

                return(id);
            }
        }
Exemplo n.º 8
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);
            _store.Dispose();
        }
Exemplo n.º 9
0
        public ListenerViewModel()
        {
            Title = "Listener";

            StartListenerCommand = new Command(() => ExecuteStartListenerCommand());
            BroadcastCommand     = new Command(() => Broadcast());

            using (_store = new X509Store(StoreName.My)) {
                TLSIdentity.DeleteIdentity(_store, ListenerCertLabel, null);
            }
        }
        public void TestListenerWithImportIdentity()
        {
            byte[] serverData = null;
            using (var stream = typeof(URLEndpointListenerTest).Assembly.GetManifestResourceStream("client.p12"))
                using (var reader = new BinaryReader(stream)) {
                    serverData = reader.ReadBytes((int)stream.Length);
                }

            // Cleanup
            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);

            // Import identity
            var id = TLSIdentity.ImportIdentity(_store, serverData, "123", ServerCertLabel, null);

            // Create listener and start
            var config = CreateListenerConfig(true, true, null, id);

            _listener = Listen(config);

            _listener.TlsIdentity.Should().NotBeNull();

            using (var doc1 = new MutableDocument("doc1")) {
                doc1.SetString("name", "Sam");
                Db.Save(doc1);
            }

            OtherDb.Count.Should().Be(0);

            RunReplication(
                _listener.LocalEndpoint(),
                ReplicatorType.PushAndPull,
                false,
                null,                           //authenticator
                false,                          //accept only self signed server cert
                _listener.TlsIdentity.Certs[0], //server cert
                0,
                0
                );

            OtherDb.Count.Should().Be(1);

            _listener.Stop();
        }
Exemplo n.º 11
0
        public void TestImportIdentity()
        {
            TLSIdentity id;

            byte[] data = null;
            using (var stream = typeof(TLSIdentityTest).GetTypeInfo().Assembly.GetManifestResourceStream("certs.p12"))
                using (var reader = new BinaryReader(stream)) {
                    data = reader.ReadBytes((int)stream.Length);
                }

            // Import
            id = TLSIdentity.ImportIdentity(_store, data, "123", ServerCertLabel, null);
            id.Should().NotBeNull();
            id.Certs.Count.Should().Be(2);
            ValidateCertsInStore(id.Certs, _store).Should().BeTrue();

            // Get
            id = TLSIdentity.GetIdentity(_store, ServerCertLabel, null);
            id.Should().NotBeNull();
        }
Exemplo n.º 12
0
        private void CreateGetDeleteServerIdentity(bool isServer)
        {
            string      commonName = isServer ? "CBL-Server" : "CBL-Client";
            string      label      = isServer ? ServerCertLabel : ClientCertLabel;
            TLSIdentity id;

            // Delete
            TLSIdentity.DeleteIdentity(_store, label, null);

            //Get
            id = TLSIdentity.GetIdentity(_store, label, null);
            id.Should().BeNull();

            // Create
            id = TLSIdentity.CreateIdentity(isServer,
                                            new Dictionary <string, string>()
            {
                { Certificate.CommonNameAttribute, commonName }
            },
                                            null,
                                            _store,
                                            label,
                                            null);
            id.Should().NotBeNull();
            id.Certs.Count.Should().Be(1);
            ValidateCertsInStore(id.Certs, _store).Should().BeTrue();

            // Get
            id = TLSIdentity.GetIdentity(_store, label, null);
            id.Should().NotBeNull();
            id.Certs.Count.Should().Be(1);
            ValidateCertsInStore(id.Certs, _store).Should().BeTrue();

            // Delete
            TLSIdentity.DeleteIdentity(_store, label, null);

            // Get
            id = TLSIdentity.GetIdentity(_store, label, null);
            id.Should().BeNull();
        }
        public void TestClientCertAuthRootCertsError()
        {
            byte[] caData;
            using (var stream = typeof(URLEndpointListenerTest).Assembly.GetManifestResourceStream("client-ca.der"))
                using (var reader = new BinaryReader(stream)) {
                    caData = reader.ReadBytes((int)stream.Length);
                }

            var rootCert = new X509Certificate2(caData);
            var auth     = new ListenerCertificateAuthenticator(new X509Certificate2Collection(rootCert));

            _listener = CreateListener(true, true, auth);

            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            // Create wrong client identity
            var id = TLSIdentity.CreateIdentity(false,
                                                new Dictionary <string, string>()
            {
                { Certificate.CommonNameAttribute, "daniel" }
            },
                                                null,
                                                _store,
                                                ClientCertLabel,
                                                null);

            id.Should().NotBeNull();
            RunReplication(
                _listener.LocalEndpoint(),
                ReplicatorType.PushAndPull,
                false,
                new ClientCertificateAuthenticator(id),
                true,
                _listener.TlsIdentity.Certs[0],
                (int)CouchbaseLiteError.TLSHandshakeFailed,  //not TLSClientCertRejected as mac has..
                CouchbaseLiteErrorType.CouchbaseLite
                );

            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            _listener.Stop();
        }
        public void TestClientCertAuthenticatorRootCerts()
        {
            byte[] caData, clientData;
            using (var stream = typeof(URLEndpointListenerTest).Assembly.GetManifestResourceStream("client-ca.der"))
                using (var reader = new BinaryReader(stream)) {
                    caData = reader.ReadBytes((int)stream.Length);
                }

            using (var stream = typeof(URLEndpointListenerTest).Assembly.GetManifestResourceStream("client.p12"))
                using (var reader = new BinaryReader(stream)) {
                    clientData = reader.ReadBytes((int)stream.Length);
                }

            var rootCert = new X509Certificate2(caData);
            var auth     = new ListenerCertificateAuthenticator(new X509Certificate2Collection(rootCert));

            _listener = CreateListener(true, true, auth);
            var serverCert = _listener.TlsIdentity.Certs[0];

            // Cleanup
            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);

            // Create client identity
            var id = TLSIdentity.ImportIdentity(_store, clientData, "123", ClientCertLabel, null);

            RunReplication(
                _listener.LocalEndpoint(),
                ReplicatorType.PushAndPull,
                false,
                new ClientCertificateAuthenticator(id),
                true,
                serverCert,
                0,
                0
                );

            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            _listener.Stop();
        }
Exemplo n.º 15
0
        public void TestGetIdentityWithCertCollection()
        {
            TLSIdentity id;

            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            TLSIdentity identity = TLSIdentity.CreateIdentity(false,
                                                              new Dictionary <string, string>()
            {
                { Certificate.CommonNameAttribute, "CA-P2PTest1" }
            },
                                                              null,
                                                              _store,
                                                              ClientCertLabel,
                                                              null);

            var certs = identity.Certs;

            id = TLSIdentity.GetIdentity(certs);
            id.Should().NotBeNull();

            // Delete
            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
        }
Exemplo n.º 16
0
        private void CreateDuplicateServerIdentity(bool isServer)
        {
            string      commonName = isServer ? "CBL-Server" : "CBL-Client";
            string      label      = isServer ? ServerCertLabel : ClientCertLabel;
            TLSIdentity id;
            Dictionary <string, string> attr = new Dictionary <string, string>()
            {
                { Certificate.CommonNameAttribute, commonName }
            };

            // Delete
            TLSIdentity.DeleteIdentity(_store, label, null);

            // Create
            id = TLSIdentity.CreateIdentity(isServer,
                                            attr,
                                            null,
                                            _store,
                                            label,
                                            null);
            id.Should().NotBeNull();
            id.Certs.Count.Should().Be(1);

            //Get - Need to check why CryptographicException: Invalid provider type specified
            //id = TLSIdentity.GetIdentity(_store, label, null);
            //id.Should().NotBeNull();

            // Create again with the same label
            Action badAction = (() => TLSIdentity.CreateIdentity(isServer,
                                                                 attr,
                                                                 null,
                                                                 _store,
                                                                 label,
                                                                 null));

            badAction.Should().Throw <CouchbaseLiteException>(CouchbaseLiteErrorMessage.DuplicateCertificate);
        }
        public void TestClientCertAuthWithCallback()
        {
            var auth = new ListenerCertificateAuthenticator((sender, cert) =>
            {
                if (cert.Count != 1)
                {
                    return(false);
                }

                return(cert[0].SubjectName.Name?.Replace("CN=", "") == "daniel");
            });

            var badAuth = new ListenerCertificateAuthenticator((sender, cert) =>
            {
                return(cert.Count == 100); // Obviously fail
            });

            _listener = CreateListener(true, true, auth);

            // User Identity
            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            var id = TLSIdentity.CreateIdentity(false,
                                                new Dictionary <string, string>()
            {
                { Certificate.CommonNameAttribute, "daniel" }
            },
                                                null,
                                                _store,
                                                ClientCertLabel,
                                                null);

            RunReplication(
                _listener.LocalEndpoint(),
                ReplicatorType.PushAndPull,
                false,
                new ClientCertificateAuthenticator(id),
                false,
                _listener.TlsIdentity.Certs[0],
                0,
                0
                );

            RunReplication(
                _listener.LocalEndpoint(),
                ReplicatorType.PushAndPull,
                false,
                null, // Don't send client cert
                false,
                _listener.TlsIdentity.Certs[0],
                (int)CouchbaseLiteError.TLSHandshakeFailed,
                CouchbaseLiteErrorType.CouchbaseLite
                );

            _listener.Stop();
            _listener = CreateListener(true, true, badAuth);

            RunReplication(
                _listener.LocalEndpoint(),
                ReplicatorType.PushAndPull,
                false,
                new ClientCertificateAuthenticator(id), // send wrong client cert
                false,
                _listener.TlsIdentity.Certs[0],
                (int)CouchbaseLiteError.TLSHandshakeFailed,
                CouchbaseLiteErrorType.CouchbaseLite
                );

            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
        }
        private URLEndpointListenerConfiguration CreateListenerConfig(bool tls = true, bool useDynamicPort = true,
                                                                      IListenerAuthenticator auth = null, TLSIdentity id = null)
        {
            _listener?.Stop();

            var config = new URLEndpointListenerConfiguration(OtherDb);

            if (useDynamicPort)
            {
                config.Port = 0;
            }
            else
            {
                config.Port = tls ? WssPort : WsPort;
            }

            config.DisableTLS    = !tls;
            config.Authenticator = auth;
            config.TlsIdentity   = id;

            return(config);
        }
Exemplo n.º 19
0
        private URLEndpointListenerConfiguration CreateListenerConfig(bool tls = true, bool useDynamicPort = true,
                                                                      IListenerAuthenticator auth = null, TLSIdentity id = null, bool readOnly = false, string networkInterface = null)
        {
            _listener?.Stop();

            var config = new URLEndpointListenerConfiguration(OtherDb)
            {
                Port          = useDynamicPort ? (ushort)0 : tls ? WssPort : WsPort,
                DisableTLS    = !tls,
                Authenticator = auth,
                TlsIdentity   = id,
                ReadOnly      = readOnly
            };

            return(config);
        }