/// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context"></param>
        public Rdpbcgr_DVCServerTransport(RdpbcgrServerSessionContext context)
        {
            this.sessionContext = context;

            if (sessionContext.SVCManager == null)
            {
                throw new NotSupportedException("Cannot get SVC from RDPBCGR connection for RDPEDYC, this transport must be created after RDPBCGR connection established.");
            }

            channel = sessionContext.SVCManager.GetChannelByName(StaticVirtualChannelName.RDPEDYC);
            if (channel == null)
            {
                throw new NotSupportedException("Cannot get SVC from RDPBCGR connection for RDPEDYC, the static virtual channel is not created.");
            }

            channel.Received += ReceivedBytes;

            if (!sessionContext.SVCManager.IsRunning)
            {
                // Better start the SVC manager here, so as to make sure the first packet of RDPEDYC can be processed
                // it is not same restrict as client, since the first packet is sent by server
                sessionContext.SVCManager.Start();
            }

            decoder    = new ServerDecodingPduBuilder();
            pduBuilder = new PduBuilder();
        }
 /// <summary>
 /// Accept an existing RDP session which established outside.
 /// </summary>
 /// <param name="rdpbcgrServer">RdpbcgrServer object.</param>
 /// <param name="serverContext">RdpbcgrServerSessionContext object.</param>
 public void Accept(RdpbcgrServer rdpbcgrServer, RdpbcgrServerSessionContext serverContext)
 {
     this.rdpbcgrAdapter        = Site.GetAdapter <IRdpbcgrAdapter>();
     this.rdpbcgrServerStack    = rdpbcgrServer;
     this.rdpbcgrSessionContext = serverContext;
     this.rdpbcgrAdapter.TS_FRAME_ACKNOWLEDGE_PDUReceived += new TS_FRAME_ACKNOWLEDGE_PDUHandler(this.VerifyTS_FRAME_ACKNOWLEDGE_PDU);
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="connectedRdpServer"></param>
        /// <param name="context"></param>
        /// <param name="transportType"></param>
        public Rdpemt_DVCServerTransport(RdpbcgrServer connectedRdpServer, RdpbcgrServerSessionContext context, DynamicVC_TransportType transportType)
        {
            this.serverSessionContext = context;
            this.rdpbcgrServer        = connectedRdpServer;
            this.transportProtocol    = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECR;
            if (transportType == DynamicVC_TransportType.RDP_UDP_Lossy)
            {
                this.transportProtocol = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECL;
            }

            if (!serverSessionContext.IsClientMultitransportChannelDataRecieved)
            {
                throw new NotSupportedException("This RDP connection doesn't support multiple transport!");
            }

            try
            {
                EstablishTransportConnection();
            }
            catch (Exception)
            {
                // Ensure resource can be released properly if exception occurred in Constructor
                Dispose();
                // Not suppress the exception, transfer the error to test result.
                throw;
            }

            decoder    = new ServerDecodingPduBuilder();
            pduBuilder = new PduBuilder();
        }
 public Server_Demand_Active_Pdu_Ex(Server_Demand_Active_Pdu orgPdu, RdpbcgrServerSessionContext serverSessionContext)
     : base(serverSessionContext)
 {
     this.commonHeader = orgPdu.commonHeader;
     //this.commonHeader.tpktHeader = orgPdu.commonHeader.tpktHeader;
     //this.commonHeader.x224Data = orgPdu.commonHeader.x224Data;
     //this.commonHeader.securityHeader = orgPdu.commonHeader.securityHeader;
     this.demandActivePduData = orgPdu.demandActivePduData;
 }
 /// <summary>
 /// Only on RDPEUDP Server can exist
 /// </summary>
 /// <param name="context"></param>
 private void CreateRdpeudpServer(RdpbcgrServerSessionContext context)
 {
     if (rdpeudpServer == null)
     {
         rdpeudpServer = new RdpeudpServer((IPEndPoint)context.LocalIdentity);
     }
     //if (!rdpeudpServer.Running)
     rdpeudpServer.Start();
 }
 /// <summary>
 /// Remove session context from server context. If connection does not exists, do nothing.
 /// </summary>
 /// <param name="sessionContext">Add session context.</param>
 internal void RemoveSession(RdpbcgrServerSessionContext sessionContext)
 {
     lock (this.sessions)
     {
         if (this.SessionContexts.Contains(sessionContext))
         {
             this.sessions.Remove(sessionContext);
         }
     }
 }
        /// <summary>
        /// Add session context to server context.
        /// </summary>
        /// <param name="sessionContext">Add session context.</param>
        internal void AddSession(RdpbcgrServerSessionContext sessionContext)
        {
            lock (this.sessions)
            {
                if (this.sessions.Contains(sessionContext))
                {
                    throw new InvalidOperationException(
                              "the sessionContext is exists in the sessionContext collection, can not add duplicate sessionContext");
                }

                this.sessions.Add(sessionContext);
            }
        }
 /// <summary>
 /// Only on RDPEUDP Server can exist
 /// </summary>
 /// <param name="context"></param>
 private static void CreateRdpeudpServer(RdpbcgrServerSessionContext context)
 {
     if (rdpeudpServer == null)
     {
         lock (rdpeudpServerLock)
         {
             if (rdpeudpServer == null)
             {
                 rdpeudpServer = new RdpeudpServer((IPEndPoint)context.LocalIdentity);
                 rdpeudpServer.Start();
             }
         }
     }
 }
Exemplo n.º 9
0
        public static TS_FP_UPDATE_PDU CreateFPUpdatePDU(RdpbcgrServerSessionContext context, TS_FP_UPDATE update)
        {
            TS_FP_UPDATE_PDU fpOutput = new TS_FP_UPDATE_PDU(context);

            fpOutput.fpOutputHeader = new nested_TS_FP_UPDATE_PDU_fpOutputHeader();

            fpOutput.dataSignature = null;
            fpOutput.length1       = 0;
            fpOutput.length2       = 0;

            fpOutput.fpOutputUpdates    = new TS_FP_UPDATE[1];
            fpOutput.fpOutputUpdates[0] = update;

            return(fpOutput);
        }
Exemplo n.º 10
0
        public static TS_FP_UPDATE_PDU CreateFPUpdatePDU(RdpbcgrServerSessionContext context, TS_FP_UPDATE update)
        {
            TS_FP_UPDATE_PDU fpOutput = new TS_FP_UPDATE_PDU(context);

            fpOutput.fpOutputHeader = (byte)(((int)nested_TS_FP_UPDATE_PDU_fpOutputHeader_actionCode_Values.FASTPATH_OUTPUT_ACTION_FASTPATH & 0x03)
                                             | ((int)((int)reserved_Values.V1 & 0x0f) << 2));
            fpOutput.dataSignature = null;
            fpOutput.length1       = 0;
            fpOutput.length2       = 0;

            fpOutput.fpOutputUpdates    = new TS_FP_UPDATE[1];
            fpOutput.fpOutputUpdates[0] = update;

            return(fpOutput);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="server"></param>
        /// <param name="context"></param>
        public RdpedycServer(RdpbcgrServer server, RdpbcgrServerSessionContext context, bool autoCloseChannel = true)
        {
            this.rdpbcgrServer         = server;
            this.sessionContext        = context;
            transportDic               = new Dictionary <DynamicVC_TransportType, IDVCTransport>();
            unprocessedDVCPacketBuffer = new List <UnprocessedDVCPDUInfo>();
            Rdpbcgr_DVCServerTransport transport = new Rdpbcgr_DVCServerTransport(context);

            channelDicbyId = new Dictionary <uint, DynamicVirtualChannel>();

            pduBuilder = new PduBuilder();

            transport.Received += ProcessPacketFromTCP;
            transportDic.Add(DynamicVC_TransportType.RDP_TCP, transport);

            this.autoCloseChannel = autoCloseChannel;
        }
        public SlowPathOutputPduEx(SlowPathOutputPdu orgPdu, RdpbcgrServerSessionContext serverSessionContext) : base(serverSessionContext)
        {
            this.commonHeader = orgPdu.commonHeader;

            if (orgPdu.slowPathUpdates != null)
            {
                Collection <RdpbcgrSlowPathUpdatePdu> updates = new Collection <RdpbcgrSlowPathUpdatePdu>();
                for (int i = 0; i < orgPdu.slowPathUpdates.Length; ++i)
                {
                    updates.Add(orgPdu.slowPathUpdates[i]);
                }

                this.slowPathUpdates = new RdpbcgrSlowPathUpdatePdu[updates.Count];
                for (int i = 0; i < updates.Count; ++i)
                {
                    this.slowPathUpdates[i] = updates[i];
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="connectedRdpServer"></param>
        /// <param name="context"></param>
        /// <param name="transportType"></param>
        public Rdpemt_DVCServerTransport(RdpbcgrServer connectedRdpServer, RdpbcgrServerSessionContext context, DynamicVC_TransportType transportType)
        {
            this.serverSessionContext = context;
            this.rdpbcgrServer        = connectedRdpServer;
            this.transportProtocol    = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECR;
            if (transportType == DynamicVC_TransportType.RDP_UDP_Lossy)
            {
                this.transportProtocol = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECL;
            }

            if (!serverSessionContext.IsClientMultitransportChannelDataRecieved)
            {
                throw new NotSupportedException("This RDP connection doesn't support multiple transport!");
            }

            EstablishTransportConnection();

            decoder    = new ServerDecodingPduBuilder();
            pduBuilder = new PduBuilder();
        }
Exemplo n.º 14
0
        internal static void EncodeSlowPathPdu(List <byte> sendBuffer,
                                               SlowPathPduCommonHeader commonHeader,
                                               byte[] dataBody,
                                               RdpbcgrServerSessionContext context)
        {
            EncodeStructure(sendBuffer, commonHeader.tpktHeader);
            EncodeStructure(sendBuffer, commonHeader.x224Data);

            List <byte> securityBuffer = new List <byte>();

            EncodeSecurityData(securityBuffer, commonHeader.securityHeader, dataBody, context);

            SendDataIndication securityExchange = new SendDataIndication(new UserId(commonHeader.initiator),
                                                                         new ChannelId(commonHeader.channelId),
                                                                         new DataPriority(ConstValue.SEND_DATA_REQUEST_PRIORITY),
                                                                         ConstValue.SEND_DATA_REQUEST_SEGMENTATION,
                                                                         new Asn1OctetString(securityBuffer.ToArray()));
            DomainMCSPDU mcsDomain = new DomainMCSPDU(DomainMCSPDU.sendDataIndication, securityExchange);

            EncodeDomainMcsPdu(sendBuffer, mcsDomain);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context"></param>
        public ServerStaticVirtualChannelManager(RdpbcgrServerSessionContext context)
        {
            this.context          = context;
            this.channelDicById   = new Dictionary <ushort, StaticVirtualChannel>();
            this.channelDicByName = new Dictionary <string, StaticVirtualChannel>();
            ushort[]      virtualChannelIds     = context.VirtualChannelIdStore;
            CHANNEL_DEF[] virtualChannelDefines = context.VirtualChannelDefines;
            if (virtualChannelIds != null && virtualChannelDefines != null &&
                virtualChannelIds.Length == virtualChannelDefines.Length)
            {
                CompressionType compressType = context.VirtualChannelSCCompressionType;
                if (context.CompressionTypeSupported == CompressionType.PACKET_COMPR_TYPE_NONE)
                {
                    compressType = CompressionType.PACKET_COMPR_TYPE_NONE;
                }
                else if (context.CompressionTypeSupported == CompressionType.PACKET_COMPR_TYPE_RDP6 ||
                         context.CompressionTypeSupported == CompressionType.PACKET_COMPR_TYPE_RDP61)
                {
                    compressType = CompressionType.PACKET_COMPR_TYPE_64K;
                }

                for (int i = 0; i < virtualChannelIds.Length; ++i)
                {
                    string name = virtualChannelDefines[i].name;
                    if (name != null)
                    {
                        name = name.Replace("\0", string.Empty).ToUpper();
                    }
                    StaticVirtualChannel channel = new ServerStaticVirtualChannel(virtualChannelIds[i],
                                                                                  name,
                                                                                  virtualChannelDefines[i].options,
                                                                                  context.VCChunkSize,
                                                                                  compressType,
                                                                                  context.VirtualChannelCSCompressionType,
                                                                                  SendPacket);
                    channelDicById.Add(virtualChannelIds[i], channel);
                    channelDicByName.Add(name, channel);
                }
            }
        }
        /// <summary>
        /// Expect a packet
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="waitTimeSpan"></param>
        /// <returns></returns>
        private T ExpectPacket <T>(RdpbcgrServerSessionContext session, TimeSpan waitTimeSpan) where T : StackPacket
        {
            DateTime endTime     = DateTime.Now + waitTimeSpan;
            object   receivedPdu = null;

            while (waitTimeSpan.TotalMilliseconds > 0)
            {
                try
                {
                    receivedPdu = this.rdpbcgrServerStack.ExpectPdu(session, waitTimeSpan);
                }
                catch (TimeoutException)
                {
                }
                if (receivedPdu is T)
                {
                    return((T)receivedPdu);
                }
                waitTimeSpan = endTime - DateTime.Now;
            }
            throw new TimeoutException("Timeout when expecting " + typeof(T).Name + " message.");
        }
        /// <summary>
        /// Establish RDP Connection
        /// </summary>
        private void EstablishRDPConnection()
        {
            sessionContext = rdpbcgrServerStack.ExpectConnect(timeout);

            #region Connection Initial
            x224ConnectionRequest = ExpectPacket <Client_X_224_Connection_Request_Pdu>(sessionContext, timeout);
            Server_X_224_Connection_Confirm_Pdu confirmPdu
                = rdpbcgrServerStack.CreateX224ConnectionConfirmPdu(sessionContext, selectedProtocols_Values.PROTOCOL_RDP_FLAG, RDP_NEG_RSP_flags_Values.DYNVC_GFX_PROTOCOL_SUPPORTED | RDP_NEG_RSP_flags_Values.EXTENDED_CLIENT_DATA_SUPPORTED);

            SendPdu(confirmPdu);

            if (bool.Parse(detectInfo.IsWindowsImplementation))
            {
                RdpbcgrServerSessionContext orgSession = sessionContext;
                sessionContext = rdpbcgrServerStack.ExpectConnect(timeout);
                if (sessionContext.Identity == orgSession.Identity)
                {
                    sessionContext = rdpbcgrServerStack.ExpectConnect(timeout);
                }
                x224ConnectionRequest = ExpectPacket <Client_X_224_Connection_Request_Pdu>(sessionContext, timeout);
                confirmPdu            = rdpbcgrServerStack.CreateX224ConnectionConfirmPdu(sessionContext, selectedProtocols_Values.PROTOCOL_RDP_FLAG, RDP_NEG_RSP_flags_Values.DYNVC_GFX_PROTOCOL_SUPPORTED | RDP_NEG_RSP_flags_Values.EXTENDED_CLIENT_DATA_SUPPORTED);

                SendPdu(confirmPdu);
            }
            #endregion Connection Initial

            #region Basic Setting Exchange

            mscConnectionInitialPDU = ExpectPacket <Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(sessionContext, timeout);

            SERVER_CERTIFICATE cert = null;
            int certLen             = 0;
            int dwKeysize           = 2048;

            byte[] privateExp, publicExp, modulus;
            cert    = rdpbcgrServerStack.GenerateCertificate(dwKeysize, out privateExp, out publicExp, out modulus);
            certLen = 120 + dwKeysize / 8;

            Server_MCS_Connect_Response_Pdu_with_GCC_Conference_Create_Response connectRespPdu = rdpbcgrServerStack.CreateMCSConnectResponsePduWithGCCConferenceCreateResponsePdu(
                sessionContext,
                EncryptionMethods.ENCRYPTION_METHOD_128BIT,
                EncryptionLevel.ENCRYPTION_LEVEL_LOW,
                cert,
                certLen,
                MULTITRANSPORT_TYPE_FLAGS.TRANSPORTTYPE_UDPFECL | MULTITRANSPORT_TYPE_FLAGS.TRANSPORTTYPE_UDPFECR);
            SendPdu(connectRespPdu);

            sessionContext.ServerPrivateExponent = new byte[privateExp.Length];
            Array.Copy(privateExp, sessionContext.ServerPrivateExponent, privateExp.Length);

            #endregion Basic Setting Exchange

            #region Channel Connection

            ExpectPacket <Client_MCS_Erect_Domain_Request>(sessionContext, timeout);
            ExpectPacket <Client_MCS_Attach_User_Request>(sessionContext, timeout);

            Server_MCS_Attach_User_Confirm_Pdu attachUserConfirmPdu = rdpbcgrServerStack.CreateMCSAttachUserConfirmPdu(sessionContext);
            SendPdu(attachUserConfirmPdu);

            //Join Channel
            int channelNum = 2;
            if (sessionContext.VirtualChannelIdStore != null)
            {
                channelNum += sessionContext.VirtualChannelIdStore.Length;
            }
            if (sessionContext.IsServerMessageChannelDataSend)
            {
                channelNum++;
            }
            for (int i = 0; i < channelNum; i++)
            {
                Client_MCS_Channel_Join_Request     channelJoinPdu      = ExpectPacket <Client_MCS_Channel_Join_Request>(sessionContext, timeout);
                Server_MCS_Channel_Join_Confirm_Pdu channelJoinResponse = rdpbcgrServerStack.CreateMCSChannelJoinConfirmPdu(
                    sessionContext,
                    channelJoinPdu.mcsChannelId);
                SendPdu(channelJoinResponse);
            }
            #endregion Channel Connection

            #region RDP Security Commencement

            securityExchangePDU = ExpectPacket <Client_Security_Exchange_Pdu>(sessionContext, timeout);

            #endregion RDP Security Commencement

            #region Secure Setting Exchange
            clientInfoPDU = ExpectPacket <Client_Info_Pdu>(sessionContext, timeout);
            #endregion Secure Setting Exchange

            #region Licensing
            Server_License_Error_Pdu_Valid_Client licensePdu = rdpbcgrServerStack.CreateLicenseErrorMessage(sessionContext);
            SendPdu(licensePdu);
            #endregion Licensing

            #region Capabilities Exchange

            RdpbcgrCapSet capSet = new RdpbcgrCapSet();
            capSet.GenerateCapabilitySets();
            Server_Demand_Active_Pdu demandActivePdu = rdpbcgrServerStack.CreateDemandActivePdu(sessionContext, capSet.CapabilitySets);
            SendPdu(demandActivePdu);

            confirmActivePDU            = ExpectPacket <Client_Confirm_Active_Pdu>(sessionContext, timeout);
            clientCapSet                = new RdpbcgrCapSet();
            clientCapSet.CapabilitySets = confirmActivePDU.confirmActivePduData.capabilitySets;
            #endregion Capabilities Exchange

            #region Connection Finalization
            ExpectPacket <Client_Synchronize_Pdu>(sessionContext, timeout);

            Server_Synchronize_Pdu synchronizePdu = rdpbcgrServerStack.CreateSynchronizePdu(sessionContext);
            SendPdu(synchronizePdu);

            Server_Control_Pdu controlCooperatePdu = rdpbcgrServerStack.CreateControlCooperatePdu(sessionContext);
            SendPdu(controlCooperatePdu);

            ExpectPacket <Client_Control_Pdu_Cooperate>(sessionContext, timeout);

            ExpectPacket <Client_Control_Pdu_Request_Control>(sessionContext, timeout);

            Server_Control_Pdu controlGrantedPdu = rdpbcgrServerStack.CreateControlGrantedPdu(sessionContext);
            SendPdu(controlGrantedPdu);


            ITsCapsSet cap = this.clientCapSet.FindCapSet(capabilitySetType_Values.CAPSTYPE_BITMAPCACHE_REV2);
            if (cap != null)
            {
                TS_BITMAPCACHE_CAPABILITYSET_REV2 bitmapCacheV2 = (TS_BITMAPCACHE_CAPABILITYSET_REV2)cap;
                if ((bitmapCacheV2.CacheFlags & CacheFlags_Values.PERSISTENT_KEYS_EXPECTED_FLAG) != 0)
                {
                    ExpectPacket <Client_Persistent_Key_List_Pdu>(sessionContext, timeout);
                }
            }

            ExpectPacket <Client_Font_List_Pdu>(sessionContext, timeout);

            Server_Font_Map_Pdu fontMapPdu = rdpbcgrServerStack.CreateFontMapPdu(sessionContext);
            SendPdu(fontMapPdu);

            #endregion Connection Finalization

            // Init for RDPEDYC
            try
            {
                rdpedycServer = new RdpedycServer(rdpbcgrServerStack, sessionContext);
                rdpedycServer.ExchangeCapabilities(timeout);
            }
            catch (Exception)
            {
                rdpedycServer = null;
            }
        }
 public Virtual_Channel_RAW_Server_Pdu_Ex(Virtual_Channel_RAW_Server_Pdu orgPdu, RdpbcgrServerSessionContext serverSessionContext)
     : base(serverSessionContext)
 {
     this.commonHeader       = orgPdu.commonHeader;
     this.channelPduHeader   = orgPdu.channelPduHeader;
     this.virtualChannelData = orgPdu.virtualChannelData;
 }
 public Server_MCS_Connect_Response_Pdu_with_GCC_Conference_Create_Response_Ex(Server_MCS_Connect_Response_Pdu_with_GCC_Conference_Create_Response orgPdu, RdpbcgrServerSessionContext serverSessionContext, NegativeType invalidType)
     : base(serverSessionContext)
 {
     this.tpktHeader  = orgPdu.tpktHeader;
     this.x224Data    = orgPdu.x224Data;
     this.mcsCrsp     = orgPdu.mcsCrsp;
     this.invalidType = invalidType;
 }
Exemplo n.º 20
0
        internal static void EncodeSecurityData(List <byte> buffer,
                                                TS_SECURITY_HEADER securityHeader,
                                                byte[] dataBody,
                                                RdpbcgrServerSessionContext context)
        {
            if (securityHeader != null)       // have a security header
            {
                EncodeStructure(buffer, (ushort)securityHeader.flags);
                EncodeStructure(buffer, securityHeader.flagsHi);

                if (securityHeader.GetType() == typeof(TS_SECURITY_HEADER1))   // non-fips security header
                {
                    if (dataBody != null && context != null)
                    {
                        TS_SECURITY_HEADER1 nonFipsHeader = securityHeader as TS_SECURITY_HEADER1;
                        byte[] dataSignature = null;

                        bool isSalted = (nonFipsHeader.flags & TS_SECURITY_HEADER_flags_Values.SEC_SECURE_CHECKSUM)
                                        == TS_SECURITY_HEADER_flags_Values.SEC_SECURE_CHECKSUM;
                        context.ServerEncrypt(dataBody, isSalted, out dataBody, out dataSignature);

                        // If the data signature has not been set, generate it.
                        // Otherwise, keep the old value.
                        if (nonFipsHeader.dataSignature == null)
                        {
                            nonFipsHeader.dataSignature = dataSignature;
                        }

                        EncodeBytes(buffer, nonFipsHeader.dataSignature);
                    }
                }
                else if (securityHeader.GetType() == typeof(TS_SECURITY_HEADER2))   // fips security header
                {
                    if (dataBody != null && context != null)
                    {
                        TS_SECURITY_HEADER2 fipsHeader = securityHeader as TS_SECURITY_HEADER2;
                        byte[] dataSignature           = null;
                        EncodeStructure(buffer, (ushort)fipsHeader.length);
                        EncodeStructure(buffer, fipsHeader.version);

                        // If the padlen equals 0, calculate it.
                        // Otherwise, keep the old value.
                        if (fipsHeader.padlen == 0)
                        {
                            fipsHeader.padlen = (byte)(ConstValue.TRIPLE_DES_PAD
                                                       - (dataBody.Length % ConstValue.TRIPLE_DES_PAD));
                        }

                        EncodeStructure(buffer, fipsHeader.padlen);
                        context.ServerEncrypt(dataBody, false, out dataBody, out dataSignature);

                        // If the data signature has not been set, generate it.
                        // Otherwise, keep the old value.
                        if (fipsHeader.dataSignature == null)
                        {
                            fipsHeader.dataSignature = dataSignature;
                        }

                        EncodeBytes(buffer, fipsHeader.dataSignature);
                    }
                }
            }

            EncodeBytes(buffer, dataBody);
        }
Exemplo n.º 21
0
        private void AcceptLoopInternal()
        {
            listenSock = new Socket(config.LocalIpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            var streamType = config.StreamType;

            var endPoint = new IPEndPoint(config.LocalIpAddress, config.LocalIpPort);

            listenSock.Bind(endPoint);

            listenSock.Listen(config.MaxConnections);

            UpdateSocketBlockingMode(listenSock, false);

            while (!acceptThreadCancellationTokenSource.IsCancellationRequested)
            {
                if (this.receivingStreams.Count >= config.MaxConnections)
                {
                    // not listen untill the current connections are less than the max value.
                    // the interval to query is 1 seconds:
                    Thread.Sleep(1000);
                    continue;
                }

                Socket socket = null;
                try
                {
                    socket = this.listenSock.Accept();

                    UpdateSocketBlockingMode(socket, true);
                }
                catch (SocketException socketException)
                {
                    if (socketException.SocketErrorCode == SocketError.WouldBlock)
                    {
                        continue;
                    }

                    throw;
                }

                TransportEvent connectEvent;

                Stream receiveStream = null;
                Stream baseStream    = new NetworkStream(socket);
                switch (streamType)
                {
                case SecurityStreamType.None:
                    receiveStream = baseStream;
                    break;

                case SecurityStreamType.CredSsp:
                    string targetSPN = ConstValue.CREDSSP_SERVER_NAME_PREFIX + config.LocalIpAddress;

                    var csspServer = new CsspServer(new ETWStream(baseStream));

                    var credSspStream = csspServer.GetStream();

                    csspServer.Authenticate(cert, targetSPN);

                    receiveStream = credSspStream;
                    break;

                default:
                    receiveStream = baseStream;
                    break;
                }

                // Start receive thread with non-blocking mode.
                UpdateSocketBlockingMode(socket, false);

                RdpbcgrReceiveThread receiveThread = new RdpbcgrReceiveThread(
                    socket.RemoteEndPoint,
                    this.packetQueue,
                    this.decoder,
                    receiveStream,
                    this.config.BufferSize
                    );

                connectEvent = new TransportEvent(EventType.Connected, socket.RemoteEndPoint, null);

                RdpbcgrServerSessionContext session = new RdpbcgrServerSessionContext();
                session.Identity                  = connectEvent.EndPoint;
                session.Server                    = this.rdpbcgrServer;
                session.LocalIdentity             = socket.LocalEndPoint;
                session.IsClientToServerEncrypted = this.rdpbcgrServer.IsClientToServerEncrypted;
                this.rdpbcgrServer.ServerContext.AddSession(session);

                this.packetQueue.AddObject(connectEvent);

                lock (this.receivingStreams)
                {
                    this.receivingStreams.Add(socket, receiveThread);
                }

                receiveThread.Start();
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Creates a new Socket for a newly created connection and  a new thread to receive packet in the loop.
        /// </summary>
        private void AcceptLoop()
        {
            while (!exitLoop)
            {
                if (this.receivingStreams.Count >= config.MaxConnections)
                {
                    // not listen untill the current connections are less than the max value.
                    // the interval to query is 1 seconds:
                    Thread.Sleep(1000);
                    continue;
                }

                Socket socket = null;
                try
                {
                    socket = this.listenSock.Accept();
                }
                catch (SocketException)
                {
                    exitLoop = true;
                    continue;
                }

                TransportEvent connectEvent;

                Stream receiveStream = null;
                Stream baseStream    = new NetworkStream(socket);
                switch (streamType)
                {
                case SecurityStreamType.None:
                    receiveStream = baseStream;
                    break;

                case SecurityStreamType.Ssl:
                    receiveStream = new SslStream(
                        new ETWStream(
                            baseStream),
                        false
                        );
                    ((SslStream)receiveStream).AuthenticateAsServer(cert);
                    break;

                case SecurityStreamType.CredSsp:
                    string targetSPN = ConstValue.CREDSSP_SERVER_NAME_PREFIX + config.LocalIpAddress;

                    var csspServer = new CsspServer(new ETWStream(baseStream));

                    var credSspStream = csspServer.GetStream();

                    csspServer.Authenticate(cert, targetSPN);

                    receiveStream = credSspStream;
                    break;

                default:
                    receiveStream = baseStream;
                    break;
                }

                RdpbcgrReceiveThread receiveThread = new RdpbcgrReceiveThread(
                    socket.RemoteEndPoint,
                    this.packetQueue,
                    this.decoder,
                    receiveStream,
                    this.config.BufferSize,
                    this.rdpbcgrServer);

                connectEvent = new TransportEvent(EventType.Connected, socket.RemoteEndPoint, null);

                RdpbcgrServerSessionContext session = new RdpbcgrServerSessionContext();
                session.Identity                  = connectEvent.EndPoint;
                session.Server                    = this.rdpbcgrServer;
                session.LocalIdentity             = socket.LocalEndPoint;
                session.IsClientToServerEncrypted = this.rdpbcgrServer.IsClientToServerEncrypted;
                this.rdpbcgrServer.ServerContext.AddSession(session);

                this.packetQueue.AddObject(connectEvent);

                lock (this.receivingStreams)
                {
                    this.receivingStreams.Add(socket, receiveThread);
                }

                receiveThread.Start();
            }
        }
 public Server_License_Error_Pdu_Valid_Client_Ex(Server_License_Error_Pdu_Valid_Client orgPdu, RdpbcgrServerSessionContext serverSessionContext)
     : base(serverSessionContext)
 {
     this.commonHeader       = orgPdu.commonHeader;
     this.preamble           = orgPdu.preamble;
     this.validClientMessage = orgPdu.validClientMessage;
 }