Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/8.0] Fix NegotiateStream connections between Linux clients and Windows servers #102216

Merged
merged 4 commits into from
Jun 7, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/libraries/Common/tests/System/Net/Security/FakeNtlmServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public FakeNtlmServer(NetworkCredential expectedCredential)
public bool IsAuthenticated { get; private set; }
public bool IsMICPresent { get; private set; }
public string? ClientSpecifiedSpn { get; private set; }
public Flags InitialClientFlags { get; private set; }
public Flags NegotiatedFlags => _negotiatedFlags;

private NetworkCredential _expectedCredential;

Expand Down Expand Up @@ -83,7 +85,7 @@ private enum MessageType : uint
}

[Flags]
private enum Flags : uint
public enum Flags : uint
{
NegotiateUnicode = 0x00000001,
NegotiateOEM = 0x00000002,
Expand Down Expand Up @@ -177,17 +179,17 @@ private static ReadOnlySpan<byte> GetField(ReadOnlySpan<byte> payload, int field
case MessageType.Negotiate:
// We don't negotiate, we just verify
Assert.True(incomingBlob.Length >= 32);
Flags flags = (Flags)BinaryPrimitives.ReadUInt32LittleEndian(incomingBlob.AsSpan(12, 4));
Assert.Equal(_requiredFlags, (flags & _requiredFlags));
Assert.True((flags & (Flags.NegotiateOEM | Flags.NegotiateUnicode)) != 0);
if (flags.HasFlag(Flags.NegotiateDomainSupplied))
InitialClientFlags = (Flags)BinaryPrimitives.ReadUInt32LittleEndian(incomingBlob.AsSpan(12, 4));
Assert.Equal(_requiredFlags, (InitialClientFlags & _requiredFlags));
Assert.True((InitialClientFlags & (Flags.NegotiateOEM | Flags.NegotiateUnicode)) != 0);
if (InitialClientFlags.HasFlag(Flags.NegotiateDomainSupplied))
{
string domain = Encoding.ASCII.GetString(GetField(incomingBlob, 16));
Assert.Equal(_expectedCredential.Domain, domain);
}
_expectedMessageType = MessageType.Authenticate;
_negotiateMessage = incomingBlob;
return _challengeMessage = GenerateChallenge(flags);
return _challengeMessage = GenerateChallenge(InitialClientFlags);

case MessageType.Authenticate:
// Validate the authentication!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,14 @@ public override void Dispose()
{
Debug.Assert(incomingBlob.IsEmpty);

Flags requiredFlags = s_requiredFlags;
if (_protectionLevel == ProtectionLevel.EncryptAndSign)
{
requiredFlags |= Flags.NegotiateSeal;
}

_negotiateMessage = new byte[sizeof(NegotiateMessage)];
CreateNtlmNegotiateMessage(_negotiateMessage);
CreateNtlmNegotiateMessage(_negotiateMessage, requiredFlags);

outgoingBlob = _negotiateMessage;
statusCode = NegotiateAuthenticationStatusCode.ContinueNeeded;
Expand All @@ -278,7 +284,7 @@ public override void Dispose()
return outgoingBlob;
}

private static unsafe void CreateNtlmNegotiateMessage(Span<byte> asBytes)
private static unsafe void CreateNtlmNegotiateMessage(Span<byte> asBytes, Flags requiredFlags)
{
Debug.Assert(HeaderLength == NtlmHeader.Length);
Debug.Assert(asBytes.Length == sizeof(NegotiateMessage));
Expand All @@ -288,7 +294,7 @@ private static unsafe void CreateNtlmNegotiateMessage(Span<byte> asBytes)
asBytes.Clear();
NtlmHeader.CopyTo(asBytes);
message.Header.MessageType = MessageType.Negotiate;
message.Flags = s_requiredFlags;
message.Flags = requiredFlags;
message.Version = s_version;
}

Expand Down Expand Up @@ -560,6 +566,13 @@ private static byte[] DeriveKey(ReadOnlySpan<byte> exportedSessionKey, ReadOnlyS
return null;
}

// We already negotiate signing, so we only need to check sealing/encryption.
if ((flags & Flags.NegotiateSeal) == 0 && _protectionLevel == ProtectionLevel.EncryptAndSign)
{
statusCode = NegotiateAuthenticationStatusCode.QopNotSupported;
return null;
}

ReadOnlySpan<byte> targetInfo = GetField(challengeMessage.TargetInfo, blob);
byte[] targetInfoBuffer = ProcessTargetInfo(targetInfo, out DateTime time, out bool hasNbNames);

Expand Down Expand Up @@ -594,7 +607,7 @@ private static byte[] DeriveKey(ReadOnlySpan<byte> exportedSessionKey, ReadOnlyS
NtlmHeader.CopyTo(responseAsSpan);

response.Header.MessageType = MessageType.Authenticate;
response.Flags = s_requiredFlags;
response.Flags = s_requiredFlags | (flags & Flags.NegotiateSeal);
response.Version = s_version;

// Calculate hash for hmac - same for lm2 and ntlm2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -883,7 +883,16 @@ private async Task ReceiveBlobAsync<TIOAdapter>(CancellationToken cancellationTo

if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeDoneId)
{
_remoteOk = true;
if (HandshakeComplete && message.Length > 0)
{
Debug.Assert(_context != null);
_context.GetOutgoingBlob(message, out NegotiateAuthenticationStatusCode statusCode);
_remoteOk = statusCode is NegotiateAuthenticationStatusCode.Completed;
}
else
{
_remoteOk = true;
}
}
else if (_framer.ReadHeader.MessageId != FrameHeader.HandshakeId)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Buffers;
using System.Buffers.Binary;
using System.IO;
Expand Down Expand Up @@ -148,10 +149,18 @@ public void NtlmProtocolExampleTest()
Assert.False(fakeNtlmServer.IsMICPresent);
}

[ConditionalFact(nameof(IsNtlmAvailable))]
public void NtlmCorrectExchangeTest()
public static IEnumerable<object[]> TestCredentials()
{
using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
yield return new object[] { new NetworkCredential("rightusername", "rightpassword") };
yield return new object[] { new NetworkCredential("rightusername", "rightpassword", "rightdomain") };
yield return new object[] { new NetworkCredential("rightusername@rightdomain.com", "rightpassword") };
}

[ConditionalTheory(nameof(IsNtlmAvailable))]
[MemberData(nameof(TestCredentials))]
public void NtlmCorrectExchangeTest(NetworkCredential credential)
{
using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(credential);
NegotiateAuthentication ntAuth = new NegotiateAuthentication(
new NegotiateAuthenticationClientOptions
{
Expand Down Expand Up @@ -190,6 +199,42 @@ public void NtlmIncorrectExchangeTest()
Assert.False(fakeNtlmServer.IsAuthenticated);
}

[ConditionalFact(nameof(IsNtlmAvailable))]
public void NtlmEncryptionTest()
{
using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);

NegotiateAuthentication ntAuth = new NegotiateAuthentication(
new NegotiateAuthenticationClientOptions
{
Package = "NTLM",
Credential = s_testCredentialRight,
TargetName = "HTTP/foo",
RequiredProtectionLevel = ProtectionLevel.EncryptAndSign
});

NegotiateAuthenticationStatusCode statusCode;
byte[]? negotiateBlob = ntAuth.GetOutgoingBlob((byte[])null, out statusCode);
Assert.Equal(NegotiateAuthenticationStatusCode.ContinueNeeded, statusCode);
Assert.NotNull(negotiateBlob);

byte[]? challengeBlob = fakeNtlmServer.GetOutgoingBlob(negotiateBlob);
Assert.NotNull(challengeBlob);
// Validate that the client sent NegotiateSeal flag
Assert.Equal(FakeNtlmServer.Flags.NegotiateSeal, (fakeNtlmServer.InitialClientFlags & FakeNtlmServer.Flags.NegotiateSeal));

byte[]? authenticateBlob = ntAuth.GetOutgoingBlob(challengeBlob, out statusCode);
Assert.Equal(NegotiateAuthenticationStatusCode.Completed, statusCode);
Assert.NotNull(authenticateBlob);

byte[]? empty = fakeNtlmServer.GetOutgoingBlob(authenticateBlob);
Assert.Null(empty);
Assert.True(fakeNtlmServer.IsAuthenticated);

// Validate that the NegotiateSeal flag survived the full exchange
Assert.Equal(FakeNtlmServer.Flags.NegotiateSeal, (fakeNtlmServer.NegotiatedFlags & FakeNtlmServer.Flags.NegotiateSeal));
}

[ConditionalFact(nameof(IsNtlmAvailable))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65678", TestPlatforms.OSX | TestPlatforms.iOS | TestPlatforms.MacCatalyst)]
public void NtlmSignatureTest()
Expand Down Expand Up @@ -218,7 +263,7 @@ public void NtlmSignatureTest()
fakeNtlmServer.Unwrap(output.WrittenSpan, temp);
Assert.Equal(s_Hello, temp);

// Test creating signature on server side and decoding it with VerifySignature on client side
// Test creating signature on server side and decoding it with VerifySignature on client side
byte[] serverSignedMessage = new byte[16 + s_Hello.Length];
fakeNtlmServer.Wrap(s_Hello, serverSignedMessage);
output.Clear();
Expand Down
Loading