private void FinishConnect(bool Success) { if (Cancellator?.IsCancellationRequested ?? true) { if (Success) { Shutdown(); } Release(true); } else if (Success) { try { lock (Lock) { Stream = new NetworkStream(Socket, false); ConnectionThread = new Thread(NetworkLoop); } ConnectionThread.Start(); State = EncryptionState.Connected; } catch { Release(false); } } else { Release(false); } }
void OnDisconnected( object? sender, DisconnectedEventArgs e ) { state = EncryptionState.Disconnected; encryption = null; Disconnected?.Invoke( this, e ); }
public InboundPacket(InboundEncryptedPacket packet, EncryptionKeys keys) { KeySpace = keys.KeySpace; EncryptedPacket = packet; Payload = keys.DecryptPayload(packet.UnprotectedHeader, packet.EncryptedPayload.Span, packet.PacketNum); }
internal void Disconnect(bool UserInitiated) { lock (Lock) { Cancellator?.Cancel(); State = EncryptionState.Disconnected; Disconnected?.Invoke(UserInitiated); } }
private void Release(bool UserInitiated) { lock (Lock) { Cancellator?.Dispose(); Stream?.Dispose(); Socket?.Dispose(); } State = EncryptionState.Disconnected; Disconnected?.Invoke(UserInitiated); }
internal static string ToSerializedValue(this EncryptionState value) { switch (value) { case EncryptionState.Enabled: return("Enabled"); case EncryptionState.Disabled: return("Disabled"); } return(null); }
void HandleEncryptResult( IPacketMsg packetMsg ) { var result = new Msg<MsgChannelEncryptResult>( packetMsg ); log.LogDebug( nameof(EnvelopeEncryptedConnection), "Encryption result: {0}", result.Body.Result ); DebugLog.Assert( encryption != null, nameof( EnvelopeEncryptedConnection ), "Encryption is null" ); if ( result.Body.Result == EResult.OK && encryption != null ) { state = EncryptionState.Encrypted; Connected?.Invoke( this, EventArgs.Empty ); } else { log.LogDebug( nameof(EnvelopeEncryptedConnection), "Encryption channel setup failed" ); Disconnect( userInitiated: false ); } }
protected EncryptionKeys(EncryptionState state, in byte[] encSecret, in byte[] decSecret, CipherSuite cipherSuite)
protected EncryptedType() { this.encryptionMethod.Init(); this.state = EncryptionState.New; this.tokenSerializer = SecurityStandardsManager.DefaultInstance.SecurityTokenSerializer; }
protected EncryptedType() { this.encryptionMethod.Init(); this.state = EncryptionState.New; this.tokenSerializer = new KeyInfoSerializer(false); }
/// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="EncryptionState" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => EncryptionState.CreateFrom(sourceValue);
void HandleEncryptRequest( IPacketMsg packetMsg ) { var request = new Msg<MsgChannelEncryptRequest>( packetMsg ); var connectedUniverse = request.Body.Universe; var protoVersion = request.Body.ProtocolVersion; log.LogDebug( nameof(EnvelopeEncryptedConnection), "Got encryption request. Universe: {0} Protocol ver: {1}", connectedUniverse, protoVersion ); DebugLog.Assert( protoVersion == 1, nameof(EnvelopeEncryptedConnection), "Encryption handshake protocol version mismatch!" ); DebugLog.Assert( connectedUniverse == universe, nameof(EnvelopeEncryptedConnection), FormattableString.Invariant( $"Expected universe {universe} but server reported universe {connectedUniverse}" ) ); byte[]? randomChallenge; if ( request.Payload.Length >= 16 ) { randomChallenge = request.Payload.ToArray(); } else { randomChallenge = null; } var publicKey = KeyDictionary.GetPublicKey( connectedUniverse ); if ( publicKey == null ) { log.LogDebug( nameof(EnvelopeEncryptedConnection), "HandleEncryptRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", connectedUniverse, protoVersion ); Disconnect( userInitiated: false ); return; } var response = new Msg<MsgChannelEncryptResponse>(); var tempSessionKey = CryptoHelper.GenerateRandomBlock( 32 ); byte[] encryptedHandshakeBlob; using ( var rsa = new RSACrypto( publicKey ) ) { if ( randomChallenge != null ) { var blobToEncrypt = new byte[ tempSessionKey.Length + randomChallenge.Length ]; Array.Copy( tempSessionKey, blobToEncrypt, tempSessionKey.Length ); Array.Copy( randomChallenge, 0, blobToEncrypt, tempSessionKey.Length, randomChallenge.Length ); encryptedHandshakeBlob = rsa.Encrypt( blobToEncrypt ); } else { encryptedHandshakeBlob = rsa.Encrypt( tempSessionKey ); } } var keyCrc = CryptoHelper.CRCHash( encryptedHandshakeBlob ); response.Write( encryptedHandshakeBlob ); response.Write( keyCrc ); response.Write( ( uint )0 ); if (randomChallenge != null) { encryption = new NetFilterEncryptionWithHMAC( tempSessionKey, log ); } else { encryption = new NetFilterEncryption( tempSessionKey, log ); } var serialized = response.Serialize(); try { debugNetworkListener?.OnOutgoingNetworkMessage( response.MsgType, serialized ); } catch ( Exception e ) { log.LogDebug( nameof( EnvelopeEncryptedConnection ), "DebugNetworkListener threw an exception: {0}", e ); } state = EncryptionState.Challenged; Send( serialized ); }
protected EncryptedType() { _encryptionMethod.Init(); _state = EncryptionState.New; }
public void ReadFrom(XmlDictionaryReader reader, long maxBufferSize) { ValidateReadState(); reader.MoveToStartElement(OpeningElementName, NamespaceUri); _encoding = reader.GetAttribute(EncodingAttribute, null); _id = reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null) ?? SecurityUniqueId.Create().Value; _wsuId = reader.GetAttribute(XD.XmlEncryptionDictionary.Id, XD.UtilityDictionary.Namespace) ?? SecurityUniqueId.Create().Value; _mimeType = reader.GetAttribute(MimeTypeAttribute, null); _type = reader.GetAttribute(TypeAttribute, null); ReadAdditionalAttributes(reader); reader.Read(); if (reader.IsStartElement(EncryptionMethodElement.ElementName, NamespaceUri)) { _encryptionMethod.ReadFrom(reader); } if (_tokenSerializer.CanReadKeyIdentifier(reader)) { XmlElement xml = null; XmlDictionaryReader localReader; if (this.ShouldReadXmlReferenceKeyInfoClause) { // We create the dom only when needed to not affect perf. XmlDocument doc = new XmlDocument(); xml = (doc.ReadNode(reader) as XmlElement); localReader = XmlDictionaryReader.CreateDictionaryReader(new XmlNodeReader(xml)); } else { localReader = reader; } try { this.KeyIdentifier = _tokenSerializer.ReadKeyIdentifier(localReader); } catch (Exception e) { // In case when the issued token ( custom token) is used as an initiator token; we will fail // to read the keyIdentifierClause using the plugged in default serializer. So We need to try to read it as an XmlReferencekeyIdentifierClause // if it is the client side. if (Fx.IsFatal(e) || !this.ShouldReadXmlReferenceKeyInfoClause) { throw; } _keyIdentifier = ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader.CreateDictionaryReader(new XmlNodeReader(xml)), e); } } reader.ReadStartElement(CipherDataElementName, EncryptedType.NamespaceUri); reader.ReadStartElement(CipherValueElementName, EncryptedType.NamespaceUri); if (maxBufferSize == 0) { ReadCipherData(reader); } else { ReadCipherData(reader, maxBufferSize); } reader.ReadEndElement(); // CipherValue reader.ReadEndElement(); // CipherData ReadAdditionalElements(reader); reader.ReadEndElement(); // OpeningElementName this.State = EncryptionState.Read; }
private void NetworkLoop() { while (!Cancellator.IsCancellationRequested) { try { if (!Socket.Poll(100000, SelectMode.SelectRead)) { continue; } } catch (SocketException) { break; } byte[] Data; try { byte[] Buffer = new byte[8]; Stream.Read(Buffer, 0, 8); int PacketLength = ToInt32(Buffer, 0); if (ToUInt32(Buffer, 4) != 0x31305456U) { break; } Data = new byte[PacketLength]; int Offset = 0; do { int BytesRead = Stream.Read(Data, Offset, PacketLength); if (BytesRead == 0) { break; } Offset += BytesRead; PacketLength -= BytesRead; } while (PacketLength > 0); if (PacketLength != 0) { break; } } catch (IOException) { break; } try { if (State == EncryptionState.Encrypted) { MessageReceived(Encryptor.Decrypt(Data)); } else { MessageType Type = MessageType.Invalid; if (Data.Length > 3) { Type = (MessageType)(ToUInt32(Data, 0) & ~0x80000000U); } if (State == EncryptionState.Connected && Type == MessageType.ChannelEncrypt) { RawMessage <ChannelEncrypt> Message = new RawMessage <ChannelEncrypt>(Data); if (Message.Payload.Length >= 16) { RawMessage <ChannelEncrypt> Response = new RawMessage <ChannelEncrypt>(MessageType.ChannelEncryptResponse); byte[] Challenge = Message.Payload, EncryptedBlob, SessionKey = new byte[32]; using (RandomNumberGenerator RNG = RandomNumberGenerator.Create()) RNG.GetBytes(SessionKey); using (RSA RSA = RSA.Create()) { RSA.ImportParameters(Parameters); byte[] BlobToEncrypt = new byte[32 + Challenge.Length]; Copy(SessionKey, BlobToEncrypt, 32); Copy(Challenge, 0, BlobToEncrypt, 32, Challenge.Length); EncryptedBlob = RSA.Encrypt(BlobToEncrypt, RSAEncryptionPadding.OaepSHA1); } byte[] CRCHash; using (CRC32 CRC = new CRC32()) CRCHash = CRC.ComputeHash(EncryptedBlob); int Length = EncryptedBlob.Length; Response.Payload = new byte[Length + 8]; Copy(EncryptedBlob, Response.Payload, Length); Copy(CRCHash, 0, Response.Payload, Length, 4); Encryptor = new EncryptionFilter(SessionKey); State = EncryptionState.Challenged; Send(Response.Serialize()); } else { Disconnect(false); } } else if (State == EncryptionState.Challenged && Type == MessageType.ChannelEncryptResult) { if (new RawMessage <ChannelEncryptResult>(Data).Body.Success) { State = EncryptionState.Encrypted; Log($"Established encrypted TCP connection to {EndpointAddress}"); Connected?.Invoke(); } else { Disconnect(false); } } else { Disconnect(false); } } } catch { } } bool UserInitiated = Cancellator.IsCancellationRequested; if (UserInitiated) { Shutdown(); } Release(UserInitiated); }
void OnConnected( object? sender, EventArgs e ) { state = EncryptionState.Connected; }