Issue authenticating with Exchange Server via NTLM
Everything seems to be in order. The challenge is processed, the account details are copied into the token and sent to the server, but the server's logs indicate that the username is blank.
I am using it in a .NET Core application, but the issue also happens in a 4.6.1 application.
This indicates to me that it could be an encoding issue, or the token generation isn't quite right (the server is looking for the username in a different part of the token).
I am slightly confused as to why the Type3Message Encodes the domain and user as UTF-16 (because of NtlmFlags.NegotiateUnicode) and converts the response to a Base64 string, only to then be encoded for the SmtpStream with UTF8 in the SmtpClient's SendCommand method. I have tried some variations, with no luck.
The Type3Message encoding offsets and lengths all appear to be appropriate. I have run the encoded bytes through its own decode mechanism, and each component is successfully extracted, so there isn't a different expectation of those bytes. I have run the result of the SendCommand's resulting bytes through, and it (of course) is not a valid Type3Message, but that may not be relevant.
As I said, it all LOOKS fine on the client end, but I don't know enough about the NTLM tokens to identify an issue in its structure.
I have included the below, so you can see that NTLM is supported, and the back and forth is happening. I can provide the final client token response from the log privately if required.
Connected to smtp://servername:25/ S: 220 servername Microsoft ESMTP MAIL Service ready at Wed, 14 Sep 2016 10:33:46 +0100 C: EHLO [myipaddress] S: 250-servername Hello [serveripaddress] S: 250-SIZE 31457280 S: 250-PIPELINING S: 250-DSN S: 250-ENHANCEDSTATUSCODES S: 250-AUTH NTLM S: 250-8BITMIME S: 250-BINARYMIME S: 250 CHUNKING C: AUTH NTLM TOKENWITHNOTMUCHINIT S: 334 TOKENWITHNONCEANDTARGETNAMEANDTARGETINFO C: TOKENRESPONSE S: 535 5.7.3 Authentication unsuccessful
I am slightly confused as to why the Type3Message Encodes the domain and user as UTF-16 (because of NtlmFlags.NegotiateUnicode) and converts the response to a Base64 string, only to then be encoded for the SmtpStream with UTF8 in the SmtpClient's SendCommand method. I have tried some variations, with no luck.
The Type3Message uses the NtlmFlags to determine which encoding to use for the username/password. If the server wants NtlmFlags.NegotiateUnicode, then it wants UTF-16LE, otherwise it wants OEM strings which are UTF-8 (well, ASCII, but UTF-8 is used in case the username/password contain non-ASCII characters in the hopes that UTF-8 will work because ASCII for sure won't).
SASL requires that tokens be base64 encoded, which is why the resulting token (remember: NTLM constructs a binary blob for its token) is encoded in base64.
The SmtpClient's SendCommand() method encodes the base64 token in UTF-8 (base64 is ASCII, so nothing changes) because it needs to convert strings into byte arrays to send over the TCP network stream and UTF-8 is the best choice to use here because either the SMTP server supports the SMTPUTF8 extension (which means it wants UTF-8) or it doesn't (which means it only accepts ASCII).
The username and password strings themselves are not ever getting re-encoded through this process.
The challenge is processed, the account details are copied into the token and sent to the server, but the server's logs indicate that the username is blank.
This may or may not indicate that the username was incorrectly encoded, but I would agree with your instincts that it is at least worth checking that the username is being encoded correctly.
Since UTF-16LE encodes ASCII usernames in such a way that each ASCII char is encoded into 2 bytes, the first of which is always 0 (aka null terminator for most string encodings), it sounds reasonable that this might be the case.
If you can start with getting me the token sent by the server, I could parse it in the debugger locally to see what flags are set and maybe it has both the UNICODE and OEM flags set? If so... maybe I can have it use OEM instead?
Or if you could test that locally, that'd be good.
The token from the server only has NegotiateUnicode. The full set of flags is:
NegotiateUnicode | RequestTarget | NegotiateNtlm | TargetTypeDomain | NegotiateNtlm2Key | NegotiateTargetInfo | NegotiateVersion
Target name and target info are successfully extracted from the token.
I have tested by using UTF8 in the Type2 and Type3 messages where it checks the flags, with the same result.
Because of line 102 in Type2: (Flags & NtlmFlags.NegotiateOem) != 0, it will use UTF8, even if both flags are set. Type3 does use UTF-16 by default instead. My testing was to hardcode UTF8.
Worth noting that it is a slightly old Exchange Server, so I also tested by skipping the use of the Type2Message in the encoding of the Type3 message to use the legacy ChallengeResponse, but that also had the same result, but I realise of course, that the flag identifying Ntlm2Key indicates it should be fine with v2.
I will try v2 only without a session.
Update (while trying v2Only):
There is a bug in HMACMD5 also. The Dispose(disposing) method sets the Key to null, which throws an ArgumentNullException. This is triggered from the 'using' statement on line 158 of ChallengeResponse2.
Changing NtlmSettings from
static NtlmAuthLevel defaultAuthLevel = NtlmAuthLevel.LM_and_NTLM_and_try_NTLMv2_Session;
to
static NtlmAuthLevel defaultAuthLevel = NtlmAuthLevel.NTLMv2_only;
I needed to change the HMACMD5 class Key property to:
public byte[] Key
{
get { return key; }
set
{
//if (value == null)
// throw new ArgumentNullException("value");
if (key != null)
Array.Clear (key, 0, key.Length);
key = value;
if (value == null)
return;
Initialize ();
}
}
This has worked. I have broken a couple of other things in the code, but I can create a pull request to resolve the HMACMD5 bug (after some more testing of course!), or feel free to make the updates yourself.
The question is what the difference is between NtlmAuthLevel.NTLMv2_only and NtlmAuthLevel.LM_and_NTLM_and_try_NTLMv2_Session?
I mean, the enum name makes it sound obvious, but it generates the NTLM hash differently, the latter uses the challenge nonce, but to get to that point, the server must support that initial response, so a response from the server has suggested that it can use that challenge nonce?
Edit:
Have talked to the one of the infrastructure team here, and it could well be that Exchange 2008 just doesn't support the session negotiation. I also see that the NTLM mechanism by default has the SupportsInitialResponse property set to true by default, so no review of server capability. Not sure how you would though, as the EHLO response doesn't seem to indicate a difference, just NTLM auth capability.
I've just fixed the HMACMD5 bug (I made Dispose() set the backing field to null instead of using the property).
That leaves the NtlmAuthLevel issue and for that I'm going to need to research that question a bit because I am no expert in NTLM either :(
After doing a bit of reading up on NTLM again, I wonder if the problem is that the client's initial Type1Message does not contain the NtlmFlags.NegotiateNtlm2Key which means that the server thinks we do not support it, but then later in our Type3Message we are in fact using it.
So the correct solution here might be to default to NTLMv2_only as you've discovered works. Either that or specify in our Type1Message that we support NegotiateNtlm2Key.
Since you've already discovered that using NTLMv2_only works, can you test my idea about initializing Type1Message.Flags to include NegotiateNtlm2Key and seeing if that works?
I'm also kind of wondering if maybe NtlmAuthLevel should have some different options... like I'm thinking that it might be best to try for NTLMv2 first, and then fall back to NTLM2 Session and then falling back to LM and NTLM or something...
Looks like SaslMechanismNtlm.GetInitialResponse() adds NtlmFlags.NegotiateNtlm2Key to the flags, so it doesn't look like adding that flag in the Type1Message .ctor would help.
I've decided to opt for just using NTLMv2. My understanding is that it's more secure than what the code was using before (NTLM2 Session Key w/ fallback to LM & NTLM).
A few people have recently reported having this same problem on stackoverflow.com. Could you verify that this is fixed for you in git master?
I'd like to make a nuget release this weekend to solve this problem if I can but I don't want to say "NTLM is fixed!" and then have it turn out that it's not...