public TlsServerHello (TlsContext context, TlsBuffer incoming) : base (HandshakeType.ServerHello) { ServerProtocol = (TlsProtocolCode)incoming.ReadInt16 (); Read (incoming); }
public TlsClientHello (TlsContext context, TlsBuffer incoming) : base (HandshakeType.ClientHello) { ClientProtocol = (TlsProtocolCode)incoming.ReadInt16 (); Read (incoming); }
protected override void Read (TlsBuffer incoming) { KeyExchange.ReadServer (incoming); if (incoming.Remaining != 0) throw new TlsException (AlertDescription.DecodeError); }
protected override void Read (TlsBuffer incoming) { ClientRandom = new SecureBuffer (incoming.ReadBytes (32)); var length = (short)incoming.ReadByte (); SessionID = new SecureBuffer (incoming.ReadBytes (length)); length = incoming.ReadInt16 (); if ((length % 2) != 0) throw new TlsException (AlertDescription.DecodeError); bool seenSCSV = false; ClientCiphers = new CipherSuiteCode [length >> 1]; for (int i = 0; i < ClientCiphers.Length; i++) { ClientCiphers [i] = (CipherSuiteCode)incoming.ReadInt16 (); if (ClientCiphers [i] == CipherSuiteCode.TLS_EMPTY_RENEGOTIATION_INFO_SCSV) seenSCSV = true; } // Compression methods length = incoming.ReadByte (); incoming.Position += length; Extensions = new TlsExtensionCollection (incoming); if (seenSCSV) Extensions.AddRenegotiationExtension (); }
public override void ReadServer (TlsBuffer incoming) { P = incoming.ReadBytes (incoming.ReadInt16 ()); G = incoming.ReadBytes (incoming.ReadInt16 ()); Y = incoming.ReadBytes (incoming.ReadInt16 ()); Signature = Signature.Read (protocol, incoming); }
public TlsCertificateRequest (TlsProtocolCode protocol, TlsBuffer incoming) : base (HandshakeType.CertificateRequest) { Protocol = protocol; Parameters = new ClientCertificateParameters (); Read (incoming); }
public override void Encode (TlsBuffer buffer) { var size = Data != null ? Data.Size : 0; buffer.Write ((short)ExtensionType); buffer.Write ((short)(size + 1)); buffer.Write ((byte)size); if (Data != null) buffer.Write (Data.Buffer); }
public override void Encode (TlsBuffer buffer) { var algorithms = SignatureParameters.SignatureAndHashAlgorithms; buffer.Write ((short)ExtensionType); buffer.Write ((short)(algorithms.Count * 2 + 2)); buffer.Write ((short)(algorithms.Count * 2)); foreach (var algorithm in algorithms) algorithm.Encode (buffer); }
public override void Encode (TlsBuffer buffer) { var asciiName = Encoding.ASCII.GetBytes (ServerName); buffer.Write ((short)ExtensionType); buffer.Write ((short)(asciiName.Length + 5)); // ServerNameList buffer.Write ((short)(asciiName.Length + 3)); // ServerList buffer.Write ((byte)0x00); // HostName buffer.Write ((short)asciiName.Length); buffer.Write (asciiName); }
protected virtual TlsServerHello GenerateServerHello() { var serverUnixTime = HandshakeParameters.GetUnixTime(); HandshakeParameters.ServerRandom = Context.Session.GetSecureRandomBytes(32); TlsBuffer.WriteInt32(HandshakeParameters.ServerRandom.Buffer, 0, serverUnixTime); return(new TlsServerHello( Context.NegotiatedProtocol, HandshakeParameters.ServerRandom, HandshakeParameters.SessionId, PendingCrypto.Cipher.Code, HandshakeParameters.ActiveExtensions)); }
public override void Encode(TlsBuffer buffer) { var asciiName = Encoding.ASCII.GetBytes(ServerName); buffer.Write((short)ExtensionType); buffer.Write((short)(asciiName.Length + 5)); // ServerNameList buffer.Write((short)(asciiName.Length + 3)); // ServerList buffer.Write((byte)0x00); // HostName buffer.Write((short)asciiName.Length); buffer.Write(asciiName); }
public override void Encode(TlsBuffer buffer) { var size = Data != null ? Data.Size : 0; buffer.Write((short)ExtensionType); buffer.Write((short)(size + 1)); buffer.Write((byte)size); if (Data != null) { buffer.Write(Data.Buffer); } }
public override void Encode(TlsBuffer buffer) { var algorithms = SignatureParameters.SignatureAndHashAlgorithms; buffer.Write((short)ExtensionType); buffer.Write((short)(algorithms.Count * 2 + 2)); buffer.Write((short)(algorithms.Count * 2)); foreach (var algorithm in algorithms) { SignatureHelper.EncodeSignatureAndHashAlgorithm(algorithm, buffer); } }
public override bool ProcessClient(TlsContext context) { if (context.IsServer) { throw new InvalidOperationException(); } if (!context.HandshakeParameters.RequestedSecureNegotiation) { throw new TlsException(AlertDescription.HandshakeFailure); } if (!context.Session.SecureRenegotiation) { // Initial handshake if (Data != null && Data.Size > 0) { throw new TlsException(AlertDescription.HandshakeFailure); } context.HandshakeParameters.SecureNegotiationSupported = true; return(true); } var clientData = context.Session.ClientVerifyData; var serverData = context.Session.ServerVerifyData; #if DEBUG_FULL if (context.EnableDebugging) { DebugHelper.WriteLine("CHECKING CLIENT DATA", clientData); DebugHelper.WriteLine("CHECKING SERVER DATA", serverData); DebugHelper.WriteLine("CHECKING WHAT WE GOT", Data); } #endif var expectedLength = clientData.Size + serverData.Size; if (Data.Size != expectedLength) { throw new TlsException(AlertDescription.DecodeError); } if (!TlsBuffer.Compare(clientData.Buffer, 0, clientData.Size, Data.Buffer, 0, clientData.Size)) { throw new TlsException(AlertDescription.HandshakeFailure); } if (!TlsBuffer.Compare(serverData.Buffer, 0, serverData.Size, Data.Buffer, clientData.Size, serverData.Size)) { throw new TlsException(AlertDescription.HandshakeFailure); } context.HandshakeParameters.SecureNegotiationSupported = true; return(true); }
protected virtual void HandleFinished(TlsFinished message) { var digest = HandshakeParameters.HandshakeMessages.GetHash(Session.Read.Cipher.HandshakeHashType); var hash = Session.Read.Cipher.PRF.ComputeClientHash(Session.Read.MasterSecret, digest); // Check server prf against client prf if (!TlsBuffer.Compare(message.Hash, hash)) { throw new TlsException(AlertDescription.HandshakeFailure); } Session.ClientVerifyData = hash; }
public void SetCipherList(ICollection <CipherSuiteCode> ciphers) { var codes = new TlsBuffer(ciphers.Count * 2); foreach (var cipher in ciphers) { codes.Write((short)cipher); } var ret = native_openssl_set_cipher_list(handle, codes.Buffer, ciphers.Count); CheckError(ret); }
public static Signature Read (TlsProtocolCode protocol, TlsBuffer incoming) { switch (protocol) { case TlsProtocolCode.Tls10: return new SignatureTls10 (incoming); case TlsProtocolCode.Tls11: return new SignatureTls11 (incoming); case TlsProtocolCode.Tls12: return new SignatureTls12 (incoming); default: throw new NotSupportedException (); } }
public SignatureAlgorithmsExtension (TlsBuffer incoming) { var length = incoming.ReadInt16 (); if ((length % 2) != 0) throw new TlsException (AlertDescription.DecodeError); SignatureParameters = new SignatureParameters (); var count = length >> 1; for (int i = 0; i < count; i++) { SignatureParameters.SignatureAndHashAlgorithms.Add (new SignatureAndHashAlgorithm (incoming)); } }
static byte[] ComputeRecordMAC(TlsProtocolCode protocol, HMac hmac, ulong seqnum, ContentType contentType, IBufferOffsetSize fragment) { var header = new TlsBuffer(13); header.Write(seqnum); header.Write((byte)contentType); header.Write((short)protocol); header.Write((short)fragment.Size); hmac.Reset(); hmac.TransformBlock(header.Buffer, 0, header.Size); hmac.TransformBlock(fragment.Buffer, fragment.Offset, fragment.Size); return(hmac.TransformFinalBlock()); }
protected override void Read(TlsBuffer incoming) { var length = incoming.ReadByte(); for (int i = 0; i < length; i++) { Parameters.CertificateTypes.Add((ClientCertificateType)incoming.ReadByte()); } if (Protocol == TlsProtocolCode.Tls12) { var length2 = incoming.ReadInt16(); if ((length2 % 2) != 0) { throw new TlsException(AlertDescription.IlegalParameter); } var signatureTypes = new SignatureAndHashAlgorithm [length2 >> 1]; for (int i = 0; i < signatureTypes.Length; i++) { Parameters.SignatureParameters.SignatureAndHashAlgorithms.Add(SignatureHelper.DecodeSignatureAndHashAlgorithm(incoming)); } } var length3 = incoming.ReadInt16(); if (incoming.Remaining != length3) { throw new TlsException(AlertDescription.DecodeError); } /* * Read requested certificate authorities (Distinguised Names) * * Name ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET OF AttributeValueAssertion * * AttributeValueAssertion ::= SEQUENCE { * attributeType OBJECT IDENTIFIER * attributeValue ANY * } * */ while (incoming.Remaining > 0) { var rdn = new ASN1(incoming.ReadBytes(incoming.ReadInt16())); Parameters.CertificateAuthorities.Add(X501.ToString(rdn)); } }
SecureBuffer CreateParameterBuffer(HandshakeParameters hsp) { var length = 4 + publicBytes.Length; var buffer = new TlsBuffer(64 + length); buffer.Write(hsp.ClientRandom.Buffer); buffer.Write(hsp.ServerRandom.Buffer); buffer.Write((byte)curveType); buffer.Write((short)namedCurve); buffer.Write((byte)publicBytes.Length); buffer.Write(publicBytes); return(new SecureBuffer(buffer.Buffer)); }
public ServerNameExtension (TlsBuffer incoming) { if (incoming.Remaining == 0) return; var length = incoming.ReadInt16 (); if (length != incoming.Remaining) throw new TlsException (AlertDescription.DecodeError); var type = incoming.ReadByte (); if (type != 0x00) throw new TlsException (AlertDescription.IlegalParameter, "Unknown NameType in ServerName extension"); var nameLength = incoming.ReadInt16 (); if (nameLength + 3 != length) throw new TlsException (AlertDescription.DecodeError); ServerName = Encoding.ASCII.GetString (incoming.ReadBytes (nameLength)); }
public void TestDecrypt(TestContext ctx, [TestHost] IEncryptionTestHost host) { var input = GetBuffer(HelloWorldResult); var output = new TlsBuffer(input.Size); var hello = GetField(HelloWorldName); var length = host.Decrypt(input, output.GetRemaining()); ctx.Assert(length, Is.EqualTo(hello.Length), "#1"); output.Position = 0; var decrypted = output.ReadBytes(length); ctx.Assert(decrypted, Is.EqualTo(hello), "#4"); }
SecureBuffer CreateParameterBuffer(HandshakeParameters hsp) { var length = P.Length + G.Length + Y.Length + 6; var buffer = new TlsBuffer(64 + length); buffer.Write(hsp.ClientRandom.Buffer); buffer.Write(hsp.ServerRandom.Buffer); buffer.Write((short)P.Length); buffer.Write(P); buffer.Write((short)G.Length); buffer.Write(G); buffer.Write((short)Y.Length); buffer.Write(Y); return(new SecureBuffer(buffer.Buffer)); }
protected virtual TlsClientHello GenerateClientHello() { var clientUnixTime = HandshakeParameters.GetUnixTime(); HandshakeParameters.ClientRandom = Context.Session.GetSecureRandomBytes(32); TlsBuffer.WriteInt32(HandshakeParameters.ClientRandom.Buffer, 0, clientUnixTime); var requestedUserCiphers = Config.UserSettings != null ? Config.UserSettings.RequestedCiphers : null; CipherSuiteCollection requestedCiphers; if (requestedUserCiphers != null) { requestedCiphers = new CipherSuiteCollection(Config.RequestedProtocol, requestedUserCiphers); } else { requestedCiphers = CipherSuiteFactory.GetDefaultCiphers(Config.RequestedProtocol); } if (requestedCiphers.Protocol != Config.RequestedProtocol) { throw new TlsException(AlertDescription.ProtocolVersion); } HandshakeParameters.SupportedCiphers = requestedCiphers.Clone(); if (Config.EnableSecureRenegotiation && !Session.SecureRenegotiation && ((Config.RenegotiationFlags & RenegotiationFlags.SendCipherSpecCode) != 0)) { HandshakeParameters.SupportedCiphers.AddSCSV(); } if (ServerNameExtension.IsLegalHostName(Config.TargetHost)) { HandshakeParameters.RequestedExtensions.Add(new ServerNameExtension(Config.TargetHost)); } if (Config.EnableSecureRenegotiation && (Session.SecureRenegotiation || ((Config.RenegotiationFlags & RenegotiationFlags.SendClientHelloExtension) != 0))) { HandshakeParameters.RequestedExtensions.Add(RenegotiationExtension.CreateClient(Context)); } if (UserSettings.HasClientCertificateParameters) { HandshakeParameters.RequestedExtensions.Add(new SignatureAlgorithmsExtension(UserSettings.ClientCertificateParameters.SignatureAndHashAlgorithms)); } return(new TlsClientHello( Config.RequestedProtocol, HandshakeParameters.ClientRandom, HandshakeParameters.SessionId, HandshakeParameters.SupportedCiphers.ToArray(), HandshakeParameters.RequestedExtensions)); }
public static Signature Read(TlsProtocolCode protocol, TlsBuffer incoming) { switch (protocol) { case TlsProtocolCode.Tls10: return(new SignatureTls10(incoming)); case TlsProtocolCode.Tls11: return(new SignatureTls11(incoming)); case TlsProtocolCode.Tls12: return(new SignatureTls12(incoming)); default: throw new NotSupportedException(); } }
protected override HandshakeMessage CreateMessage (HandshakeType type, TlsBuffer incoming) { if (type != HandshakeType.ClientHello) throw new TlsException (AlertDescription.UnexpectedMessage); if (Renegotiating) { var flags = Config.RenegotiationFlags; if ((flags & RenegotiationFlags.DisallowRenegotiation) != 0) throw new TlsException (AlertDescription.HandshakeFailure, "Renegotiation not allowed."); if (!Session.SecureRenegotiation) throw new TlsException (AlertDescription.HandshakeFailure, "Renegotiation not allowed."); } StartHandshake (); return base.CreateMessage (type, incoming); }
internal static TlsExtension CreateExtension(ExtensionType type, TlsBuffer buffer) { switch (type) { case ExtensionType.ServerName: return(new ServerNameExtension(buffer)); case ExtensionType.SignatureAlgorithms: return(new SignatureAlgorithmsExtension(buffer)); case ExtensionType.Renegotiation: return(new RenegotiationExtension(buffer)); default: return(null); } }
public void TestInputOffset(TestContext ctx, [TestHost] IEncryptionTestHost host) { var hello = GetBuffer(HelloWorldName); var input = new TlsBuffer(hello.Size + MagicDataSize + MagicData2Size); input.Write(GetField(MagicDataName)); var startPos = input.Position; input.Write(hello); input.Write(GetBuffer(MagicData2Name)); var output = host.Encrypt(new BufferOffsetSize(input.Buffer, startPos, hello.Size)); ctx.Assert(output, Is.Not.Null, "#1"); ctx.Assert(output.Size, Is.GreaterThanOrEqualTo(hello.Size + host.MinExtraEncryptedBytes), "#2"); ctx.Assert(output.Size, Is.LessThanOrEqualTo(hello.Size + host.MaxExtraEncryptedBytes), "#2"); CheckOutput(ctx, HelloWorldResult, output); }
public void TestInputOffset() { var hello = GetBuffer(HelloWorldName); var input = new TlsBuffer(hello.Size + MagicDataSize + MagicData2Size); input.Write(GetBuffer(MagicDataName)); var startPos = input.Position; input.Write(hello); input.Write(GetBuffer(MagicData2Name)); var output = Context.Encrypt(new BufferOffsetSize(input.Buffer, startPos, hello.Size)); Assert.That(output, Is.Not.Null, "#1"); Assert.That(output.Size, Is.EqualTo(hello.Size + Context.MinExtraEncryptedBytes), "#2"); CheckOutput(HelloWorldResult, output); }
public SignatureAlgorithmsExtension(TlsBuffer incoming) { var length = incoming.ReadInt16(); if ((length % 2) != 0) { throw new TlsException(AlertDescription.DecodeError); } SignatureParameters = new SignatureParameters(); var count = length >> 1; for (int i = 0; i < count; i++) { SignatureParameters.SignatureAndHashAlgorithms.Add(SignatureHelper.DecodeSignatureAndHashAlgorithm(incoming)); } }
public SignatureAlgorithmsExtension(TlsBuffer incoming) { var length = incoming.ReadInt16(); if ((length % 2) != 0) { throw new TlsException(AlertDescription.DecodeError); } var count = length >> 1; var algorithms = new List <SignatureAndHashAlgorithm> (count); for (int i = 0; i < count; i++) { algorithms.Add(new SignatureAndHashAlgorithm(incoming)); } Algorithms = algorithms; }
public override TlsExtension ProcessServer(TlsContext context) { if (!context.IsServer) { throw new InvalidOperationException(); } if (context.Session.SecureRenegotiation) { if (!TlsBuffer.Compare(context.Session.ClientVerifyData, Data)) { throw new TlsException(AlertDescription.HandshakeFailure); } } else { if (Data != null && Data.Size != 0) { throw new TlsException(AlertDescription.HandshakeFailure); } context.HandshakeParameters.RequestedSecureNegotiation = true; context.HandshakeParameters.SecureNegotiationSupported = true; context.Session.SecureRenegotiation = true; return(new RenegotiationExtension(new SecureBuffer(0))); } var clientData = context.Session.ClientVerifyData; var serverData = context.Session.ServerVerifyData; #if DEBUG_FULL if (context.EnableDebugging) { DebugHelper.WriteLine("WRITING CLIENT DATA", clientData); DebugHelper.WriteLine("WRITING SERVER DATA", serverData); } #endif var data = new SecureBuffer(clientData.Size + serverData.Size); Buffer.BlockCopy(clientData.Buffer, 0, data.Buffer, 0, clientData.Size); Buffer.BlockCopy(serverData.Buffer, 0, data.Buffer, clientData.Size, serverData.Size); return(new RenegotiationExtension(data)); }
protected override void Read (TlsBuffer incoming) { // Server random ServerRandom = new SecureBuffer (incoming.ReadBytes (32)); // Session ID var sessionIdLength = (int)incoming.ReadByte (); if (sessionIdLength > 0) { SessionID = new SecureBuffer (incoming.ReadBytes (sessionIdLength)); } // Cipher suite SelectedCipher = (CipherSuiteCode)incoming.ReadInt16 (); var compressionMethod = incoming.ReadByte (); if (compressionMethod != 0) throw new TlsException (AlertDescription.IlegalParameter, "Invalid compression method received from server"); Extensions = new TlsExtensionCollection (incoming); }
protected override int Encrypt(DisposeContext d, ContentType contentType, IBufferOffsetSize input, IBufferOffsetSize output) { // Calculate message MAC byte[] mac = null; if (IsServer) { mac = ComputeServerRecordMAC(contentType, input); } else { mac = ComputeClientRecordMAC(contentType, input); } #if DEBUG_FULL if (Cipher.EnableDebugging) { DebugHelper.WriteLine("RECORD MAC", mac); } #endif int plen; byte padLen; int totalLength = GetEncryptedSize(input.Size, out plen, out padLen); var totalOutput = new BufferOffsetSize(output.Buffer, output.Offset, totalLength); var outputWriter = new TlsBuffer(totalOutput); outputWriter.Position += HeaderSize; outputWriter.Write(input.Buffer, input.Offset, input.Size); outputWriter.Write(mac); for (int i = 0; i <= padLen; i++) { outputWriter.Write(padLen); } // Encrypt the message EncryptRecord(d, totalOutput); return(totalLength); }
protected override void Read (TlsBuffer incoming) { var length = incoming.ReadInt24 (); var endOffset = incoming.Position + length; while (incoming.Position < endOffset) { var certLength = incoming.ReadInt24 (); if (certLength == 0) break; var buffer = incoming.ReadBytes (certLength); // Create a new X509 Certificate var certificate = new X509Certificate (buffer); Certificates.Add (certificate); } if (incoming.Position != endOffset || incoming.Remaining != 0) throw new TlsException (AlertDescription.DecodeError); }
public ServerNameExtension(TlsBuffer incoming) { var length = incoming.ReadInt16(); if (length != incoming.Remaining) { throw new TlsException(AlertDescription.DecodeError); } var type = incoming.ReadByte(); if (type != 0x00) { throw new TlsException(AlertDescription.IlegalParameter, "Unknown NameType in ServerName extension"); } var nameLength = incoming.ReadInt16(); if (nameLength + 3 != length) { throw new TlsException(AlertDescription.DecodeError); } ServerName = Encoding.ASCII.GetString(incoming.ReadBytes(nameLength)); }
protected override void Read (TlsBuffer incoming) { var length = incoming.ReadByte (); for (int i = 0; i < length; i++) Parameters.CertificateTypes.Add ((ClientCertificateType)incoming.ReadByte ()); if (Protocol == TlsProtocolCode.Tls12) { var length2 = incoming.ReadInt16 (); if ((length2 % 2) != 0) throw new TlsException (AlertDescription.IlegalParameter); var signatureTypes = new SignatureAndHashAlgorithm [length2 >> 1]; for (int i = 0; i < signatureTypes.Length; i++) Parameters.SignatureParameters.SignatureAndHashAlgorithms.Add (new SignatureAndHashAlgorithm (incoming)); } var length3 = incoming.ReadInt16 (); if (incoming.Remaining != length3) throw new TlsException (AlertDescription.DecodeError); /* * Read requested certificate authorities (Distinguised Names) * * Name ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET OF AttributeValueAssertion * * AttributeValueAssertion ::= SEQUENCE { * attributeType OBJECT IDENTIFIER * attributeValue ANY * } * */ while (incoming.Remaining > 0) { var rdn = new ASN1 (incoming.ReadBytes (incoming.ReadInt16 ())); Parameters.CertificateAuthorities.Add (X501.ToString (rdn)); } }
public void TestDecryptWithInvalidPadding2(TestContext ctx, [TestHost] IEncryptionTestHost host) { var input = GetBuffer(Data11Result); var modified = new TlsBuffer(input.Size); modified.Write(input.Buffer); // Flip a bit in the last byte, this will affect the padding size. modified.Buffer [modified.Size - 1] ^= 0x01; input = new BufferOffsetSize(modified.Buffer, 0, modified.Size); try { host.Decrypt(input); ctx.AssertFail("#1"); } catch (Exception ex) { ctx.Assert(ex, Is.InstanceOf <TlsException> (), "#2"); var tlsEx = (TlsException)ex; ctx.Assert(tlsEx.Alert.Level, Is.EqualTo(AlertLevel.Fatal), "#3"); ctx.Assert(tlsEx.Alert.Description, Is.EqualTo(AlertDescription.BadRecordMAC), "#4"); } }
protected override void Read(TlsBuffer incoming) { ClientRandom = new SecureBuffer(incoming.ReadBytes(32)); var length = (short)incoming.ReadByte(); SessionID = new SecureBuffer(incoming.ReadBytes(length)); length = incoming.ReadInt16(); if ((length % 2) != 0) { throw new TlsException(AlertDescription.DecodeError); } bool seenSCSV = false; ClientCiphers = new CipherSuiteCode [length >> 1]; for (int i = 0; i < ClientCiphers.Length; i++) { ClientCiphers [i] = (CipherSuiteCode)incoming.ReadInt16(); if (ClientCiphers [i] == CipherSuiteCode.TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { seenSCSV = true; } } // Compression methods length = incoming.ReadByte(); incoming.Position += length; Extensions = new TlsExtensionCollection(incoming); if (seenSCSV) { Extensions.AddRenegotiationExtension(); } }
public void TestDecryptWithInvalidPadding(TestContext ctx, [TestHost] IEncryptionTestHost host) { var input = GetBuffer(ExtraPaddingResult); var modified = new TlsBuffer(input.Size); modified.Write(input.Buffer); var theOffset = modified.Size - (2 * host.BlockSize) - 5; modified.Buffer [theOffset] ^= 0x01; input = new BufferOffsetSize(modified.Buffer, 0, modified.Size); try { host.Decrypt(input); ctx.AssertFail("#1"); } catch (Exception ex) { ctx.Assert(ex, Is.InstanceOf <TlsException> (), "#2"); var tlsEx = (TlsException)ex; ctx.Assert(tlsEx.Alert.Level, Is.EqualTo(AlertLevel.Fatal), "#3"); ctx.Assert(tlsEx.Alert.Description, Is.EqualTo(AlertDescription.BadRecordMAC), "#4"); } }
protected virtual TlsClientHello GenerateClientHello() { var clientUnixTime = HandshakeParameters.GetUnixTime(); TlsBuffer.WriteInt32(HandshakeParameters.ClientRandom.Buffer, 0, clientUnixTime); if (ServerNameExtension.IsLegalHostName(Config.TargetHost)) { HandshakeParameters.RequestedExtensions.Add(new ServerNameExtension(Config.TargetHost)); } if (Config.EnableSecureRenegotiation && (Session.SecureRenegotiation || ((Config.RenegotiationFlags & RenegotiationFlags.SendClientHelloExtension) != 0))) { HandshakeParameters.RequestedExtensions.Add(RenegotiationExtension.CreateClient(Context)); } if (Session.SignatureParameters != null) { HandshakeParameters.RequestedExtensions.Add(new SignatureAlgorithmsExtension(Session.SignatureParameters)); } return(new TlsClientHello( Config.RequestedProtocol, HandshakeParameters.ClientRandom, HandshakeParameters.SessionId, HandshakeParameters.SupportedCiphers.ToArray(), HandshakeParameters.RequestedExtensions)); }
protected override HandshakeMessage CreateMessage(HandshakeType type, TlsBuffer incoming) { if (type != HandshakeType.ClientHello) { throw new TlsException(AlertDescription.UnexpectedMessage); } if (Renegotiating) { var flags = Config.RenegotiationFlags; if ((flags & RenegotiationFlags.DisallowRenegotiation) != 0) { throw new TlsException(AlertDescription.HandshakeFailure, "Renegotiation not allowed."); } if (!Session.SecureRenegotiation) { throw new TlsException(AlertDescription.HandshakeFailure, "Renegotiation not allowed."); } } StartHandshake(); return(base.CreateMessage(type, incoming)); }
protected override void Read (TlsBuffer incoming) { Hash = new SecureBuffer (incoming.ReadBytes (12)); if (incoming.Remaining != 0) throw new TlsException (AlertDescription.DecodeError); }
bool DecryptRecordFragment (ContentType contentType, ref TlsBuffer buffer) { var read = Session.Read; if (read == null || read.Cipher == null) return false; var output = read.Decrypt (contentType, buffer.GetRemaining ()); buffer = new TlsBuffer (output); return true; }
bool ReadStandardBuffer (ContentType contentType, ref TlsBuffer buffer) { if (buffer.Remaining < 4) throw new TlsException ( AlertDescription.DecodeError, "buffer underrun"); short protocolCode = buffer.ReadInt16 (); short length = buffer.ReadInt16 (); #if DEBUG_FULL if (EnableDebugging) { DebugHelper.WriteLine ("ReadStandardBuffer: {0:x} {1:x}", protocolCode, length); DebugHelper.WriteRemaining (" Buffer", buffer); } #endif if (HasNegotiatedProtocol) { var protocol = (TlsProtocolCode)protocolCode; if (protocol != NegotiatedProtocol) throw new TlsException (AlertDescription.ProtocolVersion); } else { if ((protocolCode >> 8 != 3) || ((protocolCode & 0x00ff) < 1)) throw new TlsException (AlertDescription.ProtocolVersion); } if (length != buffer.Remaining) throw new TlsException ( AlertDescription.DecodeError, "Invalid buffer size"); return DecryptRecordFragment (contentType, ref buffer); }
SecurityStatus _EncryptMessage (ref TlsBuffer incoming) { #if DEBUG_FULL if (EnableDebugging) DebugHelper.WriteRemaining ("EncryptMessage", incoming); #endif var buffer = EncodeRecord (ContentType.ApplicationData, incoming.GetRemaining ()); #if DEBUG_FULL if (EnableDebugging) DebugHelper.WriteBuffer ("EncryptMessage done", buffer); #endif incoming = new TlsBuffer (buffer); return SecurityStatus.OK; }
public SecurityStatus EncryptMessage (ref TlsBuffer incoming) { try { CheckValid (); return _EncryptMessage (ref incoming); } catch (TlsException ex) { OnError (ex); var alert = CreateAlert (ex.Alert); incoming = new TlsBuffer (alert); Clear (); return SecurityStatus.ContextExpired; } catch { Clear (); throw; } }
public override void ReadClient (TlsBuffer incoming) { clientKey = incoming.ReadBytes (incoming.ReadByte ()); }
public abstract void ReadClient(TlsBuffer incoming);
SecurityStatus ProcessAlert (TlsBuffer buffer) { bool decrypted = false; if ((session.Read != null && session.Read.Cipher != null) || (buffer.Remaining != 2)) decrypted = ReadStandardBuffer (ContentType.Alert, ref buffer); if (buffer.Remaining != 2) throw new TlsException (AlertDescription.IlegalParameter, "Invalid Alert message size"); var level = (AlertLevel)buffer.ReadByte (); var description = (AlertDescription)buffer.ReadByte (); if (decrypted) buffer.Dispose (); if (level == AlertLevel.Warning) { if (description == AlertDescription.CloseNotify) { ReceivedCloseNotify = true; if (eventSink != null) eventSink.ReceivedCloseNotify (); return SecurityStatus.ContextExpired; } DebugHelper.WriteLine ("Received alert: {0}", description); return SecurityStatus.ContinueNeeded; } else { throw new TlsException (description); } }
SecurityStatus _GenerateNextToken (TlsBuffer incoming, TlsMultiBuffer outgoing) { #if DEBUG_FULL if (EnableDebugging) { DebugHelper.WriteLine ("GenerateNextToken: {0}", negotiationHandler); if (incoming != null) DebugHelper.WriteRemaining (" incoming", incoming); } #endif if (incoming == null) { negotiationHandler = negotiationHandler.GenerateReply (outgoing); return SecurityStatus.ContinueNeeded; } var contentType = (ContentType)incoming.ReadByte (); #if DEBUG_FULL if (EnableDebugging) DebugHelper.WriteLine (" received message type {0}", contentType); #endif if (skipToOffset >= 0 && contentType != ContentType.Handshake) throw new TlsException (AlertDescription.InternalError); if (contentType == ContentType.Alert) return ProcessAlert (incoming); bool decrypted = false; if (cachedFragment != null) { if (contentType != ContentType.Handshake) throw new TlsException (AlertDescription.DecodeError); decrypted = ReadStandardBuffer (ContentType.Handshake, ref incoming); cachedFragment.Write (incoming.Buffer, incoming.Position, incoming.Remaining); if (cachedFragment.Remaining > 0) return SecurityStatus.ContinueNeeded; incoming.Dispose (); incoming = cachedFragment; cachedFragment = null; incoming.Position = 0; } else { decrypted = ReadStandardBuffer (contentType, ref incoming); } if (Session.Read != null && Session.Read.Cipher != null && !decrypted) throw new TlsException (AlertDescription.DecryptError, "Expected encrypted message."); try { if (contentType == ContentType.ChangeCipherSpec) return negotiationHandler.ProcessMessage (new TlsChangeCipherSpec ()); else if (contentType == ContentType.ApplicationData) { if (session.Read == null || session.Read.Cipher == null || !session.SecureRenegotiation) throw new TlsException (AlertDescription.DecodeError); // FIXME throw new NotImplementedException (); } else if (contentType != ContentType.Handshake) { throw new TlsException (AlertDescription.UnexpectedMessage); } if (skipToOffset >= 0) { incoming.Position = skipToOffset; skipToOffset = -1; } SecurityStatus result; bool finished; while (true) { var startOffset = incoming.Position; finished = ProcessHandshakeMessage (incoming, out result); if (result == SecurityStatus.CredentialsNeeded) { // Caller will call us again with the same input. skipToOffset = startOffset; if (decrypted) Session.Read.ReadSequenceNumber--; return result; } if (incoming.Remaining == 0) break; if (finished || result != SecurityStatus.ContinueNeeded) throw new TlsException (AlertDescription.UnexpectedMessage); } if (finished) negotiationHandler = negotiationHandler.GenerateReply (outgoing); return result; } finally { if (decrypted) incoming.Dispose (); } }
public SecurityStatus GenerateNextToken (TlsBuffer incoming, TlsMultiBuffer outgoing) { try { CheckValid (); return _GenerateNextToken (incoming, outgoing); } catch (TlsException ex) { OnError (ex); if (negotiationHandler != null && negotiationHandler.CanSendAlert) { var alert = CreateAlert (ex.Alert); outgoing.Add (alert); } Clear (); return SecurityStatus.ContextExpired; } catch { Clear (); throw; } }
public override void ReadServer (TlsBuffer incoming) { curveType = (ECCurveType)incoming.ReadByte (); // Currently, we only support named curves if (curveType == ECCurveType.named_curve) { namedCurve = (NamedCurve)incoming.ReadInt16 (); // TODO Check namedCurve is one we offered? domainParameters = NamedCurveHelper.GetECParameters (namedCurve); } else { // TODO Add support for explicit curve parameters throw new TlsException (AlertDescription.HandshakeFailure, "Unsupported elliptic curve type `{0}'.", curveType); } var publicLength = incoming.ReadByte (); publicBytes = incoming.ReadBytes (publicLength); // TODO Check RFC 4492 for validation serverQ = domainParameters.Curve.DecodePoint (publicBytes); Signature = Signature.Read (TlsProtocolCode.Tls12, incoming); }
SecureBuffer CreateParameterBuffer (HandshakeParameters hsp) { var length = 4 + publicBytes.Length; var buffer = new TlsBuffer (64 + length); buffer.Write (hsp.ClientRandom.Buffer); buffer.Write (hsp.ServerRandom.Buffer); buffer.Write ((byte)curveType); buffer.Write ((short)namedCurve); buffer.Write ((byte)publicBytes.Length); buffer.Write (publicBytes); return new SecureBuffer (buffer.Buffer); }
public TlsFinished (TlsBuffer incoming) : base (HandshakeType.Finished) { Read (incoming); }
public bool ProcessHandshakeMessage(HandshakeType type, TlsBuffer incoming, out SecurityStatus status) { if (HasPendingOutput && type != HandshakeType.HelloRequest) { throw new TlsException(AlertDescription.InternalError); } if (!VerifyMessage(type)) { throw new TlsException(AlertDescription.UnexpectedMessage); } var incomingBuffer = new BufferOffsetSize(incoming.Buffer, incoming.Position - 4, incoming.Remaining + 4); var startPosition = incoming.Position - 4; var message = CreateMessage(type, incoming); incoming.Position = startPosition; #if FIXME incoming.Offset = incoming.Position; #endif #if DEBUG_FULL if (Context.EnableDebugging) { DebugHelper.WriteLine("ProcessMessage: {0} {1} {2}", GetType().Name, Context.IsServer, type); } #endif var result = HandleMessage(message); switch (result) { case MessageStatus.CredentialsNeeded: status = SecurityStatus.CredentialsNeeded; return(false); case MessageStatus.Finished: hasPendingOutput = true; if (Context.IsServer) { Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer); } status = SecurityStatus.OK; return(true); case MessageStatus.IgnoreMessage: status = SecurityStatus.ContinueNeeded; return(false); case MessageStatus.Renegotiate: hasPendingOutput = true; if (message.Type != HandshakeType.HelloRequest) { Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer); } status = SecurityStatus.Renegotiate; return(true); case MessageStatus.GenerateOutput: hasPendingOutput = true; Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer); status = SecurityStatus.ContinueNeeded; return(true); case MessageStatus.ContinueNeeded: Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer); status = SecurityStatus.ContinueNeeded; return(false); default: throw new InvalidOperationException(); } }
bool ProcessHandshakeMessage (TlsBuffer incoming, out SecurityStatus status) { var handshakeType = (HandshakeType)incoming.ReadByte (); #if DEBUG_FULL if (EnableDebugging) { DebugHelper.WriteLine (">>>> Processing Handshake record ({0})", handshakeType); DebugHelper.WriteRemaining ("HANDSHAKE", incoming); } #endif // Read message length int length = incoming.ReadInt24 (); if (incoming.Remaining < length) { cachedFragment = new TlsBuffer (length + 4); cachedFragment.Position = incoming.Remaining + 4; Buffer.BlockCopy (incoming.Buffer, incoming.Position - 4, cachedFragment.Buffer, 0, cachedFragment.Position); incoming.Position += incoming.Remaining; status = SecurityStatus.ContinueNeeded; return false; } var buffer = incoming.ReadBuffer (length); return negotiationHandler.ProcessHandshakeMessage (handshakeType, buffer, out status); }
public abstract void ReadServer(TlsBuffer incoming);
SecurityStatus _DecryptMessage (ref TlsBuffer incoming) { // Try to read the Record Content Type var contentType = (ContentType)incoming.ReadByte (); #if DEBUG_FULL if (EnableDebugging) DebugHelper.WriteLine ("DecryptMessage: {0}", contentType); #endif ReadStandardBuffer (contentType, ref incoming); if (contentType == ContentType.Alert) { var level = (AlertLevel)incoming.ReadByte (); var description = (AlertDescription)incoming.ReadByte (); if (level == AlertLevel.Warning && description == AlertDescription.CloseNotify) { ReceivedCloseNotify = true; if (eventSink != null) eventSink.ReceivedCloseNotify (); return SecurityStatus.ContextExpired; } DebugHelper.WriteLine ("ALERT: {0} {1}", level, description); throw new TlsException (level, description); } else if (contentType == ContentType.ApplicationData) return SecurityStatus.OK; else if (contentType != ContentType.Handshake) throw new TlsException (AlertDescription.UnexpectedMessage, "Unknown content type {0}", contentType); try { SecurityStatus status; var finished = ProcessHandshakeMessage (incoming, out status); DebugHelper.WriteLine ("RENEGOTIATION REQUEST: {0} {1}", finished, status); return status; } finally { incoming.Dispose (); incoming = null; } }