Пример #1
0
        static void Main(string[] args)
        {
            string address = "amqp://*****:*****@127.0.0.1:5672";

            if (args.Length > 0)
            {
                address = args[0];
            }

            // uncomment the following to write frame traces
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (l, f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            Uri           addressUri = new Uri(address);
            ContainerHost host       = new ContainerHost(new Uri[] { addressUri }, null, addressUri.UserInfo);

            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            host.RegisterLinkProcessor(new LinkProcessor());
            Console.WriteLine("Link processor is registered.");

            Console.WriteLine("Start the client");
            var client = new Client(address);
            var task   = Task.Run(() => client.Run());

            Console.WriteLine("Press enter key to exit...");
            Console.ReadLine();

            client.Close();
            host.Close();
        }
Пример #2
0
        static void Main(string[] args)
        {
            string address = "amqp://*****:*****@127.0.0.1:5672";
            if (args.Length > 0)
            {
                address = args[0];
            }

            // uncomment the following to write frame traces
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a));

            Uri addressUri = new Uri(address);
            ContainerHost host = new ContainerHost(new Uri[] { addressUri }, null, addressUri.UserInfo);
            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            host.RegisterLinkProcessor(new LinkProcessor());
            Console.WriteLine("Link processor is registered");

            Console.WriteLine("Press enter key to exit...");
            Console.ReadLine();

            host.Close();
        }
Пример #3
0
        static void Main(string[] args)
        {
            Address address = new Address("amqp://*****:*****@127.0.0.1:5672");

            if (args.Length > 0)
            {
                address = new Address(args[0]);
            }

            // uncomment the following to write frame traces
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (l, f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            ContainerHost host = new ContainerHost(address);

            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", address.Host, address.Port);

            host.RegisterLinkProcessor(new LinkProcessor());
            Console.WriteLine("Link processor is registered");

            Console.WriteLine("Press enter key to exit...");
            Console.ReadLine();

            host.Close();
        }
Пример #4
0
        public static void StartHost()
        {
            if (Host != null)
            {
                throw new InvalidOperationException("Host is already running.");
            }

            // Create listener and start it.
            Uri addressUri = new Uri(address);

            Host = new ContainerHost(addressUri);
            Host.Listeners[0].SSL.Certificate = GetSslCertificate();
            Host.Listeners[0].SASL.EnableAnonymousMechanism = true;
            // These next 2 lines are for test servers only!
            //Host.Listeners[0].SSL.ClientCertificateRequired = true;
            //Host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;

            // TODO: implement a max concurrent connections
            Host.Open();
            System.Console.WriteLine($"MessageBroker Host is listenening on {addressUri.Host}:{addressUri.Port}");

            // Attach custom logic when links attempt to attach to the host
            Host.RegisterLinkProcessor(new LinkProcessor());
            System.Console.WriteLine($"MessageBroker link processor is now registered.");
        }
 public TestContainerHost(Endpoint endpoint, IHandler handler = null)
 {
     Endpoint = endpoint;
     _host    = new ContainerHost(endpoint.Address);
     _host.Listeners[0].HandlerFactory = listener => handler;
     _linkProcessor = new TestLinkProcessor();
     _host.RegisterLinkProcessor(_linkProcessor);
 }
Пример #6
0
        public void Setup()
        {
            string address = "amqp://*****:*****@127.0.0.1:5672";

            Uri           addressUri = new Uri(address);
            ContainerHost host       = new ContainerHost(new[] { addressUri }, null, addressUri.UserInfo);

            host.Open(); // Throws socketexception - AddressAlreadyInUse - only one usage of each socket address (protocol/network address/port) is normally permitted
            host.RegisterLinkProcessor(new LinkProcessor());
        }
Пример #7
0
        public void ContainerHostX509PrincipalTest()
        {
            string           name    = "ContainerHostX509PrincipalTest";
            string           address = "amqps://localhost:5676";
            X509Certificate2 cert    = null;

            try
            {
                cert = GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");
            }
            catch (PlatformNotSupportedException)
            {
                // Unix machine, ignored
                return;
            }

            ContainerHost sslHost = new ContainerHost(new Uri(address));

            sslHost.Listeners[0].SSL.Certificate = cert;
            sslHost.Listeners[0].SSL.ClientCertificateRequired           = true;
            sslHost.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
            sslHost.Listeners[0].SASL.EnableExternalMechanism            = true;
            ListenerLink link          = null;
            var          linkProcessor = new TestLinkProcessor();

            linkProcessor.OnLinkAttached += a => link = a;
            sslHost.RegisterLinkProcessor(linkProcessor);
            sslHost.Open();

            try
            {
                var factory = new ConnectionFactory();
                factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                factory.SSL.ClientCertificates.Add(cert);
                factory.SASL.Profile = SaslProfile.External;
                var connection = factory.CreateAsync(new Address(address)).Result;
                var session    = new Session(connection);
                var sender     = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();

                Assert.IsTrue(link != null, "link is null");
                var listenerConnection = (ListenerConnection)link.Session.Connection;
                Assert.IsTrue(listenerConnection.Principal != null, "principal is null");
                Assert.IsTrue(listenerConnection.Principal.Identity.AuthenticationType == "X509", "wrong auth type");

                X509Identity identity = (X509Identity)listenerConnection.Principal.Identity;
                Assert.IsTrue(identity.Certificate != null, "certificate is null");
            }
            finally
            {
                sslHost.Close();
            }
        }
Пример #8
0
        public static async Task <Session> OpenAndLinkProcessorAsync(ILinkProcessor linkProcessor)
        {
            ContainerHost host = Open();

            host.RegisterLinkProcessor(linkProcessor);
            Connection connection = await host.ConnectAsync();

            var session = new Session(connection);

            session.AddClosedCallback((_, __) => host.Close());
            return(session);
        }
Пример #9
0
        public async Task IsAuthorized_ReturnsFalse_WhenSessionConnectionClosedBeforeAuthorized()
        {
            ListenerLink   link              = null;
            var            authorized        = false;
            ILinkProcessor fakeLinkProcessor = Substitute.For <ILinkProcessor>();

            fakeLinkProcessor
            .When(instance => instance.Process(Arg.Any <AttachContext>()))
            .Do(c =>
            {
                AttachContext attachContext = c.ArgAt <AttachContext>(0);
                link = attachContext.Link;
                attachContext.Complete(new Error(ErrorCode.IllegalState)
                {
                    Description = "Test"
                });
            });

            ContainerHost host = TestAmqpHost.Open();

            try
            {
                host.RegisterLinkProcessor(fakeLinkProcessor);
                Connection connection = await host.ConnectAndAttachAsync();

                await connection.CloseAsync();

                await Task.Delay(500);

                var securityContext = new SecurityContext();
                securityContext.Authorize(link.Session.Connection);

                authorized = securityContext.IsAuthorized(link.Session.Connection);
            }
            finally
            {
                host.Close();
            }

            authorized.ShouldBeFalse();
        }
Пример #10
0
        public override Task StartInternalAsync()
        {
            var end = new TaskCompletionSource <bool>();

            _cancellationRegistration = Token.Register(() =>
            {
                end.TrySetCanceled();
            });

            var incommingLink = new IncomingLinkEndpoint(end, _messages);

            var uri = new Uri("amqp://localhost:" + Settings.Port);

            _host = new ContainerHost(uri);

            _host.Open();

            _host.RegisterMessageProcessor(uri.AbsolutePath, new MessageProcessor());
            _host.RegisterLinkProcessor(new LinkProcessor(incommingLink));

            return(end.Task);
        }
Пример #11
0
        public async Task IsAuthorized_ReturnsTrue_WhenSameConnectionAuthorizedTwice()
        {
            var            authorized        = false;
            var            links             = new List <ListenerLink>();
            ILinkProcessor fakeLinkProcessor = Substitute.For <ILinkProcessor>();

            fakeLinkProcessor
            .When(instance => instance.Process(Arg.Any <AttachContext>()))
            .Do(c =>
            {
                AttachContext attachContext = c.ArgAt <AttachContext>(0);
                links.Add(attachContext.Link);
                attachContext.Complete(new Error(ErrorCode.IllegalState)
                {
                    Description = "Test"
                });
            });

            ContainerHost host = TestAmqpHost.Open();

            try
            {
                host.RegisterLinkProcessor(fakeLinkProcessor);
                Connection connection = await host.ConnectAndAttachAsync(2);

                var securityContext = new SecurityContext();
                securityContext.Authorize(links[0].Session.Connection);
                securityContext.Authorize(links[1].Session.Connection);
                authorized = securityContext.IsAuthorized(links[1].Session.Connection);

                await connection.CloseAsync();
            }
            finally
            {
                host.Close();
            }

            authorized.ShouldBeTrue();
        }
Пример #12
0
        public async Task WebSocketSslMutalAuthTest()
        {
            string testName      = "WebSocketSslMutalAuthTest";
            string listenAddress = "wss://localhost:18081/" + testName + "/";
            Uri    uri           = new Uri(listenAddress);

            X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");

            string output;
            int    code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);

            if (code != 0)
            {
                string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
                                            uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
                code = Exec("netsh.exe", args, out output);
                Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
            }

            X509Certificate serviceCert  = null;
            X509Certificate clientCert   = null;
            ListenerLink    listenerLink = null;

            var linkProcessor = new TestLinkProcessor()
            {
                OnLinkAttached = c => listenerLink = c
            };
            var host = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);

            host.Listeners[0].SASL.EnableExternalMechanism            = true;
            host.Listeners[0].SSL.ClientCertificateRequired           = true;
            host.Listeners[0].SSL.CheckCertificateRevocation          = true;
            host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return(true); };
            host.RegisterLinkProcessor(linkProcessor);
            host.Open();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return(true); };
                var wssFactory = new WebSocketTransportFactory();
                wssFactory.Options = o =>
                {
                    o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
                };

                ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
                connectionFactory.SASL.Profile = SaslProfile.External;
                Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));

                Session    session = new Session(connection);
                SenderLink sender  = new SenderLink(session, "sender-" + testName, "q1");
                await sender.SendAsync(new Message("test") { Properties = new Properties()
                                                             {
                                                                 MessageId = testName
                                                             } });

                await connection.CloseAsync();

                Assert.IsTrue(serviceCert != null, "service cert not received");
                Assert.IsTrue(clientCert != null, "client cert not received");
                Assert.IsTrue(listenerLink != null, "link not attached");

                IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
                Assert.IsTrue(principal != null, "connection pricipal is null");
                Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
            }
            finally
            {
                host.Close();
            }
        }
Пример #13
0
        public async Task WebSocketSslMutalAuthTest()
        {
            string testName = "WebSocketSslMutalAuthTest";
            string listenAddress = "wss://localhost:18081/" + testName + "/";
            Uri uri = new Uri(listenAddress);

            X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");

            string output;
            int code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);
            if (code != 0)
            {
                string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
                    uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
                code = Exec("netsh.exe", args, out output);
                Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
            }

            X509Certificate serviceCert = null;
            X509Certificate clientCert = null;
            ListenerLink listenerLink = null;

            var linkProcessor = new TestLinkProcessor() { OnLinkAttached = c => listenerLink = c };
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.Listeners[0].SASL.EnableExternalMechanism = true;
            host.Listeners[0].SSL.ClientCertificateRequired = true;
            host.Listeners[0].SSL.CheckCertificateRevocation = true;
            host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return true; };
            host.RegisterLinkProcessor(linkProcessor);
            host.Open();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return true; };
                var wssFactory = new WebSocketTransportFactory();
                wssFactory.Options = o =>
                {
                    o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
                };

                ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
                connectionFactory.SASL.Profile = SaslProfile.External;
                Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");
                await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } });                
                await connection.CloseAsync();

                Assert.IsTrue(serviceCert != null, "service cert not received");
                Assert.IsTrue(clientCert != null, "client cert not received");
                Assert.IsTrue(listenerLink != null, "link not attached");

                IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
                Assert.IsTrue(principal != null, "connection pricipal is null");
                Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
            }
            finally
            {
                host.Close();
            }
        }
Пример #14
0
        public void ContainerHostX509PrincipalTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            string address = "amqps://localhost:5676";
            X509Certificate2 cert = GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");
            ContainerHost sslHost = new ContainerHost(new Uri(address));
            sslHost.Listeners[0].SSL.Certificate = cert;
            sslHost.Listeners[0].SSL.ClientCertificateRequired = true;
            sslHost.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
            sslHost.Listeners[0].SASL.EnableExternalMechanism = true;
            ListenerLink link = null;
            var linkProcessor = new TestLinkProcessor();
            linkProcessor.OnLinkAttached += a => link = a;
            sslHost.RegisterLinkProcessor(linkProcessor);
            sslHost.Open();

            try
            {
                var factory = new ConnectionFactory();
                factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                factory.SSL.ClientCertificates.Add(cert);
                factory.SASL.Profile = SaslProfile.External;
                var connection = factory.CreateAsync(new Address(address)).Result;
                var session = new Session(connection);
                var sender = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();

                Assert.IsTrue(link != null, "link is null");
                var listenerConnection = (ListenerConnection)link.Session.Connection;
                Assert.IsTrue(listenerConnection.Principal != null, "principal is null");
                Assert.IsTrue(listenerConnection.Principal.Identity.AuthenticationType == "X509", "wrong auth type");

                X509Identity identity = (X509Identity)listenerConnection.Principal.Identity;
                Assert.IsTrue(identity.Certificate != null, "certificate is null");
            }
            finally
            {
                sslHost.Close();
            }
        }
Пример #15
0
 public void RegisterLinkProcessor(ILinkProcessor linkProcessor)
 {
     containerHost.RegisterLinkProcessor(linkProcessor);
 }