-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
GssapiAuthenticator.cs
431 lines (380 loc) · 16.4 KB
/
GssapiAuthenticator.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Driver.Core.Connections;
using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver.Core.Authentication
{
/// <summary>
/// A GSSAPI SASL authenticator.
/// </summary>
public sealed class GssapiAuthenticator : SaslAuthenticator
{
// constants
/// <summary>
/// The name of the mechanism.
/// </summary>
public const string MechanismName = "GSSAPI";
/// <summary>
/// The default service name.
/// </summary>
public const string DefaultServiceName = "mongodb";
private const string __canonicalizeHostNamePropertyName = "CANONICALIZE_HOST_NAME";
private const string __realmPropertyName = "REALM";
private const string __serviceNamePropertyName = "SERVICE_NAME";
private const string __serviceRealmPropertyName = "SERVICE_REALM";
// static properties
/// <summary>
/// Gets the name of the canonicalize host name property.
/// </summary>
/// <value>
/// The name of the canonicalize host name property.
/// </value>
public static string CanonicalizeHostNamePropertyName
{
get { return __canonicalizeHostNamePropertyName; }
}
/// <summary>
/// Gets the name of the realm property.
/// </summary>
/// <value>
/// The name of the realm property.
/// </value>
[Obsolete("Use ServiceRealmPropertyName")]
public static string RealmPropertyName
{
get { return __realmPropertyName; }
}
/// <summary>
/// Gets the name of the service name property.
/// </summary>
/// <value>
/// The name of the service name property.
/// </value>
public static string ServiceNamePropertyName
{
get { return __serviceNamePropertyName; }
}
/// <summary>
/// Gets the name of the service realm property.
/// </summary>
/// <value>
/// The name of the service realm property.
/// </value>
public static string ServiceRealmPropertyName
{
get { return __serviceRealmPropertyName; }
}
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="GssapiAuthenticator"/> class.
/// </summary>
/// <param name="credential">The credential.</param>
/// <param name="properties">The properties.</param>
[Obsolete("Use the newest overload instead.")]
public GssapiAuthenticator(UsernamePasswordCredential credential, IEnumerable<KeyValuePair<string, string>> properties)
: this(credential, properties, serverApi: null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GssapiAuthenticator"/> class.
/// </summary>
/// <param name="credential">The credential.</param>
/// <param name="properties">The properties.</param>
/// <param name="serverApi">The server API.</param>
public GssapiAuthenticator(
UsernamePasswordCredential credential,
IEnumerable<KeyValuePair<string, string>> properties,
ServerApi serverApi)
: base(CreateMechanism(credential, properties), serverApi)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GssapiAuthenticator"/> class.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="properties">The properties.</param>
[Obsolete("Use the newest overload instead.")]
public GssapiAuthenticator(string username, IEnumerable<KeyValuePair<string, string>> properties)
: this(username, properties, serverApi: null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GssapiAuthenticator"/> class.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="properties">The properties.</param>
/// <param name="serverApi">The server API.</param>
public GssapiAuthenticator(
string username,
IEnumerable<KeyValuePair<string, string>> properties,
ServerApi serverApi)
: base(CreateMechanism(username, null, properties), serverApi)
{
}
/// <inheritdoc/>
public override string DatabaseName
{
get { return "$external"; }
}
private static GssapiMechanism CreateMechanism(UsernamePasswordCredential credential, IEnumerable<KeyValuePair<string, string>> properties)
{
if (credential.Source != "$external")
{
throw new ArgumentException("GSSAPI authentication may only use the $external source.", "credential");
}
return CreateMechanism(credential.Username, credential.Password, properties);
}
private static GssapiMechanism CreateMechanism(string username, SecureString password, IEnumerable<KeyValuePair<string, string>> properties)
{
var serviceName = DefaultServiceName;
var canonicalizeHostName = false;
string realm = null;
if (properties != null)
{
foreach (var pair in properties)
{
switch (pair.Key.ToUpperInvariant())
{
case __serviceNamePropertyName:
serviceName = (string)pair.Value;
break;
case __serviceRealmPropertyName:
case __realmPropertyName:
realm = (string)pair.Value;
break;
case __canonicalizeHostNamePropertyName:
canonicalizeHostName = bool.Parse(pair.Value);
break;
default:
var message = string.Format("Unknown GSSAPI property '{0}'.", pair.Key);
throw new ArgumentException(message, "properties");
}
}
}
return new GssapiMechanism(serviceName, canonicalizeHostName, realm, username, password);
}
// nested classes
private class GssapiMechanism : ISaslMechanism
{
// fields
private readonly bool _canonicalizeHostName;
private readonly SecureString _password;
private readonly string _realm;
private readonly string _serviceName;
private readonly string _username;
public GssapiMechanism(string serviceName, bool canonicalizeHostName, string realm, string username, SecureString password)
{
_serviceName = serviceName;
_canonicalizeHostName = canonicalizeHostName;
_realm = realm;
_username = Ensure.IsNotNullOrEmpty(username, nameof(username));
_password = password;
}
public string Name
{
get { return MechanismName; }
}
public ISaslStep Initialize(
IConnection connection,
SaslConversation conversation,
ConnectionDescription description,
CancellationToken cancellationToken)
{
Ensure.IsNotNull(connection, nameof(connection));
Ensure.IsNotNull(description, nameof(description));
var hostName = connection.EndPoint.GetHostAndPort().Host;
if (string.IsNullOrEmpty(hostName))
{
throw new MongoAuthenticationException(connection.ConnectionId, "Only DnsEndPoint and IPEndPoint are supported for GSSAPI authentication.");
}
if (_canonicalizeHostName)
{
var entry = Dns.GetHostEntry(hostName);
if (entry != null)
{
hostName = entry.HostName;
}
}
return new FirstStep(_serviceName, hostName, _realm, _username, _password, conversation);
}
public Task<ISaslStep> InitializeAsync(
IConnection connection,
SaslConversation conversation,
ConnectionDescription description,
CancellationToken cancellationToken)
=> Task.FromResult(Initialize(connection, conversation, description, cancellationToken));
}
private class FirstStep : ISaslStep
{
private readonly string _authorizationId;
private readonly byte[] _bytesToSendToServer;
private readonly ISecurityContext _context;
public FirstStep(string serviceName, string hostname, string realm, string username, SecureString password, SaslConversation conversation)
{
_authorizationId = username;
try
{
_context = SecurityContextFactory.InitializeSecurityContext(serviceName, hostname, realm, _authorizationId, password);
conversation.RegisterItemForDisposal(_context);
_bytesToSendToServer = _context.Next(null);
}
catch (GssapiException ex)
{
if (password != null)
{
throw new MongoAuthenticationException(conversation.ConnectionId, "Unable to initialize security context. Ensure the username and password are correct.", ex);
}
else
{
throw new MongoAuthenticationException(conversation.ConnectionId, "Unable to initialize security context.", ex);
}
}
}
public byte[] BytesToSendToServer
{
get { return _bytesToSendToServer; }
}
public bool IsComplete
{
get { return false; }
}
public ISaslStep Transition(SaslConversation conversation, byte[] bytesReceivedFromServer)
{
byte[] bytesToSendToServer;
try
{
bytesToSendToServer = _context.Next(bytesReceivedFromServer);
}
catch (GssapiException ex)
{
throw new MongoAuthenticationException(conversation.ConnectionId, "Unable to initialize security context", ex);
}
if (!_context.IsInitialized)
{
return new InitializeStep(_authorizationId, _context, bytesToSendToServer);
}
return new NegotiateStep(_authorizationId, _context, bytesToSendToServer);
}
public Task<ISaslStep> TransitionAsync(SaslConversation conversation, byte[] bytesReceivedFromServer, CancellationToken cancellationToken)
=> Task.FromResult(Transition(conversation, bytesReceivedFromServer));
}
private class InitializeStep : ISaslStep
{
private readonly string _authorizationId;
private readonly ISecurityContext _context;
private readonly byte[] _bytesToSendToServer;
public InitializeStep(string authorizationId, ISecurityContext context, byte[] bytesToSendToServer)
{
_authorizationId = authorizationId;
_context = context;
_bytesToSendToServer = bytesToSendToServer ?? new byte[0];
}
public byte[] BytesToSendToServer
{
get { return _bytesToSendToServer; }
}
public bool IsComplete
{
get { return false; }
}
public ISaslStep Transition(SaslConversation conversation, byte[] bytesReceivedFromServer)
{
byte[] bytesToSendToServer;
try
{
bytesToSendToServer = _context.Next(bytesReceivedFromServer);
}
catch (GssapiException ex)
{
throw new MongoAuthenticationException(conversation.ConnectionId, "Unable to initialize security context", ex);
}
if (!_context.IsInitialized)
{
return new InitializeStep(_authorizationId, _context, bytesToSendToServer);
}
return new NegotiateStep(_authorizationId, _context, bytesToSendToServer);
}
public Task<ISaslStep> TransitionAsync(SaslConversation conversation, byte[] bytesReceivedFromServer, CancellationToken cancellationToken)
=> Task.FromResult(Transition(conversation, bytesReceivedFromServer));
}
private class NegotiateStep : ISaslStep
{
private readonly string _authorizationId;
private readonly ISecurityContext _context;
private readonly byte[] _bytesToSendToServer;
public NegotiateStep(string authorizationId, ISecurityContext context, byte[] bytesToSendToServer)
{
_authorizationId = authorizationId;
_context = context;
_bytesToSendToServer = bytesToSendToServer ?? new byte[0];
}
public byte[] BytesToSendToServer
{
get { return _bytesToSendToServer; }
}
public bool IsComplete
{
get { return false; }
}
public ISaslStep Transition(SaslConversation conversation, byte[] bytesReceivedFromServer)
{
try
{
// NOTE: We simply check whether we can successfully decrypt the message,
// but don't do anything with the decrypted plaintext
_ = _context.DecryptMessage(0, bytesReceivedFromServer);
}
catch (GssapiException ex)
{
throw new MongoAuthenticationException(conversation.ConnectionId, "Unable to decrypt message.", ex);
}
int length = 4;
if (_authorizationId != null)
{
length += _authorizationId.Length;
}
bytesReceivedFromServer = new byte[length];
bytesReceivedFromServer[0] = 0x1; // NO_PROTECTION
bytesReceivedFromServer[1] = 0x0; // NO_PROTECTION
bytesReceivedFromServer[2] = 0x0; // NO_PROTECTION
bytesReceivedFromServer[3] = 0x0; // NO_PROTECTION
if (_authorizationId != null)
{
var authorizationIdBytes = Encoding.UTF8.GetBytes(_authorizationId);
authorizationIdBytes.CopyTo(bytesReceivedFromServer, 4);
}
byte[] bytesToSendToServer;
try
{
bytesToSendToServer = _context.EncryptMessage(bytesReceivedFromServer);
}
catch (GssapiException ex)
{
throw new MongoAuthenticationException(conversation.ConnectionId, "Unable to encrypt message.", ex);
}
return new CompletedStep(bytesToSendToServer);
}
public Task<ISaslStep> TransitionAsync(SaslConversation conversation, byte[] bytesReceivedFromServer, CancellationToken cancellationToken)
=> Task.FromResult(Transition(conversation, bytesReceivedFromServer));
}
}
}