/
AuthenticationHelper.NtAuth.cs
216 lines (190 loc) · 10.7 KB
/
AuthenticationHelper.NtAuth.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Authentication.ExtendedProtection;
namespace System.Net.Http
{
internal static partial class AuthenticationHelper
{
private const string UsePortInSpnCtxSwitch = "System.Net.Http.UsePortInSpn";
private const string UsePortInSpnEnvironmentVariable = "DOTNET_SYSTEM_NET_HTTP_USEPORTINSPN";
private static volatile int s_usePortInSpn = -1;
private static bool UsePortInSpn
{
get
{
int usePortInSpn = s_usePortInSpn;
if (usePortInSpn != -1)
{
return usePortInSpn != 0;
}
// First check for the AppContext switch, giving it priority over the environment variable.
if (AppContext.TryGetSwitch(UsePortInSpnCtxSwitch, out bool value))
{
s_usePortInSpn = value ? 1 : 0;
}
else
{
// AppContext switch wasn't used. Check the environment variable.
s_usePortInSpn =
Environment.GetEnvironmentVariable(UsePortInSpnEnvironmentVariable) is string envVar &&
(envVar == "1" || envVar.Equals("true", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
}
return s_usePortInSpn != 0;
}
}
private static Task<HttpResponseMessage> InnerSendAsync(HttpRequestMessage request, bool async, bool isProxyAuth, HttpConnectionPool pool, HttpConnection connection, CancellationToken cancellationToken)
{
return isProxyAuth ?
connection.SendAsyncCore(request, async, cancellationToken) :
pool.SendWithNtProxyAuthAsync(connection, request, async, cancellationToken);
}
private static bool ProxySupportsConnectionAuth(HttpResponseMessage response)
{
if (!response.Headers.TryGetValues(KnownHeaders.ProxySupport.Descriptor, out IEnumerable<string>? values))
{
return false;
}
foreach (string v in values)
{
if (v == "Session-Based-Authentication")
{
return true;
}
}
return false;
}
private static async Task<HttpResponseMessage> SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, bool async, ICredentials credentials, bool isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
{
HttpResponseMessage response = await InnerSendAsync(request, async, isProxyAuth, connectionPool, connection, cancellationToken).ConfigureAwait(false);
if (!isProxyAuth && connection.Kind == HttpConnectionKind.Proxy && !ProxySupportsConnectionAuth(response))
{
// Proxy didn't indicate that it supports connection-based auth, so we can't proceed.
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Error(connection, $"Proxy doesn't support connection-based auth, uri={authUri}");
}
return response;
}
if (TryGetAuthenticationChallenge(response, isProxyAuth, authUri, credentials, out AuthenticationChallenge challenge))
{
if (challenge.AuthenticationType == AuthenticationType.Negotiate ||
challenge.AuthenticationType == AuthenticationType.Ntlm)
{
bool isNewConnection = false;
bool needDrain = true;
try
{
if (response.Headers.ConnectionClose.GetValueOrDefault())
{
// Server is closing the connection and asking us to authenticate on a new connection.
// First, detach the current connection from the pool. This means it will no longer count against the connection limit.
// Instead, it will be replaced by the new connection below.
connection.DetachFromPool();
connection = await connectionPool.CreateHttp11ConnectionAsync(request, async, cancellationToken).ConfigureAwait(false);
connection!.Acquire();
isNewConnection = true;
needDrain = false;
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(connection, $"Authentication: {challenge.AuthenticationType}, Uri: {authUri.AbsoluteUri}");
}
// Calculate SPN (Service Principal Name) using the host name of the request.
// Use the request's 'Host' header if available. Otherwise, use the request uri.
// Ignore the 'Host' header if this is proxy authentication since we need to use
// the host name of the proxy itself for SPN calculation.
string hostName;
if (!isProxyAuth && request.HasHeaders && request.Headers.Host != null)
{
// Use the host name without any normalization.
hostName = request.Headers.Host;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(connection, $"Authentication: {challenge.AuthenticationType}, Host: {hostName}");
}
}
else
{
// Need to use FQDN normalized host so that CNAME's are traversed.
// Use DNS to do the forward lookup to an A (host) record.
// But skip DNS lookup on IP literals. Otherwise, we would end up
// doing an unintended reverse DNS lookup.
UriHostNameType hnt = authUri.HostNameType;
if (hnt == UriHostNameType.IPv6 || hnt == UriHostNameType.IPv4)
{
hostName = authUri.IdnHost;
}
else
{
IPHostEntry result = await Dns.GetHostEntryAsync(authUri.IdnHost, cancellationToken).ConfigureAwait(false);
hostName = result.HostName;
}
if (!isProxyAuth && !authUri.IsDefaultPort && UsePortInSpn)
{
hostName = string.Create(null, stackalloc char[128], $"{hostName}:{authUri.Port}");
}
}
string spn = "HTTP/" + hostName;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(connection, $"Authentication: {challenge.AuthenticationType}, SPN: {spn}");
}
ChannelBinding? channelBinding = connection.TransportContext?.GetChannelBinding(ChannelBindingKind.Endpoint);
NTAuthentication authContext = new NTAuthentication(isServer: false, challenge.SchemeName, challenge.Credential, spn, ContextFlagsPal.Connection | ContextFlagsPal.InitIntegrity, channelBinding);
string? challengeData = challenge.ChallengeData;
try
{
while (true)
{
string? challengeResponse = authContext.GetOutgoingBlob(challengeData);
if (challengeResponse == null)
{
// Response indicated denial even after login, so stop processing and return current response.
break;
}
if (needDrain)
{
await connection.DrainResponseAsync(response!, cancellationToken).ConfigureAwait(false);
}
SetRequestAuthenticationHeaderValue(request, new AuthenticationHeaderValue(challenge.SchemeName, challengeResponse), isProxyAuth);
response = await InnerSendAsync(request, async, isProxyAuth, connectionPool, connection, cancellationToken).ConfigureAwait(false);
if (authContext.IsCompleted || !TryGetRepeatedChallenge(response, challenge.SchemeName, isProxyAuth, out challengeData))
{
break;
}
needDrain = true;
}
}
finally
{
authContext.CloseContext();
}
}
finally
{
if (isNewConnection)
{
connection!.Release();
}
}
}
}
return response!;
}
public static Task<HttpResponseMessage> SendWithNtProxyAuthAsync(HttpRequestMessage request, Uri proxyUri, bool async, ICredentials proxyCredentials, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
{
return SendWithNtAuthAsync(request, proxyUri, async, proxyCredentials, isProxyAuth: true, connection, connectionPool, cancellationToken);
}
public static Task<HttpResponseMessage> SendWithNtConnectionAuthAsync(HttpRequestMessage request, bool async, ICredentials credentials, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
{
Debug.Assert(request.RequestUri != null);
return SendWithNtAuthAsync(request, request.RequestUri, async, credentials, isProxyAuth: false, connection, connectionPool, cancellationToken);
}
}
}