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"); } } }
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(); }; }
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); } }
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"); } } }
/// <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(); }; }
/// <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(); }
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"); } } }
/// <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(); }
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"); } } }
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); }
/// <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); }
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; }
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; }
/// <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; }
/// <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)); }
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(); }
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); } } }
/// <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)); }
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; }
/// <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));*/ }
/// <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));*/ }
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); } }
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); } }
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("++"); }
/// <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); } }
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; }
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 }
/// <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); } }
/// <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); } }
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 }
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(); }
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; }
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(); }
/// <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); } }
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); }
/// <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); }
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(); } } }
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); } }
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); } }
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(); }
/// <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; } }
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); }
/// <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)); }
public virtual Extension Parse(byte[] serverHello, ref int currentLen, Int16 extLen, ConnectionEnd end) { return this; }
public virtual void Process(ConnectionEnd end) { }
public FileHelper(ConnectionEnd end) { _pathStreamDict = new Dictionary<string, FileStream>(5); _end = end; }
public virtual void Write(Stream stream, ConnectionEnd end) { }
/// <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); }
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>(); }
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(); }; }
public override Extension Parse(byte[] buffer, ref int currentLen, Int16 extLen, ConnectionEnd end) { this.HandleRenegotiationExt(buffer, ref currentLen, extLen); return this; }