Ejemplo n.º 1
0
        public UpgradeHandshaker(IDictionary<string, object> handshakeEnvironment)
        {
            InternalSocket = (SecureSocket) handshakeEnvironment["secureSocket"];
            _end = (ConnectionEnd) handshakeEnvironment["end"];
            _responseReceivedRaised = new ManualResetEvent(false);
            OnResponseReceived += ResponseReceivedHandler;
               _handshakeResult = new Dictionary<string, object>();

            if (_end == ConnectionEnd.Client)
            {
                if (handshakeEnvironment.ContainsKey(":host") || (handshakeEnvironment[":host"] is string)
                    || handshakeEnvironment.ContainsKey(":version") || (handshakeEnvironment[":version"] is string))
                {
                    _headers = new Dictionary<string, string>
                        {
                            {":host", (string) handshakeEnvironment[":host"]},
                            {":version", (string) handshakeEnvironment[":version"]}
                        };
                }
                else
                {
                    throw new ArgumentException("Incorrect header for upgrade handshake");
                }
            }
        }
Ejemplo n.º 2
0
        public UpgradeHandshaker(IDictionary <string, object> handshakeEnvironment)
        {
            InternalSocket          = (SecureSocket)handshakeEnvironment["secureSocket"];
            _end                    = (ConnectionEnd)handshakeEnvironment["end"];
            _responseReceivedRaised = new ManualResetEvent(false);
            _handshakeResult        = new Dictionary <string, object>();

            if (_end == ConnectionEnd.Client)
            {
                if (handshakeEnvironment.ContainsKey(":host") || (handshakeEnvironment[":host"] is string) ||
                    handshakeEnvironment.ContainsKey(":version") || (handshakeEnvironment[":version"] is string))
                {
                    _headers = new Dictionary <string, string>
                    {
                        { ":path", (string)handshakeEnvironment[":path"] },
                        { ":host", (string)handshakeEnvironment[":host"] },
                        { ":version", (string)handshakeEnvironment[":version"] }
                    };
                }
                else
                {
                    throw new InvalidConstraintException("Incorrect header for upgrade handshake");
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Http2OwinMessageHandler"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="end"></param>
 /// <param name="transportInfo">The transport information.</param>
 /// <param name="next">The next layer delegate.</param>
 /// <param name="cancel">The cancellation token.</param>
 public Http2OwinMessageHandler(DuplexStream stream, ConnectionEnd end, TransportInformation transportInfo,
                         AppFunc next, CancellationToken cancel)
     : base(stream, end, stream.IsSecure, transportInfo, cancel)
 {
     _next = next;
     stream.OnClose += delegate { Dispose(); };
 }
Ejemplo n.º 4
0
        private byte[] GetKey(ConnectionEnd end, ConnectionDirection direction)
        {
            switch (end)
            {
            case ConnectionEnd.Client:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_keyConfig.Server ?? throw new InvalidOperationException("Server key is not initialized"));

                case ConnectionDirection.Write:
                    return(_keyConfig.Client ?? throw new InvalidOperationException("Client key is not initialized"));

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            case ConnectionEnd.Server:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_keyConfig.Client ?? throw new InvalidOperationException("Client key is not initialized"));

                case ConnectionDirection.Write:
                    return(_keyConfig.Server ?? throw new InvalidOperationException("Server key is not initialized"));

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            default:
                throw new ArgumentOutOfRangeException(nameof(end), end, null);
            }
        }
Ejemplo n.º 5
0
        public UpgradeHandshaker(IDictionary <string, object> handshakeEnvironment)
        {
            IoStream         = (Stream)handshakeEnvironment[HandshakeKeys.Stream];
            _end             = (ConnectionEnd)handshakeEnvironment[HandshakeKeys.ConnectionEnd];
            _handshakeResult = new Dictionary <string, object>();

            if (_end == ConnectionEnd.Client)
            {
                if (handshakeEnvironment.ContainsKey(CommonHeaders.Host) || (handshakeEnvironment[CommonHeaders.Host] is string) ||
                    handshakeEnvironment.ContainsKey(CommonHeaders.Version) || (handshakeEnvironment[CommonHeaders.Version] is string))
                {
                    _headers = new Dictionary <string, object>
                    {
                        { CommonHeaders.Path, handshakeEnvironment[CommonHeaders.Path] },
                        { CommonHeaders.Host, handshakeEnvironment[CommonHeaders.Host] },
                        { CommonHeaders.Version, handshakeEnvironment[CommonHeaders.Version] },
                        { CommonHeaders.MaxConcurrentStreams, Constants.DefaultMaxConcurrentStreams },
                        { CommonHeaders.InitialWindowSize, Constants.InitialFlowControlWindowSize },
                    };
                }
                else
                {
                    throw new InvalidConstraintException("Incorrect header for upgrade handshake");
                }
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Http2OwinMessageHandler"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="end"></param>
 /// <param name="isSecure"></param>
 /// <param name="next">The next layer delegate.</param>
 /// <param name="cancel">The cancellation token.</param>
 public Http2OwinMessageHandler(Stream stream, ConnectionEnd end, bool isSecure,
                                AppFunc next, CancellationToken cancel)
     : base(stream, end, isSecure, cancel)
 {
     _next = next;
     _session.OnSessionDisposed += delegate { Dispose(); };
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Create a new HandshakeLayer object given a SecureChannel and which end of the connection it is to be.
        /// </summary>
        /// <param name="secureChannel">the SecureChannel that comprises the secure functionality of this layer</param>
        /// <param name="connectionEnd">this specifies which end of the connection - Server or Client</param>
        public HandshakeLayer(SecureChannel secureChannel, ConnectionEnd connectionEnd)
        {
            // SHA256 is a class that computes the SHA-256 (SHA stands for Standard Hashing Algorithm) of it's input.
            m_localHash = SHA256.Create();
            m_remoteHash = SHA256.Create();

            m_secureChannel = secureChannel;
            SecurityParameters = new SecurityParameters
            {
                Entity = connectionEnd,
                CompressionAlgorithm = CompressionMethod.Null,
                PRFAlgorithm = PRFAlgorithm.SHA256,
                CipherType = CipherType.Block
            };

            AllowedCipherSuites = new[]
            {
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA
            };

            VerifyCertificate = c => c.Verify();
        }
Ejemplo n.º 8
0
        public UpgradeHandshaker(IDictionary<string, object> handshakeEnvironment)
        {
            IoStream = (Stream)handshakeEnvironment[HandshakeKeys.Stream];
            _end = (ConnectionEnd)handshakeEnvironment[HandshakeKeys.ConnectionEnd];
            _handshakeResult = new Dictionary<string, object>();

            if (_end == ConnectionEnd.Client)
            {
                if (handshakeEnvironment.ContainsKey(CommonHeaders.Host) || (handshakeEnvironment[CommonHeaders.Host] is string)
                    || handshakeEnvironment.ContainsKey(CommonHeaders.Version) || (handshakeEnvironment[CommonHeaders.Version] is string))
                {
                    _headers = new Dictionary<string, object>
                        {
                            {CommonHeaders.Path, handshakeEnvironment[CommonHeaders.Path]},
                            {CommonHeaders.Host, handshakeEnvironment[CommonHeaders.Host]},
                            {CommonHeaders.Version, handshakeEnvironment[CommonHeaders.Version]},
                            {CommonHeaders.MaxConcurrentStreams, 100},
                            {CommonHeaders.InitialWindowSize, 2000000},
                        };
                }
                else
                {
                    throw new InvalidConstraintException("Incorrect header for upgrade handshake");
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create a new HandshakeLayer object given a SecureChannel and which end of the connection it is to be.
        /// </summary>
        /// <param name="secureChannel">the SecureChannel that comprises the secure functionality of this layer</param>
        /// <param name="connectionEnd">this specifies which end of the connection - Server or Client</param>
        public HandshakeLayer(SecureChannel secureChannel, ConnectionEnd connectionEnd)
        {
            // SHA256 is a class that computes the SHA-256 (SHA stands for Standard Hashing Algorithm) of it's input.
            m_localHash  = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); //SHA256.Create();
            m_remoteHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); // SHA256.Create();

            m_secureChannel    = secureChannel;
            SecurityParameters = new SecurityParameters
            {
                Entity = connectionEnd,
                CompressionAlgorithm = CompressionMethod.Null,
                PRFAlgorithm         = PRFAlgorithm.SHA256,
                CipherType           = CipherType.Block
            };

            AllowedCipherSuites = new[]
            {
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA
            };

#warning This method is not available in .NETStandard 1.6 - planned for 2.0; using X509Chain for now as it has the same functionality in NetFx, where X509Certificate2.Verify() calls the same internal method as X509Chain().Build(c)
            VerifyCertificate = c => new X509Chain().Build(c); //c.Verify();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Create a new HandshakeLayer object given a SecureChannel and which end of the connection it is to be.
        /// </summary>
        /// <param name="secureChannel">the SecureChannel that comprises the secure functionality of this layer</param>
        /// <param name="connectionEnd">this specifies which end of the connection - Server or Client</param>
        public HandshakeLayer(SecureChannel secureChannel, ConnectionEnd connectionEnd)
        {
            // SHA256 is a class that computes the SHA-256 (SHA stands for Standard Hashing Algorithm) of it's input.
            m_localHash  = SHA256.Create();
            m_remoteHash = SHA256.Create();

            m_secureChannel    = secureChannel;
            SecurityParameters = new SecurityParameters
            {
                Entity = connectionEnd,
                CompressionAlgorithm = CompressionMethod.Null,
                PRFAlgorithm         = PRFAlgorithm.SHA256,
                CipherType           = CipherType.Block
            };

            AllowedCipherSuites = new[]
            {
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA
            };

            VerifyCertificate = c => c.Verify();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Http2OwinMessageHandler"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="end"></param>
 /// <param name="isSecure"></param>
 /// <param name="next">The next layer delegate.</param>
 /// <param name="cancel">The cancellation token.</param>
 public Http2OwinMessageHandler(Stream stream, ConnectionEnd end, bool isSecure,
                         AppFunc next, CancellationToken cancel)
     : base(stream, end, isSecure, cancel)
 {
     _next = next;
     _session.OnSessionDisposed += delegate { Dispose(); };
 }
Ejemplo n.º 12
0
        public UpgradeHandshaker(IDictionary<string, object> handshakeEnvironment)
        {
            InternalSocket = (SecureSocket)handshakeEnvironment["secureSocket"];
            _end = (ConnectionEnd)handshakeEnvironment["end"];
            _responseReceivedRaised = new ManualResetEvent(false);
            _handshakeResult = new Dictionary<string, object>();

            if (_end == ConnectionEnd.Client)
            {
                if (handshakeEnvironment.ContainsKey(":host") || (handshakeEnvironment[":host"] is string)
                    || handshakeEnvironment.ContainsKey(":version") || (handshakeEnvironment[":version"] is string))
                {
                    _headers = new Dictionary<string, object>
                        {
                            {":path",  handshakeEnvironment[":path"]},
                            {":host",  handshakeEnvironment[":host"]},
                            {":version",  handshakeEnvironment[":version"]},
                            {":max_concurrent_streams", 100},
                            {":initial_window_size", 2000000},
                        };
                }
                else
                {
                    throw new InvalidConstraintException("Incorrect header for upgrade handshake");
                }
            }
        }
Ejemplo n.º 13
0
        public SecureChannel(ConnectionEnd connectionEnd)
        {
            m_handshakeLayer = new HandshakeLayer(this, connectionEnd);
            m_handshakeLayer.CipherSuiteChange += OnCipherSuiteChangeFromHandshakeLayer;

            m_recordLayer = new RecordLayer(m_protocolVersion);

            m_outgoingMessageBag = new OutgoingMessageBag(this);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Create a new SecureChannel with the given <see cref="ConnectionEnd"/>.
        /// </summary>
        /// <param name="connectionEnd">the ConnectionEnd that this channel is to talk to</param>
        public SecureChannel(ConnectionEnd connectionEnd)
        {
            m_handshakeLayer = new HandshakeLayer(this, connectionEnd);
            m_handshakeLayer.CipherSuiteChange += OnCipherSuiteChangeFromHandshakeLayer;

            m_recordLayer = new RecordLayer(m_protocolVersion);

            m_outgoingMessageBag = new OutgoingMessageBag(this);
        }
Ejemplo n.º 15
0
 public static CipherSuite InitializeCipherSuite(byte[] master, byte[] clientrnd, byte[] serverrnd, CipherDefinition definition, ConnectionEnd entity)
 {
     CipherSuite ret = new CipherSuite();
     SymmetricAlgorithm bulk = (SymmetricAlgorithm)Activator.CreateInstance(definition.BulkCipherAlgorithm);
     if (definition.BulkIVSize > 0)
         bulk.Mode = CipherMode.CBC;
     bulk.Padding = PaddingMode.None;
     bulk.BlockSize = definition.BulkIVSize * 8;
     // get the keys and IVs
     byte[] client_mac, server_mac, client_key, server_key, client_iv, server_iv;
     byte[] random = new byte[64];
     Array.Copy(serverrnd, 0, random, 0, 32);
     Array.Copy(clientrnd, 0, random, 32, 32);
     PseudoRandomDeriveBytes prf = new PseudoRandomDeriveBytes(master, "key expansion", random);
     client_mac = prf.GetBytes(definition.HashSize);
     server_mac = prf.GetBytes(definition.HashSize);
     client_key = prf.GetBytes(definition.BulkKeySize);
     server_key = prf.GetBytes(definition.BulkKeySize);
     client_iv = prf.GetBytes(definition.BulkIVSize);
     server_iv = prf.GetBytes(definition.BulkIVSize);
     prf.Dispose();
     if (definition.Exportable) { // make some extra modifications if the keys are exportable
         Array.Copy(clientrnd, 0, random, 0, 32);
         Array.Copy(serverrnd, 0, random, 32, 32);
         prf = new PseudoRandomDeriveBytes(client_key, "client write key", random);
         client_key = prf.GetBytes(definition.BulkExpandedSize);
         prf.Dispose();
         prf = new PseudoRandomDeriveBytes(server_key, "server write key", random);
         server_key = prf.GetBytes(definition.BulkExpandedSize);
         prf.Dispose();
         prf = new PseudoRandomDeriveBytes(new byte[0], "IV block", random);
         client_iv = prf.GetBytes(definition.BulkIVSize);
         server_iv = prf.GetBytes(definition.BulkIVSize);
         prf.Dispose();
     }
     // generate the cipher objects
     if (entity == ConnectionEnd.Client) {
         ret.Encryptor = bulk.CreateEncryptor(client_key, client_iv);
         ret.Decryptor = bulk.CreateDecryptor(server_key, server_iv);
         ret.LocalHasher = new HMAC((HashAlgorithm)Activator.CreateInstance(definition.HashAlgorithm), client_mac);
         ret.RemoteHasher = new HMAC((HashAlgorithm)Activator.CreateInstance(definition.HashAlgorithm), server_mac);
     } else {
         ret.Encryptor = bulk.CreateEncryptor(server_key, server_iv);
         ret.Decryptor = bulk.CreateDecryptor(client_key, client_iv);
         ret.LocalHasher = new HMAC((HashAlgorithm)Activator.CreateInstance(definition.HashAlgorithm), server_mac);
         ret.RemoteHasher = new HMAC((HashAlgorithm)Activator.CreateInstance(definition.HashAlgorithm), client_mac);
     }
     // clear sensitive data
     Array.Clear(client_mac, 0, client_mac.Length);
     Array.Clear(server_mac, 0, server_mac.Length);
     Array.Clear(client_key, 0, client_key.Length);
     Array.Clear(server_key, 0, server_key.Length);
     Array.Clear(client_iv, 0, client_iv.Length);
     Array.Clear(server_iv, 0, server_iv.Length);
     Array.Clear(random, 0, random.Length);
     return ret;
 }
Ejemplo n.º 16
0
        public ICipherParameters Create(ConnectionEnd end, ConnectionDirection direction)
        {
            var key = GetKey(end, direction);

            SecurityAssert.NotNull(key);
            SecurityAssert.Assert(key.Length > 0);

            return(new AESKeyParameter(key));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Http2MessageHandler"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="end">TODO</param>
 /// <param name="isSecure"></param>
 /// <param name="transportInfo">The transport information.</param>
 /// <param name="cancel">The cancel.</param>
 protected Http2MessageHandler(Stream stream, ConnectionEnd end, bool isSecure, 
                                 TransportInformation transportInfo, CancellationToken cancel)
 {
     _isSecure = isSecure;
     _transportInfo = transportInfo;
     _isDisposed = false;
     _cancToken = cancel;
     _stream = stream;
     _end = end;
     _wereFirstSettingsSent = false;
 }
Ejemplo n.º 18
0
		/// <summary>
		/// Initializes a new instance of the SecurityOptions class.
		/// </summary>
		/// <param name="protocol">One of the <see cref="SecureProtocol"/> values.</param>
		/// <param name="cert">A <see cref="Certificate"/> instance.</param>
		/// <param name="entity">One of the <see cref="ConnectionEnd"/> values.</param>
		/// <param name="verifyType">One of the <see cref="CredentialVerification"/> values.</param>
		/// <param name="verifier">The <see cref="CertVerifyEventHandler"/> delegate.</param>
		/// <param name="commonName">The common name of the remote computer. This is usually a domain name.</param>
		/// <param name="flags">A bitwise combination of the <see cref="SecurityFlags"/> values.</param>
		/// <param name="allowed">A bitwise combination of the <see cref="SslAlgorithms"/> values.</param>
		/// <param name="requestHandler">The <see cref="CertRequestEventHandler"/> delegate.</param>
		public SecurityOptions(SecureProtocol protocol, Certificate cert, ConnectionEnd entity, CredentialVerification verifyType, CertVerifyEventHandler verifier, string commonName, SecurityFlags flags, SslAlgorithms allowed, CertRequestEventHandler requestHandler) {
			this.Protocol = protocol;
			this.Certificate = cert;
			this.Entity = entity;
			this.VerificationType = verifyType;
			this.Verifier = verifier;
			this.CommonName = commonName;
			this.Flags = flags;
			this.AllowedAlgorithms = allowed;
			this.RequestHandler = requestHandler;
		}
Ejemplo n.º 19
0
        /// <summary>
        /// Gets the streams opened by the specified endpoint.
        /// </summary>
        /// <param name="end">The endpoint.</param>
        /// <returns></returns>
        public int GetOpenedStreamsBy(ConnectionEnd end)
        {
            if (end == ConnectionEnd.Client)
            {
                return(FlowControlledStreams.Count(element => element.Key % 2 != 0) +
                       NonFlowControlledStreams.Count(element => element.Key % 2 != 0));
            }

            return(FlowControlledStreams.Count(element => element.Key % 2 == 0) +
                   NonFlowControlledStreams.Count(element => element.Key % 2 == 0));
        }
Ejemplo n.º 20
0
        public Http2Session(SecureSocket sessionSocket, ConnectionEnd end, 
                            bool usePriorities, bool useFlowControl,
                            IDictionary<string, object> handshakeResult = null)
        {
            _ourEnd = end;
            _usePriorities = usePriorities;
            _useFlowControl = useFlowControl;
            _handshakeHeaders = new Dictionary<string, string>(16);
            ApplyHandshakeResults(handshakeResult);

            if (_ourEnd == ConnectionEnd.Client)
            {
                _remoteEnd = ConnectionEnd.Server;
                _lastId = -1; // Streams opened by client are odd
            }
            else
            {
                _remoteEnd = ConnectionEnd.Client;
                _lastId = 0; // Streams opened by server are even
            }

            _goAwayReceived = false;
            _settingsManager = new SettingsManager();
            _comprProc = new CompressionProcessor(_ourEnd);
            _sessionSocket = sessionSocket;

            _frameReader = new FrameReader(_sessionSocket);

            ActiveStreams = new ActiveStreams();

            _writeQueue = new WriteQueue(_sessionSocket, ActiveStreams, _usePriorities);

            if (_sessionSocket != null && sessionSocket.SecureProtocol == SecureProtocol.None)
            {
                OurMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
                RemoteMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
                InitialWindowSize = int.Parse(_handshakeHeaders[":initial_window_size"]);
            }
            else
            {
                OurMaxConcurrentStreams = 100; //Spec recommends value 100 by default
                RemoteMaxConcurrentStreams = 100;
                InitialWindowSize = 2000000;
            }
            _flowControlManager = new FlowControlManager(this);

            if (!_useFlowControl)
            {
                _flowControlManager.Options = (byte) FlowControlOptions.DontUseFlowControl;
            }

            SessionWindowSize = 0;
            _toBeContinuedHeaders = new HeadersList();
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Initializes a new instance of the SecurityOptions class.
 /// </summary>
 /// <param name="protocol">One of the <see cref="SecureProtocol"/> values.</param>
 /// <param name="cert">A <see cref="Certificate"/> instance.</param>
 /// <param name="entity">One of the <see cref="ConnectionEnd"/> values.</param>
 /// <param name="verifyType">One of the <see cref="CredentialVerification"/> values.</param>
 /// <param name="verifier">The <see cref="CertVerifyEventHandler"/> delegate.</param>
 /// <param name="commonName">The common name of the remote computer. This is usually a domain name.</param>
 /// <param name="flags">A bitwise combination of the <see cref="SecurityFlags"/> values.</param>
 /// <param name="allowed">A bitwise combination of the <see cref="SslAlgorithms"/> values.</param>
 /// <param name="requestHandler">The <see cref="CertRequestEventHandler"/> delegate.</param>
 public SecurityOptions(SecureProtocol protocol, Certificate cert, ConnectionEnd entity, CredentialVerification verifyType, CertVerifyEventHandler verifier, string commonName, SecurityFlags flags, SslAlgorithms allowed, CertRequestEventHandler requestHandler)
 {
     this.Protocol          = protocol;
     this.Certificate       = cert;
     this.Entity            = entity;
     this.VerificationType  = verifyType;
     this.Verifier          = verifier;
     this.CommonName        = commonName;
     this.Flags             = flags;
     this.AllowedAlgorithms = allowed;
     this.RequestHandler    = requestHandler;
 }
Ejemplo n.º 22
0
        public void WriteExtensions(Stream stream, ConnectionEnd end)
        {
            if (this.Count != 0)
            {
                byte[] allExtensionsLength = BinaryHelper.Int16ToBytes(this.ExtensionsByteLength);
                stream.Write(allExtensionsLength, 0, allExtensionsLength.Length);

                foreach (var extension in this)
                {
                    extension.Write(stream, end);
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Deserialization constructor
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        protected BinaryAmbiance(SerializationInfo info, StreamingContext context)
        {
            #region Incremental serialization fix; delete try-catch when properly saved with all members
            try
            {
                mLocked = info.GetBoolean("mLocked");
            }
            catch
            {
                this.mLocked = false;
            }

            try
            {
                mEnableTooltip = info.GetBoolean("mEnableTooltip");
            }
            catch
            {
                mEnableTooltip = true;
            }

            try
            {
                mShowAutomataController = info.GetBoolean("mShowAutomataController");
            }
            catch
            {
                mShowAutomataController = false;
            }
            #endregion
            mShowGrid              = info.GetBoolean("mShowGrid");
            mGradientBottom        = (Color)info.GetValue("mGradientBottom", typeof(Color));
            mGradientTop           = (Color)info.GetValue("mGradientTop", typeof(Color));
            mAllowAddConnection    = info.GetBoolean("mAllowAddConnection");
            mAllowAddShape         = info.GetBoolean("mAllowAddShape");
            mAllowDeleteShape      = info.GetBoolean("mAllowDeleteShape");
            mAllowMoveShape        = info.GetBoolean("mAllowMoveShape");
            mAutomataPulse         = info.GetInt32("mAutomataPulse");
            mBackgroundColor       = (Color)info.GetValue("mBackgroundColor", typeof(Color));
            mBackgroundImagePath   = info.GetString("mBackgroundImagePath");
            mBackgroundType        = (CanvasBackgroundType)info.GetValue("mBackgroundType", typeof(CanvasBackgroundType));
            mDefaultConnectionPath = info.GetString("mDefaultConnectionPath");
            mGradientMode          = (LinearGradientMode)info.GetValue("mGradientMode", typeof(LinearGradientMode));
            mEnableContextMenu     = info.GetBoolean("mEnableContextMenu");
            mGridSize              = info.GetInt32("mGridSize");
            mRestrictToCanvas      = info.GetBoolean("mRestrictToCanvas");
            mSnap = info.GetBoolean("mSnap");
            mDefaultConnectionEnd = (ConnectionEnd)info.GetValue("mDefaultConnectionEnd", typeof(ConnectionEnd));
            mEnableLayout         = info.GetBoolean("mEnableLayout");
            mGraphLayoutAlgorithm = (GraphLayoutAlgorithms)info.GetValue("mGraphLayoutAlgorithm", typeof(GraphLayoutAlgorithms));
        }
Ejemplo n.º 24
0
        private static bool AddExtensionToResult(byte[] buffer, ref int currentLen, Int16 extLen, ConnectionEnd end, 
                                                    ExtensionList knownExtensions, ExtensionType type, ref ExtensionList result)
        {
            foreach (var extension in knownExtensions)
            {
                if (extension.Type == type)
                {
                    result.Add(extension.Parse(buffer, ref currentLen, extLen, end));
                    return true;
                }
            }

            return false;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Attaches the extension to ClientHello message.
        /// </summary>
        /// <param name="clientHello">The clientHello message.</param>
        /// <param name="currentLen">The current index in clientHello array.
        /// This index divides handled and unhandled bytes in client Hello</param>
        /// <returns>
        /// Byte array that contains clientHello with attached extension
        /// </returns>
        public override void Write(Stream stream, ConnectionEnd end)
        {
            int curPosition = (int)stream.Position;

            byte[] renegotiationType = BinaryHelper.Int16ToBytes((short)this.Type);
            stream.Write(renegotiationType, 0, renegotiationType.Length);

            byte[] extDataSize = BinaryHelper.Int16ToBytes(this.ExtensionDataSize);
            stream.Write(extDataSize, 0, extDataSize.Length);

            stream.WriteByte(this.renegotiatedConnection);

            /*if (this.OnAddedToClientHello != null)
             *  this.OnAddedToClientHello(this, new AddedToClientHelloArgs(curPosition));*/
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Attaches the extension to ClientHello message.
        /// </summary>
        /// <param name="clientHello">The clientHello message.</param>
        /// <param name="currentLen">The current index in clientHello array.
        /// This index divides handled and unhandled bytes in client Hello</param>
        /// <returns>
        /// Byte array that contains clientHello with attached extension
        /// </returns>
        public override void Write(Stream stream, ConnectionEnd end)
        {
            int curPosition = (int)stream.Position;

            byte[] renegotiationType = BinaryHelper.Int16ToBytes((short)this.Type);
            stream.Write(renegotiationType, 0, renegotiationType.Length);

            byte[] extDataSize = BinaryHelper.Int16ToBytes(this.ExtensionDataSize);
            stream.Write(extDataSize, 0, extDataSize.Length);

            stream.WriteByte(this.renegotiatedConnection);

            /*if (this.OnAddedToClientHello != null)
                this.OnAddedToClientHello(this, new AddedToClientHelloArgs(curPosition));*/
        }
Ejemplo n.º 27
0
 public async Task Process()
 {
     try {
         realOutputWriter         = new StreamWriter(realOutputStream, NaiveUtils.UTF8Encoding);
         realOutputWriter.NewLine = "\r\n";
         ConnectionBegin?.Invoke(this);
         await _requestingLoop().CAF();
     } catch (DisconnectedException) {
     } finally {
         try {
             baseStream.Close();
         } catch (Exception) { }
         ConnectionEnd?.Invoke(this);
     }
 }
Ejemplo n.º 28
0
        public override void Write(Stream stream, ConnectionEnd end)
        {
            int curPosition = (int)stream.Position;

            byte[] alpnType = BinaryHelper.Int16ToBytes((short)this.Type);
            stream.Write(alpnType, 0, alpnType.Length);

            byte[] extDataSize = BinaryHelper.Int16ToBytes(this.ExtensionDataSize);
            stream.Write(extDataSize, 0, extDataSize.Length);

            if (end == ConnectionEnd.Client)
            {
                Int16 serializedProtocolListSize = 0;

                this.ClientKnownProtocolList.Count(protocol =>
                {
                    serializedProtocolListSize += (Int16)(protocol.Length + 1);
                    return(true);
                });
                byte[] serializedProtocolListSizeBytes = BinaryHelper.Int16ToBytes(serializedProtocolListSize);
                stream.Write(serializedProtocolListSizeBytes, 0, serializedProtocolListSizeBytes.Length);

                foreach (var protocol in this.ClientKnownProtocolList)
                {
                    byte protoLen = (byte)(protocol.Length);
                    stream.WriteByte(protoLen);

                    byte[] protocolData = Encoding.UTF8.GetBytes(protocol);
                    stream.Write(protocolData, 0, protocolData.Length);
                }

                if (this.OnAddedToClientHello != null)
                {
                    this.OnAddedToClientHello(this, new ALPNAddedToClientHelloArgs(curPosition));
                }
            }
            else
            {
                byte   selectedProtoLen    = (byte)(Encoding.UTF8.GetByteCount(this.SelectedProtocol));
                Int16  protocolVectorLen   = (Int16)(selectedProtoLen + 1);
                byte[] protocolVectorBytes = BinaryHelper.Int16ToBytes(protocolVectorLen);
                byte[] selectedProtoBytes  = Encoding.UTF8.GetBytes(this.SelectedProtocol);

                stream.Write(protocolVectorBytes, 0, protocolVectorBytes.Length);
                stream.WriteByte(selectedProtoLen);
                stream.Write(selectedProtoBytes, 0, selectedProtoBytes.Length);
            }
        }
Ejemplo n.º 29
0
        public BlockSum(Point leftTopPoint)
        {
            ShapePoints[0] = leftTopPoint;

            BlockSize   = BlockSumMinSize;
            InPortSigns = new List <FormattedText>();

            PortPoints.RemoveAt(1);
            ConnectionObj.RemoveAt(1);
            ConnectionEnd.RemoveAt(1);

            PortDeltaMax = BlockSumMinSize.Height / 3;
            PortDelta    = FontSize;  //отступ знаков от верхнего края

            SetInPortSigns("++");
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Create a new SecureChannel with the given <see cref="ConnectionEnd"/>.
        /// </summary>
        /// <param name="connectionEnd">the ConnectionEnd that this channel is to talk to</param>
        private SecureChannel(ConnectionEnd connectionEnd, Configuration configuration = null)
        {
            Configuration   = configuration ?? new Configuration();
            n_ConnectionEnd = connectionEnd;

            m_handshakeLayer = new HandshakeLayer(this, connectionEnd);
            m_handshakeLayer.CipherSuiteChange += OnCipherSuiteChangeFromHandshakeLayer;
            RecordLayer = new RecordLayer();

            m_outgoingMessageBag = new OutgoingMessageBag(this);
            if (!Configuration.VerifyCertificate)
            {
                //若不验证证书,则直接返回true
                SetVerifyCertificate(c => true);
            }
        }
Ejemplo n.º 31
0
        public static ExtensionList Parse(byte[] buffer, ref int currentLen, ExtensionList knownExtensions, ConnectionEnd end)
        {
            var extsList = new ExtensionList();
            int extsLen = BinaryHelper.Int16FromBytes(buffer[currentLen++], buffer[currentLen++]);
            int extOffsetEnd = currentLen + extsLen;

            while (currentLen < extOffsetEnd)
            {
                ExtensionType type = (ExtensionType)BinaryHelper.Int16FromBytes(buffer[currentLen++], buffer[currentLen++]);
                Int16 extLen = BinaryHelper.Int16FromBytes(buffer[currentLen++], buffer[currentLen++]);

                if (AddExtensionToResult(buffer, ref currentLen, extLen, end, knownExtensions, type, ref extsList) == false)
                    currentLen += extLen;
            }

            return extsList;
        }
Ejemplo n.º 32
0
        public ALPNExtension(ConnectionEnd end, IEnumerable <string> knownProtocols)
        {
            this.Type = ExtensionType.ALPN;

            this.SelectedProtocol = String.Empty;
            if (end == ConnectionEnd.Client)
            {
                this.ClientKnownProtocolList = new List <string>(knownProtocols);
                this.ExtensionDataSize       = CalcExtensionDataSize(this.ClientKnownProtocolList);
            }
            else
            {
                this.ServerKnownProtocolList = new List <string>(knownProtocols);
            }

            this.ExtensionSize = (Int16)(sizeof(Int16) * 2 + this.ExtensionDataSize); //type + length + data length
        }
Ejemplo n.º 33
0
        /// <summary>
        ///     Calls SSL_CTX_new()
        /// </summary>
        /// <param name="sslMethod"></param>
        /// <param name="end"></param>
        /// <param name="protoList"></param>
        public SslContext(
            SslMethod sslMethod,
            ConnectionEnd end,
            IEnumerable <string> protoList) :
            base(Native.ExpectNonNull(Native.SSL_CTX_new(sslMethod.Handle)), true)
        {
            alpnExt = new AlpnExtension(Handle, protoList);

            _ptrOnClientCertThunk = OnClientCertThunk;
            _ptrOnVerifyCertThunk = OnVerifyCertThunk;
            _ptrOnAlpn            = alpnExt.AlpnCb;

            if (end == ConnectionEnd.Server)
            {
                Native.SSL_CTX_set_alpn_select_cb(Handle, _ptrOnAlpn, IntPtr.Zero);
            }
        }
Ejemplo n.º 34
0
		/// <summary>
		///     Calls SSL_CTX_new()
		/// </summary>
		/// <param name="sslMethod"></param>
		/// <param name="end"></param>
		/// <param name="protoList"></param>
		public SslContext(
			SslMethod sslMethod,
			ConnectionEnd end,
			IEnumerable<string> protoList) :
			base(Native.ExpectNonNull(Native.SSL_CTX_new(sslMethod.Handle)), true)
		{
			alpnExt = new AlpnExtension(Handle, protoList);

			_ptrOnClientCertThunk = OnClientCertThunk;
			_ptrOnVerifyCertThunk = OnVerifyCertThunk;
			_ptrOnAlpn = alpnExt.AlpnCb;

			if (end == ConnectionEnd.Server)
			{
				Native.SSL_CTX_set_alpn_select_cb(Handle, _ptrOnAlpn, IntPtr.Zero);
			}
		}
Ejemplo n.º 35
0
        public ALPNExtension(ConnectionEnd end, IEnumerable<string> knownProtocols)
        {
            this.Type = ExtensionType.ALPN;

            this.SelectedProtocol = String.Empty;
            if (end == ConnectionEnd.Client)
            {
                this.ClientKnownProtocolList = new List<string>(knownProtocols);
                this.ExtensionDataSize = CalcExtensionDataSize(this.ClientKnownProtocolList);
            }
            else
            {
                this.ServerKnownProtocolList = new List<string>(knownProtocols);
            }

            this.ExtensionSize = (Int16)(sizeof(Int16) * 2 + this.ExtensionDataSize); //type + length + data length
        }
Ejemplo n.º 36
0
        public CompressionProcessor(ConnectionEnd end)
        {
            if (end == ConnectionEnd.Client)
            {
                _localHeaderTable  = CompressionInitialHeaders.ResponseInitialHeaders;
                _remoteHeaderTable = CompressionInitialHeaders.RequestInitialHeaders;
            }
            else
            {
                _localHeaderTable  = CompressionInitialHeaders.RequestInitialHeaders;
                _remoteHeaderTable = CompressionInitialHeaders.ResponseInitialHeaders;
            }
            _localRefSet  = new SizedHeadersList();
            _remoteRefSet = new SizedHeadersList();

            InitCompressor();
            InitDecompressor();
        }
Ejemplo n.º 37
0
        public CompressionProcessor(ConnectionEnd end)
        {
            if (end == ConnectionEnd.Client)
            {
                _localHeaderTable = CompressionInitialHeaders.ResponseInitialHeaders;
                _remoteHeaderTable = CompressionInitialHeaders.RequestInitialHeaders;
            }
            else
            {
                _localHeaderTable = CompressionInitialHeaders.RequestInitialHeaders;
                _remoteHeaderTable = CompressionInitialHeaders.ResponseInitialHeaders;
            }
            _localRefSet = new SizedHeadersList();
            _remoteRefSet = new SizedHeadersList();

            InitCompressor();
            InitDecompressor();
        }
Ejemplo n.º 38
0
        public Http2Session(SecureSocket sessionSocket, ConnectionEnd end,
                            bool usePriorities, bool useFlowControl,
                            IDictionary <string, object> handshakeResult = null)
        {
            _ourEnd           = end;
            _usePriorities    = usePriorities;
            _useFlowControl   = useFlowControl;
            _handshakeHeaders = new Dictionary <string, string>(16);
            ApplyHandshakeResults(handshakeResult);

            if (_ourEnd == ConnectionEnd.Client)
            {
                _remoteEnd = ConnectionEnd.Server;
                _lastId    = -1; // Streams opened by client are odd
            }
            else
            {
                _remoteEnd = ConnectionEnd.Client;
                _lastId    = 0; // Streams opened by server are even
            }

            _goAwayReceived  = false;
            _settingsManager = new SettingsManager();
            _comprProc       = new CompressionProcessor(_ourEnd);
            _sessionSocket   = sessionSocket;

            _frameReader = new FrameReader(_sessionSocket);

            ActiveStreams = new ActiveStreams();

            _writeQueue = new WriteQueue(_sessionSocket, ActiveStreams, _usePriorities);

            OurMaxConcurrentStreams    = 100; //Spec recommends value 100 by default
            RemoteMaxConcurrentStreams = 100;

            _flowControlManager = new FlowControlManager(this);

            if (!_useFlowControl)
            {
                _flowControlManager.Options = (byte)FlowControlOptions.DontUseFlowControl;
            }

            SessionWindowSize = 0;
        }
Ejemplo n.º 39
0
        public HandshakeLayer(SecureChannel secureChannel, ConnectionEnd connectionEnd)
        {
            m_secureChannel = secureChannel;
            SecurityParameters = new SecurityParameters();
              SecurityParameters.Entity = connectionEnd;
              SecurityParameters.CompressionAlgorithm = CompressionMethod.Null;
              SecurityParameters.PRFAlgorithm = PRFAlgorithm.SHA256;
              SecurityParameters.CipherType = CipherType.Block;

              AllowedCipherSuites = new CipherSuite[]
            {
              CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
              CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,
              CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
              CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA,
            };

              VerifyCertificate = c => c.Verify();
        }
Ejemplo n.º 40
0
        /// <summary>
        ///     Calls SSL_CTX_new()
        /// </summary>
        /// <param name="sslMethod"></param>
        /// <param name="end"></param>
        /// <param name="includeAlpn"></param>
        /// <param name="protoList"></param>
        public SslContext(SslMethod sslMethod, ConnectionEnd end, bool includeAlpn, IEnumerable <string> protoList = null)
            :
            base(Native.ExpectNonNull(Native.SSL_CTX_new(sslMethod.Handle)), true)
        {
            if (!includeAlpn)
            {
                return;
            }

            alpnExt = new AlpnExtension(Handle, protoList);

            if (end == ConnectionEnd.Server)
            {
                alpnCb = alpnExt.AlpnCb;
                var alpnCbPtr = Marshal.GetFunctionPointerForDelegate(alpnCb);
                var arg       = new IntPtr();
                Native.SSL_CTX_set_alpn_select_cb(Handle, alpnCbPtr, arg);
            }
        }
Ejemplo n.º 41
0
 public SecurityOptions(SecureProtocol protocol, ExtensionType[] extensions, Certificate cert,
                        ConnectionEnd entity, IEnumerable <string> knownProtocols,
                        CredentialVerification verifyType, CertVerifyEventHandler verifier,
                        string commonName, SecurityFlags flags, SslAlgorithms allowed,
                        CertRequestEventHandler requestHandler)
 {
     this.Protocol          = protocol;
     this.Certificate       = cert;
     this.Entity            = entity;
     this.VerificationType  = verifyType;
     this.Verifier          = verifier;
     this.CommonName        = commonName;
     this.Flags             = flags;
     this.AllowedAlgorithms = allowed;
     this.RequestHandler    = requestHandler;
     this.KnownProtocols    = knownProtocols;
     this.Extensions        = extensions;
     this.ExtensionList     = FormExtsList(extensions);
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Http2MessageHandler"/> class.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="end">TODO</param>
        /// <param name="isSecure"></param>
        /// <param name="cancel">The cancel.</param>
        protected Http2MessageHandler(Stream stream, ConnectionEnd end, bool isSecure, CancellationToken cancel)
        {
            _isSecure = isSecure;

            //09 spec:
            //SETTINGS_ENABLE_PUSH (2):  This setting can be use to disable server
            //push (Section 8.2).  An endpoint MUST NOT send a PUSH_PROMISE
            //frame if it receives this setting set to a value of 0.  The
            //initial value is 1, which indicates that push is permitted.

            _isPushEnabled         = true;
            _isDisposed            = false;
            _cancToken             = cancel;
            _stream                = stream;
            _end                   = end;
            _wereFirstSettingsSent = false;

            _session = new Http2Session(_stream, _end, true, true, _isSecure, _cancToken);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Http2MessageHandler"/> class.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="end">TODO</param>
        /// <param name="isSecure"></param>
        /// <param name="cancel">The cancel.</param>
        protected Http2MessageHandler(Stream stream, ConnectionEnd end, bool isSecure, CancellationToken cancel)
        {
            _isSecure = isSecure;

            //09 spec:
            //SETTINGS_ENABLE_PUSH (2):  This setting can be use to disable server
            //push (Section 8.2).  An endpoint MUST NOT send a PUSH_PROMISE
            //frame if it receives this setting set to a value of 0.  The
            //initial value is 1, which indicates that push is permitted.

            _isPushEnabled = true;
            _isDisposed = false;
            _cancToken = cancel;
            _stream = stream;
            _end = end;
            _wereFirstSettingsSent = false;

            _session = new Http2Session(_stream, _end, true, true, _isSecure, _cancToken);
        }
Ejemplo n.º 44
0
 public override void Process(ConnectionEnd end)
 {
     if (end == ConnectionEnd.Server)
     {
         foreach (var protocol in this.ServerKnownProtocolList)
         {
             if (this.ClientKnownProtocolList.Contains(protocol))
             {
                 this.SelectedProtocol  = protocol;
                 this.ExtensionDataSize = (short)(Encoding.UTF8.GetByteCount(this.SelectedProtocol) + sizeof(byte) + sizeof(Int16));
                 this.ExtensionSize     = (Int16)(sizeof(Int16) * 2 + this.ExtensionDataSize); //type + length + data length
                 break;
             }
         }
         if (this.SelectedProtocol == String.Empty)
         {
             throw new ALPNCantSelectProtocolException();
         }
     }
 }
Ejemplo n.º 45
0
        public void ProcessExtensions(byte[] buffer, ref int currentLen, ConnectionEnd end)
        {
            ExtensionList extList;

            if (end == ConnectionEnd.Client)
            {
                extList = ExtensionsParser.Parse(buffer, ref currentLen, this.clientHelloExts, ConnectionEnd.Client);
                this.serverHelloExts = extList;
            }
            else
            {
                extList = ExtensionsParser.Parse(buffer, ref currentLen, this.serverHelloExts, ConnectionEnd.Server);
                this.clientHelloExts = extList;
            }

            foreach (var extension in extList)
            {
                extension.Process(end);
            }
        }
Ejemplo n.º 46
0
        public CompressionProcessor(ConnectionEnd end)
        {
            //default max headers table size
            _maxHeaderByteSize = 4096;

            //05 The header table is initially empty.
            _remoteHeadersTable = new HeadersList();
            _localHeadersTable = new HeadersList();

            //05 The reference set is initially empty.
            _remoteRefSet = new HeadersList();
            _localRefSet = new HeadersList();

            _huffmanProc = new HuffmanCompressionProcessor();

            _localEnd = end;

            InitCompressor();
            InitDecompressor();
        }
        public ICipherParameters Create(ConnectionEnd end, ConnectionDirection direction)
        {
            if (_certificateConfig.Certificate is null)
            {
                throw new InvalidOperationException("Certificate is not initialized");
            }

            var publicKey = (RSAPublicKey)_certificateConfig.Certificate.SubjectPublicKey;

            switch (end)
            {
            case ConnectionEnd.Client:
                return(new RSAPublicKeyParameter(publicKey));

            case ConnectionEnd.Server:
                return(new RSAPrivateKeyParameter((RSAPrivateKey)_certificateManager.GetPrivateKey(publicKey)));

            default:
                throw new ArgumentOutOfRangeException(nameof(end), end, null);
            }
        }
Ejemplo n.º 48
0
        public HandshakeLayer(SecureChannel secureChannel, ConnectionEnd connectionEnd)
        {
            m_localHash  = SHA256.Create();
            m_remoteHash = SHA256.Create();

            m_secureChannel           = secureChannel;
            SecurityParameters        = new SecurityParameters();
            SecurityParameters.Entity = connectionEnd;
            SecurityParameters.CompressionAlgorithm = CompressionMethod.Null;
            SecurityParameters.PRFAlgorithm         = PRFAlgorithm.SHA256;
            SecurityParameters.CipherType           = CipherType.Block;

            AllowedCipherSuites = new CipherSuite[]
            {
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
                CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA,
            };

            VerifyCertificate = c => c.Verify();
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Deserialization constructor
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        protected Connection(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            this.InitConnection();
            //attaching the connection to shape connector occurs in the BinarySerializer class;
            //instantiate the connectors to keep the UID references until then

            this.mTo = new Connector(info.GetString("mTo.UID"));

            this.mFrom = new Connector(info.GetString("mFrom.UID"));

            this.mLineColor = (Color)info.GetValue("mLineColor", typeof(Color));

            this.mLineEnd = (ConnectionEnd)info.GetValue("mLineEnd", typeof(ConnectionEnd));

            this.mLineWidth = info.GetInt32("mLineWidth");

            mLinePath = info.GetString("mLinePath");

            if (mLinePath == "Bezier")
            {
                mPainter = info.GetValue("mPainter", typeof(BezierPainter)) as BezierPainter;
            }

            mInsertionPoints = (ArrayList)info.GetValue("mInsertionPoints", typeof(ArrayList));

            this.Tag = info.GetString("mLayer");             //layer is set in the post-deserialization

            try
            {
                this.mZOrder = info.GetInt32("mZOrder");
            }
            catch
            {
                this.mZOrder = 0;
            }
        }
Ejemplo n.º 50
0
        public void SendConnection(SwitchConnection conn)
        {
            var scr = new ConnectionEnd()
            {
                Id     = conn.Source.Address,
                Volumn = (byte)conn.Source.Volumn,
                Status = conn.Source.IsConnected ? eStatus.On : eStatus.Off
            };

            var dest = new ConnectionEnd()
            {
                Id     = conn.Dest.Address,
                Volumn = (byte)conn.Dest.Volumn,
                Status = conn.Dest.IsConnected ? eStatus.On : eStatus.Off
            };

            var msg = new ConnectionMessage()
            {
                Source = scr,
                Dest   = dest
            };

            this.Presentation.SendData(msg);
        }
Ejemplo n.º 51
0
		/// <summary>
		/// Deserialization constructor
		/// </summary>
		/// <param name="info"></param>
		/// <param name="context"></param>
		protected BinaryAmbiance(SerializationInfo info, StreamingContext context) 
		{
		
		
			#region Incremental serialization fix; delete try-catch when properly saved with all members
			try
			{				
				 mLocked = info.GetBoolean("mLocked");
			}
			catch
			{
				this.mLocked = false;
			}

			try
			{
				mEnableTooltip = info.GetBoolean("mEnableTooltip");
			}
			catch
			{
				mEnableTooltip = true;
			}

			try
			{
			mShowAutomataController = info.GetBoolean("mShowAutomataController");
			}
			catch
			{
				mShowAutomataController = false;
			}
			#endregion
				mShowGrid = info.GetBoolean("mShowGrid");
				mGradientBottom = (Color) info.GetValue("mGradientBottom", typeof(Color));
				mGradientTop = (Color) info.GetValue("mGradientTop", typeof(Color));
				mAllowAddConnection = info.GetBoolean("mAllowAddConnection");
				mAllowAddShape = info.GetBoolean("mAllowAddShape");
				mAllowDeleteShape = info.GetBoolean("mAllowDeleteShape");
				mAllowMoveShape = info.GetBoolean("mAllowMoveShape");
				mAutomataPulse = info.GetInt32("mAutomataPulse");
				mBackgroundColor = (Color) info.GetValue("mBackgroundColor", typeof(Color));
				mBackgroundImagePath = info.GetString("mBackgroundImagePath");
				mBackgroundType = (CanvasBackgroundType) info.GetValue("mBackgroundType", typeof(CanvasBackgroundType));
				mDefaultConnectionPath = info.GetString("mDefaultConnectionPath");
				mGradientMode =(LinearGradientMode)  info.GetValue("mGradientMode", typeof(LinearGradientMode));
				mEnableContextMenu = info.GetBoolean("mEnableContextMenu");
				mGridSize = info.GetInt32("mGridSize");
				mRestrictToCanvas = info.GetBoolean("mRestrictToCanvas");
				mSnap = info.GetBoolean("mSnap");
				mDefaultConnectionEnd  = (ConnectionEnd) info.GetValue("mDefaultConnectionEnd", typeof(ConnectionEnd));
				mEnableLayout = info.GetBoolean("mEnableLayout");
				mGraphLayoutAlgorithm = (GraphLayoutAlgorithms) info.GetValue("mGraphLayoutAlgorithm", typeof(GraphLayoutAlgorithms));
				
			
		}
Ejemplo n.º 52
0
 public virtual Extension Parse(byte[] serverHello, ref int currentLen, Int16 extLen, ConnectionEnd end)
 {
     return this;
 }
Ejemplo n.º 53
0
 public virtual void Process(ConnectionEnd end)
 {
 }
Ejemplo n.º 54
0
 public FileHelper(ConnectionEnd end)
 {
     _pathStreamDict = new Dictionary<string, FileStream>(5);
     _end = end;
 }
Ejemplo n.º 55
0
 public virtual void Write(Stream stream, ConnectionEnd end)
 {
 }
Ejemplo n.º 56
0
 /// <summary>
 /// Prevents a default instance of the <see cref="RenegotiationExtension"/> class from being created.
 /// </summary>
 public RenegotiationExtension(ConnectionEnd end)
 {
     this.Type = ExtensionType.Renegotiation;
     this.ExtensionDataSize = 0x01;
     this.ExtensionSize = sizeof(Int16) * 2 + sizeof(byte);
 }
Ejemplo n.º 57
0
        public Http2Session(Stream stream, ConnectionEnd end, 
                            bool usePriorities, bool useFlowControl, bool isSecure,
                            CancellationToken cancel,
                            int initialWindowSize = Constants.InitialFlowControlWindowSize,
                            int maxConcurrentStreams = Constants.DefaultMaxConcurrentStreams)
        {

            if (stream == null)
                throw new ArgumentNullException("stream is null");

            if (cancel == null)
                throw new ArgumentNullException("cancellation token is null");

            if (maxConcurrentStreams <= 0)
                throw new ArgumentOutOfRangeException("maxConcurrentStreams cant be less or equal then 0");

            if (initialWindowSize <= 0 && useFlowControl)
                throw new ArgumentOutOfRangeException("initialWindowSize cant be less or equal then 0");

            _ourEnd = end;
            _usePriorities = usePriorities;
            _useFlowControl = useFlowControl;
            _isSecure = isSecure;

            _cancelSessionToken = cancel;

            if (_ourEnd == ConnectionEnd.Client)
            {
                _remoteEnd = ConnectionEnd.Server;
                _lastId = -1; // Streams opened by client are odd

                //if we got unsecure connection then server will respond with id == 1. We cant initiate 
                //new stream with id == 1.
                if (!(stream is SslStream))
                {
                    _lastId = 3;
                }
            }
            else
            {
                _remoteEnd = ConnectionEnd.Client;
                _lastId = 0; // Streams opened by server are even
            }

            _goAwayReceived = false;
            _comprProc = new CompressionProcessor(_ourEnd);
            _ioStream = stream;

            _frameReader = new FrameReader(_ioStream);

            ActiveStreams = new ActiveStreams();

            _writeQueue = new WriteQueue(_ioStream, ActiveStreams, _comprProc, _usePriorities);
            OurMaxConcurrentStreams = maxConcurrentStreams;
            RemoteMaxConcurrentStreams = maxConcurrentStreams;
            InitialWindowSize = initialWindowSize;

            _flowControlManager = new FlowControlManager(this);

            if (!_useFlowControl)
            {
                _flowControlManager.Options = (byte) FlowControlOptions.DontUseFlowControl;
            }

            SessionWindowSize = 0;
            _headersSequences = new HeadersSequenceList();
            _promisedResources = new Dictionary<int, string>();
        }
Ejemplo n.º 58
0
 public static CipherSuite InitializeCipherSuite(byte[] master, byte[] clientrnd, byte[] serverrnd, CipherDefinition definition, ConnectionEnd entity)
 {
     CipherSuite ret = new CipherSuite();
     SymmetricAlgorithm bulk = (SymmetricAlgorithm)Activator.CreateInstance(definition.BulkCipherAlgorithm);
     if (definition.BulkIVSize > 0)
         bulk.Mode = CipherMode.CBC;
     bulk.Padding = PaddingMode.None;
     bulk.BlockSize = definition.BulkIVSize * 8;
     // get the keys and IVs
     byte[] client_mac, server_mac, client_key, server_key, client_iv, server_iv;
     Ssl3DeriveBytes prf = new Ssl3DeriveBytes(master, clientrnd, serverrnd, false);
     client_mac = prf.GetBytes(definition.HashSize);
     server_mac = prf.GetBytes(definition.HashSize);
     client_key = prf.GetBytes(definition.BulkKeySize);
     server_key = prf.GetBytes(definition.BulkKeySize);
     client_iv = prf.GetBytes(definition.BulkIVSize);
     server_iv = prf.GetBytes(definition.BulkIVSize);
     prf.Dispose();
     if (definition.Exportable) { // make some extra modifications if the keys are exportable
         MD5 md5 = new MD5CryptoServiceProvider();
         md5.TransformBlock(client_key, 0, client_key.Length, client_key, 0);
         md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0);
         md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length);
         client_key = new byte[definition.BulkExpandedSize];
         Buffer.BlockCopy(md5.Hash, 0, client_key, 0, client_key.Length);
         md5.Initialize();
         md5.TransformBlock(server_key, 0, server_key.Length, server_key, 0);
         md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0);
         md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length);
         server_key = new byte[definition.BulkExpandedSize];
         Buffer.BlockCopy(md5.Hash, 0, server_key, 0, server_key.Length);
         md5.Initialize();
         md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0);
         md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length);
         client_iv = new byte[definition.BulkIVSize];
         Buffer.BlockCopy(md5.Hash, 0, client_iv, 0, client_iv.Length);
         md5.Initialize();
         md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0);
         md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length);
         server_iv = new byte[definition.BulkIVSize];
         Buffer.BlockCopy(md5.Hash, 0, server_iv, 0, server_iv.Length);
         md5.Clear();
     }
     // generate the cipher objects
     if (entity == ConnectionEnd.Client) {
         ret.Encryptor = bulk.CreateEncryptor(client_key, client_iv);
         ret.Decryptor = bulk.CreateDecryptor(server_key, server_iv);
         ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac);
         ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac);
     } else {
         ret.Encryptor = bulk.CreateEncryptor(server_key, server_iv);
         ret.Decryptor = bulk.CreateDecryptor(client_key, client_iv);
         ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac);
         ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac);
     }
     // clear sensitive data
     Array.Clear(client_mac, 0, client_mac.Length);
     Array.Clear(server_mac, 0, server_mac.Length);
     Array.Clear(client_key, 0, client_key.Length);
     Array.Clear(server_key, 0, server_key.Length);
     Array.Clear(client_iv, 0, client_iv.Length);
     Array.Clear(server_iv, 0, server_iv.Length);
     return ret;
 }
 public Http2ClientMessageHandler(DuplexStream stream, ConnectionEnd end, TransportInformation transportInfo, CancellationToken cancel)
     : base(stream, end, stream.IsSecure, transportInfo, cancel)
 {
     _fileHelper = new FileHelper(ConnectionEnd.Client);
     stream.OnClose += delegate { Dispose(); };
 }
Ejemplo n.º 60
0
        public override Extension Parse(byte[] buffer, ref int currentLen, Int16 extLen, ConnectionEnd end)
        {
            this.HandleRenegotiationExt(buffer, ref currentLen, extLen);

            return this;
        }