コード例 #1
0
        public void HandleSetEncodingsTest(bool forceConnect, VncEncoding expectedEncoding)
        {
            using (var stream = new TestStream())
            {
                // Have the client send a list of supported encodings, including
                // Raw and zlib
                VncStream clientStream = new VncStream(stream.Input);
                clientStream.SendByte(0);
                clientStream.SendUInt16BE(2); // 2 encodings are supported
                clientStream.SendUInt32BE((uint)VncEncoding.Raw);
                clientStream.SendUInt32BE((uint)VncEncoding.Zlib);
                stream.Input.Position = 0;

                var session = new VncServerSession();
                session.Connect(stream, null, startThread: false, forceConnected: forceConnect);

                session.HandleSetEncodings();

                // The server should not have written any output, but switched
                // to zlib encoding
                VncStream serverStream = new VncStream(stream.Output);
                Assert.Equal(0, serverStream.Stream.Length);
                stream.Output.Position = 0;

                Assert.Equal(expectedEncoding, session.Encoder.Encoding);
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: 5l1v3r1/remoteviewing
        private static void Main(string[] args)
        {
            Console.WriteLine("Listening on local port 5900.");
            Console.WriteLine("Try to connect! The password is: {0}", password);

            // Wait for a connection.
            var listener = new TcpListener(IPAddress.Loopback, 5900);

            listener.Start();
            var client = listener.AcceptTcpClient();

            // Set up a framebuffer and options.
            var options = new VncServerSessionOptions();

            options.AuthenticationMethod = AuthenticationMethod.Password;

            // Create a session.
            session = new VncServerSession(
                new VncPasswordChallenge(),
                new ConsoleLogger());
            session.Connected        += HandleConnected;
            session.ConnectionFailed += HandleConnectionFailed;
            session.Closed           += HandleClosed;
            session.PasswordProvided += HandlePasswordProvided;
            session.SetFramebufferSource(new DummyFramebufferSource());
            session.Connect(client.GetStream(), options);

            // Let's go.
            Console.WriteLine("Hit ENTER to exit");
            Console.ReadLine();
        }
コード例 #3
0
        public void NegotiateSecurityIncorrectPasswordTest()
        {
            using (var stream = new TestStream())
            {
                // Have the client send authentication method 'Password', which is what the server expects
                VncStream clientStream = new VncStream(stream.Input);
                clientStream.SendByte((byte)AuthenticationMethod.Password);
                clientStream.Send(new byte[16]); // An empty response
                stream.Input.Position = 0;

                var session = new VncServerSession();
                session.Connect(stream, null, startThread: false);

                Assert.False(session.NegotiateSecurity(new AuthenticationMethod[] { AuthenticationMethod.Password }));

                VncStream serverStream = new VncStream(stream.Output);
                stream.Output.Position = 0;

                // Server will have offered 1 authentication method, and failed to authenticate
                // the client
                Assert.Equal(1, serverStream.ReceiveByte());                                   // 1 authentication method offered
                Assert.Equal((byte)AuthenticationMethod.Password, serverStream.ReceiveByte()); // The authentication method offered
                Assert.NotEqual(0u, serverStream.ReceiveUInt32BE());                           // Challenge, part 1
                Assert.NotEqual(0u, serverStream.ReceiveUInt32BE());                           // Challenge, part 2
                Assert.NotEqual(0u, serverStream.ReceiveUInt32BE());                           // Challenge, part 3
                Assert.NotEqual(0u, serverStream.ReceiveUInt32BE());                           // Challenge, part 4
                Assert.Equal(1u, serverStream.ReceiveUInt32BE());                              // Authentication failed
                Assert.Equal("Failed to authenticate", serverStream.ReceiveString());          // Error message

                Assert.Equal(stream.Output.Length, stream.Output.Position);
                Assert.Equal(stream.Input.Length, stream.Input.Position);
            }
        }
コード例 #4
0
        public void NegotiateSecurityInvalidMethodTest()
        {
            using (var stream = new TestStream())
            {
                // Have the client send authentication method 'None', while we only accept 'Password'
                VncStream clientStream = new VncStream(stream.Input);
                clientStream.SendByte((byte)AuthenticationMethod.None);
                stream.Input.Position = 0;

                var session = new VncServerSession();
                session.Connect(stream, null, startThread: false);

                Assert.False(session.NegotiateSecurity(new AuthenticationMethod[] { AuthenticationMethod.Password }));

                VncStream serverStream = new VncStream(stream.Output);
                stream.Output.Position = 0;

                // Server will have offered 1 authentication method, and disconnected when the client
                // accepted an invalid authentication method.
                Assert.Equal(1, serverStream.ReceiveByte());                                   // 1 authentication method offered
                Assert.Equal((byte)AuthenticationMethod.Password, serverStream.ReceiveByte()); // The authentication method offered
                Assert.Equal(1u, serverStream.ReceiveUInt32BE());                              // authentication failed
                Assert.Equal("Invalid authentication method.", serverStream.ReceiveString());  // error message
            }
        }
コード例 #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Listening on local port 5900.");
            Console.WriteLine("Try to connect! The password is: {0}", Password);

            // Wait for a connection.
            var listener = new TcpListener(IPAddress.Any, 5900);

            listener.Start();
            var client = listener.AcceptTcpClient();

            // Set up a framebuffer and options.
            var options = new VncServerSessionOptions {
                AuthenticationMethod = AuthenticationMethod.Password
            };

            // Create a session.
            Session                   = new VncServerSession();
            Session.Connected        += HandleConnected;
            Session.ConnectionFailed += HandleConnectionFailed;
            Session.Closed           += HandleClosed;
            Session.PasswordProvided += HandlePasswordProvided;
            Session.SetFramebufferSource(new VncScreenFramebufferSource("Hello World", Screen.PrimaryScreen));
            Session.Connect(client.GetStream(), options);

            // Let's go.
            Application.Run();
        }
コード例 #6
0
        public static int StartWithHeadlessVncPlatform <T>(
            this T builder,
            string host, int port,
            string[] args, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
            where T : AppBuilderBase <T>, new()
        {
            var tcpServer = new TcpListener(host == null ? IPAddress.Loopback : IPAddress.Parse(host), port);

            tcpServer.Start();
            return(builder
                   .UseHeadless(false)
                   .AfterSetup(_ =>
            {
                var lt = ((IClassicDesktopStyleApplicationLifetime)builder.Instance.ApplicationLifetime);
                lt.Startup += async delegate
                {
                    while (true)
                    {
                        var client = await tcpServer.AcceptTcpClientAsync();
                        var options = new VncServerSessionOptions
                        {
                            AuthenticationMethod = AuthenticationMethod.None
                        };
                        var session = new VncServerSession();

                        session.SetFramebufferSource(new HeadlessVncFramebufferSource(
                                                         session, lt.MainWindow));
                        session.Connect(client.GetStream(), options);
                    }
                };
            })
                   .StartWithClassicDesktopLifetime(args, shutdownMode));
        }
コード例 #7
0
ファイル: Form1.cs プロジェクト: gus3826/SemicsVNCProject
        public static void ListenerThread()
        {
            while (true)
            {
                // Wait for a connection.
                TcpClient client = listener.AcceptTcpClient();   //AcceptTcpClient 접속하는 클라이언트에 대해 TCPClient 객체 생성

                // Set up a framebuffer and options.
                var options = new VncServerSessionOptions();
                options.AuthenticationMethod = AuthenticationMethod.Password;

                // Virtual mouse
                var mouse = new VncMouse();

                // Virtual keyboard
                var keyboard = new VncKeyboard();

                // Create a session.
                session                   = new VncServerSession();
                session.LogData          += HandleLogData; //로그를 저장하기위해 새로추가
                session.Connected        += HandleConnected;
                session.ConnectionFailed += HandleConnectionFailed;
                session.Closed           += HandleClosed;
                session.PasswordProvided += HandlePasswordProvided;
                session.SetFramebufferSource(new VncScreenFramebufferSource("Hello World", Screen.PrimaryScreen));
                session.PointerChanged += mouse.OnMouseUpdate;
                session.KeyChanged     += keyboard.OnKeyboardUpdate;
                session.Connect(client.GetStream(), options);


                //세션을 저장하는곳

                NetWorkItem item;
                item.session   = session;
                item.tcpClient = client;
                sessionList.Add(item);

                // 접속한 ip따오는
                Socket     c        = client.Client;
                IPEndPoint ip_point = (IPEndPoint)c.RemoteEndPoint;  //누가요청했는지 접근할수있게 IPEndPoint속성을 이용
                clientIP = ip_point.Address.ToString();

                session.ip = ip_point.Address.ToString();

                // MessageBox.Show(ip);
                clientID   = session.UserData;
                session.id = clientID;
                // MessageBox.Show(userID);



                // Let's go.
                //Application.Run();
            }
        }
コード例 #8
0
        private void ConnectService(TcpClient tcpClient)
        {
            try
            {
                string loalIp = GetLocalIpAddress();

                IPEndPoint remotePoint = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                IPEndPoint localpPoint = tcpClient.Client.LocalEndPoint as IPEndPoint;

                OnAddLogEvent($"VNC连接接入,客户端ip:{remotePoint.Address},端口:{remotePoint.Port}");

                VncServerSessionOptions options = new VncServerSessionOptions();
                //设置需要密码验证
                options.AuthenticationMethod = AuthenticationMethod.Password;

                // 创建一个会话
                VncServerSession session = new VncServerSession();
                session.MaxUpdateRate     = 20;
                session.Connected        += HandleConnected;
                session.ConnectionFailed += HandleConnectionFailed;
                session.Closed           += HandleClosed;
                session.PasswordProvided += HandlePasswordProvided;
                session.CreatingDesktop  += Session_CreatingDesktop;

                //session.FramebufferCapturing += Session_FramebufferCapturing;
                session.FramebufferUpdating += Session_FramebufferUpdating;

                session.KeyChanged             += Session_KeyChanged;
                session.PointerChanged         += Session_PointerChanged;
                session.RemoteClipboardChanged += Session_RemoteClipboardChanged;

                //设置分享的屏幕等信息 连接名字 name
                string name = loalIp + ":" + localpPoint.Port + "--" + remotePoint.Address + ":" + remotePoint.Port;
                VncScreenFramebufferSource vncScreenSource = new VncScreenFramebufferSource(name, Screen.PrimaryScreen);
                session.SetFramebufferSource(vncScreenSource);

                Dictionary <string, string> connectInfo = new Dictionary <string, string>()
                {
                    { "LoalIp", loalIp },
                    { "LocalpPort", localpPoint.Port.ToString() },
                    { "RemoteIp", remotePoint.Address.ToString() },
                    { "RemotePort", remotePoint.Port.ToString() },
                };
                session.UserData = connectInfo;
                session.Connect(tcpClient, options);

                sessionList.Add(session);
            }
            catch (Exception ex)
            {
                OnAddLogEvent($"连接出现错误,原因:{ex.Message}");
            }
        }
コード例 #9
0
        public static void Listen()
        {
            if (GV.IP.StartsWith("172.27"))
            {
                Random      Rand     = new Random();
                TcpListener listener = null;
                while (true)
                {
                    try
                    {
                        int iPort = Rand.Next(10000, 60000);//Max 65535
                        listener = new TcpListener(IPAddress.Any, iPort);
                        listener.Start();
                        ExecuteQuery("UPDATE c_machines set STATUS = 'Online', SystemState = '' ,RDPPort='" + iPort + "',CMVersion = '" + GV.sSoftwareVersion + "',LastSession='" + GV.sSessionID + "',LastUpdatedDate = GETDATE(), LastLoggedProjectID='" + GV.sProjectID + "' WHERE MachineID='" + GV.sMachineID + "';");
                        break;
                    }
                    catch (Exception ex)
                    {
                        listener = null;
                        Thread.Sleep(30000);
                    }
                }

                try
                {
                    var client = listener.AcceptTcpClient();

                    // Set up a framebuffer and options.
                    var options = new VncServerSessionOptions();
                    options.AuthenticationMethod = AuthenticationMethod.Password;

                    // Create a session.
                    Session                   = new VncServerSession();
                    Session.Connected        += SessionConnected;
                    Session.ConnectionFailed += ConnectionFailed;
                    Session.Closed           += ConnectionClosed;

                    Session.PasswordProvided += HandlePasswordProvided;
                    Session.SetFramebufferSource(new VncScreenFramebufferSource("Hello World", System.Windows.Forms.Screen.PrimaryScreen));
                    Session.Connect(client.GetStream(), options);
                }
                catch (Exception ex)
                {
                    ExecuteQuery("UPDATE c_machines set STATUS = 'Connection Error',RDPPort='',LastUpdatedDate = GETDATE() WHERE MachineID='" + GV.sMachineID + "';");
                    GM.Error_Log(System.Reflection.MethodBase.GetCurrentMethod(), ex, true, false);
                }
            }
        }
コード例 #10
0
        public void NegotiateSecurityNoSecurityTypesTest()
        {
            using (var stream = new TestStream())
            {
                var session = new VncServerSession();
                session.Connect(stream, null, startThread: false);

                Assert.False(session.NegotiateSecurity(Array.Empty <AuthenticationMethod>()));

                VncStream serverStream = new VncStream(stream.Output);
                stream.Output.Position = 0;

                // Server should have sent a zero-length array, and a message explaining
                // the disconnect reason
                Assert.Equal(0, serverStream.ReceiveByte());
                Assert.Equal("The server and client could not agree on any authentication method.", serverStream.ReceiveString());
            }
        }
コード例 #11
0
        public void NegotiateVersionNot38Test(string version)
        {
            using (var stream = new TestStream())
            {
                // Mimick the client negotiating RFB 3.8
                VncStream clientStream = new VncStream(stream.Input);
                clientStream.SendString(version);
                stream.Input.Position = 0;

                VncServerSession session = new VncServerSession();
                session.Connect(stream, null, startThread: false);

                Assert.True(session.NegotiateVersion(out AuthenticationMethod[] methods));
                Assert.Empty(methods);

                stream.Output.Position = 0;

                Assert.Equal(Encoding.UTF8.GetBytes("RFB 003.008\n"), ((MemoryStream)stream.Output).ToArray());
            }
        }
コード例 #12
0
        public void NegotiateVersionBoth38Test(VncServerSessionOptions sessionOptions, AuthenticationMethod expectedAuthenticationMethod)
        {
            using (var stream = new TestStream())
            {
                // Mimick the client negotiating RFB 3.8
                VncStream clientStream = new VncStream(stream.Input);
                clientStream.SendString("RFB 003.008\n");
                stream.Input.Position = 0;

                VncServerSession session = new VncServerSession();
                session.Connect(stream, sessionOptions, startThread: false);

                Assert.True(session.NegotiateVersion(out AuthenticationMethod[] methods));

                Assert.Collection(
                    methods,
                    (m) => Assert.Equal(expectedAuthenticationMethod, m));

                stream.Output.Position = 0;

                Assert.Equal(Encoding.UTF8.GetBytes("RFB 003.008\n"), ((MemoryStream)stream.Output).ToArray());
            }
        }
コード例 #13
0
        private void ConnectService(TcpClient tcpClient)
        {
            try
            {
                string loalIp = GetLocalIpAddress();

                IPEndPoint remotePoint = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                Console.WriteLine($"VNC连接接入,客户端ip:{remotePoint.Address},端口:{remotePoint.Port}");

                VncServerSessionOptions options = new VncServerSessionOptions();
                //设置需要密码验证
                options.AuthenticationMethod = AuthenticationMethod.Password;

                // 创建一个会话
                VncServerSession session = new VncServerSession();

                session.Connected              += HandleConnected;
                session.ConnectionFailed       += HandleConnectionFailed;
                session.Closed                 += HandleClosed;
                session.PasswordProvided       += HandlePasswordProvided;
                session.CreatingDesktop        += Session_CreatingDesktop;
                session.KeyChanged             += Session_KeyChanged;
                session.PointerChanged         += Session_PointerChanged;
                session.RemoteClipboardChanged += Session_RemoteClipboardChanged;
                //设置分享的屏幕等信息 连接名字 name
                string name = loalIp + ":" + this.servicePort + "--" + remotePoint.Address + ":" + remotePoint.Port;
                VncScreenFramebufferSource vncScreenSource = new VncScreenFramebufferSource(name, Screen.PrimaryScreen);
                session.SetFramebufferSource(vncScreenSource);
                session.Connect(tcpClient, options);

                sessionList.Add(session);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接出现错误,原因:{ex.Message}");
            }
        }
コード例 #14
0
        public void NegotiateSecuritySuccessTest()
        {
            using (var stream = new TestStream())
            {
                // Have the client send authentication method 'None', which is what the server expects
                VncStream clientStream = new VncStream(stream.Input);
                clientStream.SendByte((byte)AuthenticationMethod.None);
                stream.Input.Position = 0;

                var session = new VncServerSession();
                session.Connect(stream, null, startThread: false);

                Assert.True(session.NegotiateSecurity(new AuthenticationMethod[] { AuthenticationMethod.None }));

                VncStream serverStream = new VncStream(stream.Output);
                stream.Output.Position = 0;

                // Server will have offered 1 authentication method, and successfully authenticated
                // the client
                Assert.Equal(1, serverStream.ReceiveByte());                               // 1 authentication method offered
                Assert.Equal((byte)AuthenticationMethod.None, serverStream.ReceiveByte()); // The authentication method offered
                Assert.Equal(0u, serverStream.ReceiveUInt32BE());                          // authentication succeeded
            }
        }
コード例 #15
0
        public void SetDesktopSizeTest()
        {
            var framebuffer1 = new VncFramebuffer("test-1", 100, 200, VncPixelFormat.RGB32);
            var framebuffer2 = new VncFramebuffer("test-2", 200, 400, VncPixelFormat.RGB32);
            var framebuffer  = framebuffer1;

            var framebufferSourceMock = new Mock <IVncFramebufferSource>(MockBehavior.Strict);

            framebufferSourceMock
            .Setup(m => m.SetDesktopSize(200, 300))
            .Returns(ExtendedDesktopSizeStatus.Success)
            .Callback(() => { framebuffer = framebuffer2; });

            framebufferSourceMock
            .Setup(m => m.Capture())
            .Returns(() => framebuffer);

            using (var stream = new TestStream())
            {
                VncStream clientStream = new VncStream(stream.Input);

                // Negotiating the dessktop size
                clientStream.SendByte(0); // share desktop setting

                // Send a SetDesktopSize request
                clientStream.SendByte((byte)VncMessageType.SetDesktopSize);
                clientStream.SendByte(0);       // padding
                clientStream.SendUInt16BE(200); // width
                clientStream.SendUInt16BE(300); // height
                clientStream.SendByte(1);       // number of screens
                clientStream.SendByte(0);       // padding
                clientStream.SendUInt32BE(1);   // screen id
                clientStream.SendUInt16BE(0);   // x position
                clientStream.SendUInt16BE(0);   // x position
                clientStream.SendUInt16BE(200); // width
                clientStream.SendUInt16BE(300); // height
                clientStream.SendUInt32BE(0);   // flags

                stream.Input.Position = 0;

                var session = new VncServerSession();
                session.SetFramebufferSource(framebufferSourceMock.Object);
                session.Connect(stream, null, startThread: false);

                // Negotiate the desktop
                session.NegotiateDesktop();
                Assert.Equal(VncPixelFormat.RGB32, session.ClientPixelFormat);

                // Handle the SetDesktopSize request
                session.HandleMessage();

                VncStream serverStream = new VncStream(stream.Output);
                stream.Output.Position = 0;

                // Desktop negotiation result
                Assert.Equal(100, serverStream.ReceiveUInt16BE());
                Assert.Equal(200, serverStream.ReceiveUInt16BE());
                var format = serverStream.Receive(16);
                Assert.Equal("test-1", serverStream.ReceiveString());

                // SetDesktopSize result
                Assert.Equal(0, serverStream.ReceiveUInt16BE());                                         // Update rectangle request
                Assert.Equal(1, serverStream.ReceiveUInt16BE());                                         // 1 rectangle;

                Assert.Equal((ushort)ExtendedDesktopSizeReason.Client, serverStream.ReceiveUInt16BE());  // x
                Assert.Equal((ushort)ExtendedDesktopSizeStatus.Success, serverStream.ReceiveUInt16BE()); // y
                Assert.Equal(100, serverStream.ReceiveUInt16BE());                                       // width
                Assert.Equal(200, serverStream.ReceiveUInt16BE());                                       // height

                Assert.Equal((int)VncEncoding.ExtendedDesktopSize, (int)serverStream.ReceiveUInt32BE()); // encoding

                Assert.Equal(1u, serverStream.ReceiveByte());                                            // Number of screens
                serverStream.Receive(3);                                                                 // Padding
                Assert.Equal(0u, serverStream.ReceiveUInt32BE());                                        // screen ID
                Assert.Equal(0u, serverStream.ReceiveUInt16BE());                                        // x-position
                Assert.Equal(0u, serverStream.ReceiveUInt16BE());                                        // y-position
                Assert.Equal(100u, serverStream.ReceiveUInt16BE());                                      // width
                Assert.Equal(200u, serverStream.ReceiveUInt16BE());                                      // height
                Assert.Equal(0u, serverStream.ReceiveUInt32BE());                                        // flags

                Assert.Equal(stream.Output.Length, stream.Output.Position);
                Assert.Equal(stream.Input.Length, stream.Input.Position);
            }
        }
コード例 #16
0
        public void ConnectNullTest()
        {
            var session = new VncServerSession();

            Assert.Throws <ArgumentNullException>(() => session.Connect(null, null));
        }