-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
_DigestClient.cs
1275 lines (1100 loc) · 61.3 KB
/
_DigestClient.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="_DigestClient.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Security;
using System.Diagnostics;
internal class DigestClient : ISessionAuthenticationModule {
internal const string AuthType = "Digest";
internal static string Signature = AuthType.ToLower(CultureInfo.InvariantCulture);
internal static int SignatureSize = Signature.Length;
private static PrefixLookup challengeCache = new PrefixLookup();
private static readonly char[] singleSpaceArray = new char[]{' '};
// Microsoft: make sure WDigest fixes these bugs before we
// enable this code ("Windows OS" Product Studio database):
//
// 921024 1 Wdigest should support MD5, at least for explicit (non-default) credentials.
// 762116 2 WDigest should ignore directives that do not have a value
// 762115 3 WDigest should allow an application to retrieve the parsed domain directive
//
private static bool _WDigestAvailable;
static DigestClient() {
_WDigestAvailable = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, NegotiationInfoClass.WDigest)!=null;
}
public Authorization Authenticate(string challenge, WebRequest webRequest, ICredentials credentials) {
GlobalLog.Print("DigestClient::Authenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()");
return DoAuthenticate(challenge, webRequest, credentials, false);
}
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) {
GlobalLog.Print("DigestClient::DoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString());
GlobalLog.Assert(credentials != null, "DigestClient::DoAuthenticate()|credentials == null");
if (credentials==null) {
return null;
}
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "DigestClient::DoAuthenticate()|httpWebRequest == null");
GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "DigestClient::DoAuthenticate()|httpWebRequest.ChallengedUri == null");
// If it's default credentials, we support them on XP and up through WDigest.
NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, DigestClient.Signature);
GlobalLog.Print("DigestClient::DoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC));
if (NC is SystemNetworkCredential) {
if (WDigestAvailable) {
return XPDoAuthenticate(challenge, httpWebRequest, credentials, preAuthenticate);
}
else {
return null;
}
}
HttpDigestChallenge digestChallenge;
if (!preAuthenticate) {
int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature);
if (index < 0) {
return null;
}
digestChallenge = HttpDigest.Interpret(challenge, index, httpWebRequest);
}
else {
GlobalLog.Print("DigestClient::DoAuthenticate() looking up digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri);
digestChallenge = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as HttpDigestChallenge;
}
if (digestChallenge==null) {
return null;
}
bool supported = CheckQOP(digestChallenge);
if (!supported) {
if (Logging.On)
Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_digest_qop_not_supported, digestChallenge.QualityOfProtection));
return null;
}
if (preAuthenticate) {
GlobalLog.Print("DigestClient::DoAuthenticate() retrieved digestChallenge#" + ValidationHelper.HashString(digestChallenge) + " digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri);
digestChallenge = digestChallenge.CopyAndIncrementNonce();
digestChallenge.SetFromRequest(httpWebRequest);
}
if (NC==null) {
return null;
}
ICredentialPolicy policy = AuthenticationManager.CredentialPolicy;
if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this))
return null;
SpnToken spnToken = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest);
ChannelBinding binding = null;
if (httpWebRequest.CurrentAuthenticationState.TransportContext != null)
{
binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint);
}
Authorization digestResponse = HttpDigest.Authenticate(digestChallenge, NC, spnToken.Spn, binding);
if (!preAuthenticate && webRequest.PreAuthenticate && digestResponse != null) {
// add this to the cache of challenges so we can preauthenticate
string[] prefixes = digestChallenge.Domain==null ?
new string[]{httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.UriEscaped)}
: digestChallenge.Domain.Split(singleSpaceArray);
// If Domain property is not set we associate Digest only with the server Uri namespace (used to do with whole server)
digestResponse.ProtectionRealm = digestChallenge.Domain==null ? null: prefixes;
for (int i=0; i<prefixes.Length; i++) {
GlobalLog.Print("DigestClient::DoAuthenticate() adding digestChallenge#" + ValidationHelper.HashString(digestChallenge) + " for prefix:" + prefixes[i]);
challengeCache.Add(prefixes[i], digestChallenge);
}
}
return digestResponse;
}
public Authorization PreAuthenticate(WebRequest webRequest, ICredentials credentials) {
GlobalLog.Print("DigestClient::PreAuthenticate() webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()");
return DoAuthenticate(null, webRequest, credentials, true);
}
public bool CanPreAuthenticate {
get {
return true;
}
}
public string AuthenticationType {
get {
return AuthType;
}
}
internal static bool CheckQOP(HttpDigestChallenge challenge) {
// our internal implementatoin only support "auth" QualityOfProtection.
// if it's not what the server wants we'll have to throw:
// the case in which the server sends no qop directive we default to "auth"
if (challenge.QopPresent) {
int index = 0;
while (index>=0) {
// find the next occurence of "auth"
index = challenge.QualityOfProtection.IndexOf(HttpDigest.SupportedQuality, index);
if (index<0) {
return false;
}
// if it's a whole word we're done
if ((index==0 || HttpDigest.ValidSeparator.IndexOf(challenge.QualityOfProtection[index - 1])>=0) &&
(index+HttpDigest.SupportedQuality.Length==challenge.QualityOfProtection.Length || HttpDigest.ValidSeparator.IndexOf(challenge.QualityOfProtection[index + HttpDigest.SupportedQuality.Length])>=0) ) {
break;
}
index += HttpDigest.SupportedQuality.Length;
}
}
return true;
}
public bool Update(string challenge, WebRequest webRequest) {
GlobalLog.Print("DigestClient::Update(): [" + challenge + "]");
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest!=null, "DigestClient::Update()|httpWebRequest == null");
GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "DigestClient::Update()|httpWebRequest.ChallengedUri == null");
// make sure WDigest fixes these bugs before we enable this code ("Windows OS"):
// 921024 1 WDigest should support MD5, at least for explicit (non-default) credentials.
// 762116 2 WDigest should ignore directives that do not have a value
// 762115 3 WDigest should allow an application to retrieve the parsed domain directive
if (httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this) != null) {
return XPUpdate(challenge, httpWebRequest);
}
// here's how we know if the handshake is complete when we get the response back,
// (keeping in mind that we need to support stale credentials):
// !40X - complete & success
// 40X & stale=false - complete & failure
// 40X & stale=true - !complete
if (httpWebRequest.ResponseStatusCode!=httpWebRequest.CurrentAuthenticationState.StatusCodeMatch) {
GlobalLog.Print("DigestClient::Update(): no status code match. returning true");
ChannelBinding binding = null;
if (httpWebRequest.CurrentAuthenticationState.TransportContext != null)
{
binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint);
}
httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, binding);
return true;
}
int index = challenge==null ? -1 : AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature);
if (index < 0) {
GlobalLog.Print("DigestClient::Update(): no challenge. returning true");
return true;
}
int blobBegin = index + SignatureSize;
string incoming = null;
//
// there may be multiple challenges. If the next character after the
// package name is not a comma then it is challenge data
//
if (challenge.Length > blobBegin && challenge[blobBegin] != ',') {
++blobBegin;
}
else {
index = -1;
}
if (index >= 0 && challenge.Length > blobBegin) {
incoming = challenge.Substring(blobBegin);
}
HttpDigestChallenge digestChallenge = HttpDigest.Interpret(challenge, index, httpWebRequest);
if (digestChallenge==null) {
GlobalLog.Print("DigestClient::Update(): not a valid digest challenge. returning true");
return true;
}
GlobalLog.Print("DigestClient::Update(): returning digestChallenge.Stale:" + digestChallenge.Stale.ToString());
return !digestChallenge.Stale;
}
public bool CanUseDefaultCredentials {
get {
return WDigestAvailable;
}
}
internal static bool WDigestAvailable {
get {
return _WDigestAvailable;
}
}
public void ClearSession(WebRequest webRequest) {
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "NtlmClient::ClearSession()|httpWebRequest == null");
// when we're using WDigest.dll we need to keep the NTAuthentication instance around, since it's in the
// challengeCache so remove the reference in the AuthenticationState to avoid closing it in ClearSession
#if WDIGEST_PREAUTH
httpWebRequest.CurrentAuthenticationState.SetSecurityContext(null, this);
#else
httpWebRequest.CurrentAuthenticationState.ClearSession();
#endif
}
// On Windows XP and up, WDigest.dll supports the Digest authentication scheme (in addition to
// support for HTTP client sides, it also supports HTTP server side and SASL) through SSPI.
private Authorization XPDoAuthenticate(string challenge, HttpWebRequest httpWebRequest, ICredentials credentials, bool preAuthenticate) {
GlobalLog.Print("DigestClient::XPDoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] httpWebRequest#" + ValidationHelper.HashString(httpWebRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString());
NTAuthentication authSession = null;
string incoming = null;
int index;
if (!preAuthenticate) {
index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature);
if (index < 0) {
return null;
}
authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this);
GlobalLog.Print("DigestClient::XPDoAuthenticate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession));
incoming = RefineDigestChallenge(challenge, index);
}
else {
#if WDIGEST_PREAUTH
GlobalLog.Print("DigestClient::XPDoAuthenticate() looking up digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri);
authSession = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as NTAuthentication;
if (authSession==null) {
return null;
}
#else
GlobalLog.Print("DigestClient::XPDoAuthenticate() looking up digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri);
HttpDigestChallenge digestChallenge = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as HttpDigestChallenge;
if (digestChallenge==null) {
return null;
}
GlobalLog.Print("DigestClient::XPDoAuthenticate() retrieved digestChallenge#" + ValidationHelper.HashString(digestChallenge) + " digestChallenge for prefix:" + httpWebRequest.ChallengedUri.AbsoluteUri);
digestChallenge = digestChallenge.CopyAndIncrementNonce();
digestChallenge.SetFromRequest(httpWebRequest);
incoming = digestChallenge.ToBlob();
#endif
}
UriComponents uriParts = 0;
Uri remoteUri = httpWebRequest.GetRemoteResourceUri();
if (httpWebRequest.CurrentMethod.ConnectRequest) {
uriParts = UriComponents.HostAndPort;
// Use the orriginal request Uri, not the proxy Uri
remoteUri = httpWebRequest.RequestUri;
}
else {
uriParts = UriComponents.PathAndQuery;
}
// here we use Address instead of ChallengedUri. This is because the
// Digest hash is generated using the uri as it is present on the wire
string rawUri = remoteUri.GetParts(uriParts, UriFormat.UriEscaped);
GlobalLog.Print("DigestClient::XPDoAuthenticate() rawUri:" + ValidationHelper.ToString(rawUri));
if (authSession==null) {
NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature);
GlobalLog.Print("DigestClient::XPDoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC));
if (NC == null || (!(NC is SystemNetworkCredential) && NC.InternalGetUserName().Length == 0))
{
return null;
}
ICredentialPolicy policy = AuthenticationManager.CredentialPolicy;
if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this))
return null;
SpnToken spn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest);
GlobalLog.Print("NtlmClient::Authenticate() ChallengedSpn:" + ValidationHelper.ToString(spn));
ChannelBinding binding = null;
if (httpWebRequest.CurrentAuthenticationState.TransportContext != null)
{
binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint);
}
authSession =
new NTAuthentication(
NegotiationInfoClass.WDigest,
NC,
spn,
httpWebRequest,
binding);
GlobalLog.Print("DigestClient::XPDoAuthenticate() setting SecurityContext for:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " to authSession:" + ValidationHelper.HashString(authSession));
httpWebRequest.CurrentAuthenticationState.SetSecurityContext(authSession, this);
}
SecurityStatus statusCode;
string clientResponse;
GlobalLog.Print("DigestClient::XPDoAuthenticate() incoming:" + ValidationHelper.ToString(incoming));
#if WDIGEST_PREAUTH
clientResponse = authSession.GetOutgoingDigestBlob(incoming, httpWebRequest.CurrentMethod.Name, rawUri, null, preAuthenticate, true, out statusCode);
#else
clientResponse = authSession.GetOutgoingDigestBlob(incoming, httpWebRequest.CurrentMethod.Name, rawUri, null, false, false, out statusCode);
#endif
if (clientResponse == null)
return null;
GlobalLog.Print("DigestClient::XPDoAuthenticate() GetOutgoingDigestBlob(" + incoming + ") returns:" + ValidationHelper.ToString(clientResponse));
Authorization digestResponse = new Authorization(AuthType + " " + clientResponse, authSession.IsCompleted, string.Empty, authSession.IsMutualAuthFlag);
if (!preAuthenticate && httpWebRequest.PreAuthenticate) {
// add this to the cache of challenges so we can preauthenticate
// use this DCR when avaialble to do this without calling HttpDigest.Interpret():
// 762115 3 WDigest should allow an application to retrieve the parsed domain directive
HttpDigestChallenge digestChallenge = HttpDigest.Interpret(incoming, -1, httpWebRequest);
string[] prefixes = digestChallenge.Domain==null ?
new string[]{httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.UriEscaped)}
: digestChallenge.Domain.Split(singleSpaceArray);
// If Domain property is not set we associate Digest only with the server Uri namespace (used to do with whole server)
digestResponse.ProtectionRealm = digestChallenge.Domain==null ? null: prefixes;
for (int i=0; i<prefixes.Length; i++) {
GlobalLog.Print("DigestClient::XPDoAuthenticate() adding authSession#" + ValidationHelper.HashString(authSession) + " for prefix:" + prefixes[i]);
#if WDIGEST_PREAUTH
challengeCache.Add(prefixes[i], authSession);
#else
challengeCache.Add(prefixes[i], digestChallenge);
#endif
}
}
return digestResponse;
}
private bool XPUpdate(string challenge, HttpWebRequest httpWebRequest) {
GlobalLog.Print("DigestClient::XPUpdate(): " + challenge);
NTAuthentication authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this);
GlobalLog.Print("DigestClient::XPUpdate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession));
if (authSession==null) {
return false;
}
int index = challenge==null ? -1 : AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature);
if (index < 0) {
GlobalLog.Print("DigestClient::XPUpdate(): no challenge. returning true");
// Extract the CBT we used and cache it for future requests that want to do preauth
httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, authSession.ChannelBinding);
ClearSession(httpWebRequest);
return true;
}
// here's how we know if the handshake is complete when we get the response back,
// (keeping in mind that we need to support stale credentials):
// !40X - complete & success
// 40X & stale=false - complete & failure
// 40X & stale=true - !complete
if (httpWebRequest.ResponseStatusCode!=httpWebRequest.CurrentAuthenticationState.StatusCodeMatch) {
GlobalLog.Print("DigestClient::XPUpdate(): no status code match. returning true");
// Extract the CBT we used and cache it for future requests that want to do preauth
httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, authSession.ChannelBinding);
ClearSession(httpWebRequest);
return true;
}
string incoming = RefineDigestChallenge(challenge, index);
GlobalLog.Print("DigestClient::XPDoAuthenticate() incoming:" + ValidationHelper.ToString(incoming));
// we should get here only on invalid or stale credentials:
SecurityStatus statusCode;
string clientResponse = authSession.GetOutgoingDigestBlob(incoming, httpWebRequest.CurrentMethod.Name, null, null, false, true, out statusCode);
httpWebRequest.CurrentAuthenticationState.Authorization.MutuallyAuthenticated = authSession.IsMutualAuthFlag;
GlobalLog.Print("DigestClient::XPUpdate() GetOutgoingDigestBlob(" + incoming + ") returns:" + ValidationHelper.ToString(clientResponse));
GlobalLog.Assert(authSession.IsCompleted, "DigestClient::XPUpdate()|IsCompleted == false");
GlobalLog.Print("DigestClient::XPUpdate() GetOutgoingBlob() returns clientResponse:[" + ValidationHelper.ToString(clientResponse) + "] IsCompleted:" + authSession.IsCompleted.ToString());
return authSession.IsCompleted;
}
//
// Extract digest relevant part from a raw server blob
//
private static string RefineDigestChallenge(string challenge, int index)
{
string incoming = null;
Debug.Assert(challenge != null);
Debug.Assert(index >= 0 && index < challenge.Length);
int blobBegin = index + SignatureSize;
//
// there may be multiple challenges. If the next character after the
// package name is not a comma then it is challenge data
//
if (challenge.Length > blobBegin && challenge[blobBegin] != ',') {
++blobBegin;
}
else {
index = -1;
}
if (index >= 0 && challenge.Length > blobBegin) {
incoming = challenge.Substring(blobBegin);
}
else
{
Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_auth_invalid_challenge, DigestClient.AuthType));
return String.Empty; // Error, no valid digest challenge, no further processing required
}
// now make sure there's nothing at the end of the challenge that is not part of the digest challenge
// this would happen if I have a Digest challenge followed by another challenge like ",NTLM,Negotiate"
// use this DCR when avaialble to do this without parsing:
// 762116 2 WDigest should ignore directives that do not have a value
int startingPoint = 0;
int start = startingPoint;
int offset;
bool valid = true;
string name, value;
HttpDigestChallenge digestChallenge = new HttpDigestChallenge();
for (;;) {
offset = start;
index = AuthenticationManager.SplitNoQuotes(incoming, ref offset);
GlobalLog.Print("DigestClient::XPDoAuthenticate() SplitNoQuotes() returning index:" + index + " offset:" + offset);
if (offset<0) {
break;
}
name = incoming.Substring(start, offset-start);
if (index<0) {
value = HttpDigest.unquote(incoming.Substring(offset+1));
}
else {
value = HttpDigest.unquote(incoming.Substring(offset+1, index-offset-1));
}
valid = digestChallenge.defineAttribute(name, value);
GlobalLog.Print("DigestClient::XPDoAuthenticate() defineAttribute(" + name + ", " + value + ") returns " + valid);
if (index<0 || !valid) {
break;
}
start = ++index;
}
GlobalLog.Print("DigestClient::XPDoAuthenticate() start:" + start + " offset:" + offset + " index:" + index + " valid:" + valid + " incoming.Length:" + incoming.Length + " incoming:" + incoming);
if ((!valid || offset<0) && start<incoming.Length) {
incoming = start > 0 ? incoming.Substring(0, start-1) : ""; // First parameter might have been invalid, leaving start at 0
}
return incoming;
}
}
internal class HttpDigestChallenge {
// General authentication related information
internal string HostName;
internal string Realm;
internal Uri ChallengedUri;
// Digest specific fields
internal string Uri;
internal string Nonce;
internal string Opaque;
internal bool Stale;
internal string Algorithm;
internal string Method;
internal string Domain;
internal string QualityOfProtection;
internal string ClientNonce;
internal int NonceCount;
internal string Charset;
internal string ServiceName;
internal string ChannelBinding;
internal bool UTF8Charset;
internal bool QopPresent;
internal MD5CryptoServiceProvider MD5provider = new MD5CryptoServiceProvider();
internal void SetFromRequest(HttpWebRequest httpWebRequest) {
this.HostName = httpWebRequest.ChallengedUri.Host;
this.Method = httpWebRequest.CurrentMethod.Name;
if (httpWebRequest.CurrentMethod.ConnectRequest) {
// Use the orriginal request Uri, not the proxy Uri
this.Uri = httpWebRequest.RequestUri.GetParts(UriComponents.HostAndPort, UriFormat.UriEscaped);
}
else {
// Don't use PathAndQuery, it breaks IIS6
// GetParts(Path) doesn't return the initial slash
this.Uri = "/" + httpWebRequest.GetRemoteResourceUri().GetParts(UriComponents.Path,
UriFormat.UriEscaped);
}
this.ChallengedUri = httpWebRequest.ChallengedUri;
}
internal HttpDigestChallenge CopyAndIncrementNonce() {
HttpDigestChallenge challengeCopy = null;
lock(this) {
challengeCopy = this.MemberwiseClone() as HttpDigestChallenge;
++NonceCount;
}
challengeCopy.MD5provider = new MD5CryptoServiceProvider();
return challengeCopy;
}
public bool defineAttribute(string name, string value) {
name = name.Trim().ToLower(CultureInfo.InvariantCulture);
if (name.Equals(HttpDigest.DA_algorithm)) {
Algorithm = value;
}
else if (name.Equals(HttpDigest.DA_cnonce)) {
ClientNonce = value;
}
else if (name.Equals(HttpDigest.DA_nc)) {
NonceCount = Int32.Parse(value, NumberFormatInfo.InvariantInfo);
}
else if (name.Equals(HttpDigest.DA_nonce)) {
Nonce = value;
}
else if (name.Equals(HttpDigest.DA_opaque)) {
Opaque = value;
}
else if (name.Equals(HttpDigest.DA_qop)) {
QualityOfProtection = value;
QopPresent = QualityOfProtection!=null && QualityOfProtection.Length>0;
}
else if (name.Equals(HttpDigest.DA_realm)) {
Realm = value;
}
else if (name.Equals(HttpDigest.DA_domain)) {
Domain = value;
}
else if (name.Equals(HttpDigest.DA_response)) {
}
else if (name.Equals(HttpDigest.DA_stale)) {
Stale = value.ToLower(CultureInfo.InvariantCulture).Equals("true");
}
else if (name.Equals(HttpDigest.DA_uri)) {
Uri = value;
}
else if (name.Equals(HttpDigest.DA_charset)) {
Charset = value;
}
else if (name.Equals(HttpDigest.DA_cipher)) {
// ignore
}
else if (name.Equals(HttpDigest.DA_username)) {
// ignore
}
else {
//
// the token is not recognized, this usually
// happens when there are multiple challenges
//
return false;
}
return true;
}
internal string ToBlob() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_realm, Realm, true));
if (Algorithm!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_algorithm, Algorithm, true));
}
if (Charset!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_charset, Charset, false));
}
if (Nonce!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_nonce, Nonce, true));
}
if (Uri!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_uri, Uri, true));
}
if (ClientNonce!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_cnonce, ClientNonce, true));
}
if (NonceCount>0) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_nc, NonceCount.ToString("x8", NumberFormatInfo.InvariantInfo), true));
}
if (QualityOfProtection!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_qop, QualityOfProtection, true));
}
if (Opaque!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_opaque, Opaque, true));
}
if (Domain!=null) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_domain, Domain, true));
}
if (Stale) {
stringBuilder.Append(",");
stringBuilder.Append(HttpDigest.pair(HttpDigest.DA_stale, "true", true));
}
return stringBuilder.ToString();
}
}
internal static class HttpDigest {
//
// these are the tokens defined by Digest
// http://www.ietf.org/rfc/rfc2831.txt
//
internal const string DA_algorithm = "algorithm";
internal const string DA_cnonce = "cnonce"; // client-nonce
internal const string DA_domain = "domain";
internal const string DA_nc = "nc"; // nonce-count
internal const string DA_nonce = "nonce";
internal const string DA_opaque = "opaque";
internal const string DA_qop = "qop"; // quality-of-protection
internal const string DA_realm = "realm";
internal const string DA_response = "response";
internal const string DA_stale = "stale";
internal const string DA_uri = "uri";
internal const string DA_username = "username";
internal const string DA_charset = "charset";
internal const string DA_cipher = "cipher";
// directives specific to CBT. hashed-dirs contains a comma-separated list of directives
// that have been hashed into the client nonce. service-name contains the client-provided
// SPN. channel-binding contains the hex-encoded MD5 hash of the channel binding token.
internal const string DA_hasheddirs = "hashed-dirs";
internal const string DA_servicename = "service-name";
internal const string DA_channelbinding = "channel-binding";
internal const string SupportedQuality = "auth";
internal const string ValidSeparator = ", \"\'\t\r\n";
// The value of the hashed-dirs directive. It's always "service-name,channel-binding".
internal const string HashedDirs = DA_servicename + "," + DA_channelbinding;
// A server which understands CBT will send a nonce with this prefix. If we see it,
// send a response containing the CBT directives.
internal const string Upgraded = "+Upgraded+";
// When sending an upgraded response, we prefix this string to the client-nonce directive
// to let the server know.
internal const string UpgradedV1 = Upgraded + "v1";
// If the client application doesn't provide a ChannelBinding, this is what we send
// as the channel-binding directive, meaning that the client had no outer secure channel.
// See ZeroBindHash in ds/security/protocols/sspcommon/sspbindings.cxx
internal const string ZeroChannelBindingHash = "00000000000000000000000000000000";
private const string suppressExtendedProtectionKey = @"System\CurrentControlSet\Control\Lsa";
private const string suppressExtendedProtectionKeyPath = @"HKEY_LOCAL_MACHINE\" + suppressExtendedProtectionKey;
private const string suppressExtendedProtectionValueName = "SuppressExtendedProtection";
private static volatile bool suppressExtendedProtection;
static HttpDigest() {
ReadSuppressExtendedProtectionRegistryValue();
}
[RegistryPermission(SecurityAction.Assert, Read = suppressExtendedProtectionKeyPath)]
private static void ReadSuppressExtendedProtectionRegistryValue() {
// In Win7 and later, the default value for SuppressExtendedProtection is 0 (enable
// CBT support), whereas in pre-Win7 OS versions it is 1 (suppress CBT support).
suppressExtendedProtection = !ComNetOS.IsWin7orLater;
try {
using (RegistryKey lsaKey = Registry.LocalMachine.OpenSubKey(suppressExtendedProtectionKey)) {
try
{
// We only consider value 1 (2 is only used for Kerberos and 0 means CBT should
// be supported). We ignore all other values.
if (lsaKey.GetValueKind(suppressExtendedProtectionValueName) == RegistryValueKind.DWord) {
suppressExtendedProtection = ((int)lsaKey.GetValue(suppressExtendedProtectionValueName)) == 1;
}
}
catch (UnauthorizedAccessException e) {
if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message);
}
catch (IOException e) {
if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message);
}
}
}
catch (SecurityException e) {
if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message);
}
catch (ObjectDisposedException e) {
if (Logging.On) Logging.PrintWarning(Logging.Web, typeof(HttpDigest), "ReadSuppressExtendedProtectionRegistryValue", e.Message);
}
}
//
// consider internally caching the nonces sent to us by a server so that
// we can correctly send out nonce counts for subsequent requests
//
// used to create a random nonce
//
private static readonly RNGCryptoServiceProvider RandomGenerator = new RNGCryptoServiceProvider();
//
// this method parses the challenge and breaks it into the
// fundamental pieces that Digest defines and understands
//
internal static HttpDigestChallenge Interpret(string challenge, int startingPoint, HttpWebRequest httpWebRequest) {
HttpDigestChallenge digestChallenge = new HttpDigestChallenge();
digestChallenge.SetFromRequest(httpWebRequest);
//
// define the part of the challenge we really care about
//
startingPoint = startingPoint==-1 ? 0 : startingPoint + DigestClient.SignatureSize;
bool valid;
int start, offset, index;
string name, value;
// forst time parse looking for a charset="utf-8" directive
// not too bad, IIS 6.0, by default, sends this as the first directive.
// if the server does not send this we'll end up parsing twice.
start = startingPoint;
for (;;) {
offset = start;
index = AuthenticationManager.SplitNoQuotes(challenge, ref offset);
if (offset<0) {
break;
}
name = challenge.Substring(start, offset-start);
if (string.Compare(name, DA_charset, StringComparison.OrdinalIgnoreCase)==0) {
if (index<0) {
value = unquote(challenge.Substring(offset+1));
}
else {
value = unquote(challenge.Substring(offset+1, index-offset-1));
}
GlobalLog.Print("HttpDigest::Interpret() server provided a hint to use [" + value + "] encoding");
if (string.Compare(value, "utf-8", StringComparison.OrdinalIgnoreCase)==0) {
digestChallenge.UTF8Charset = true;
break;
}
}
if (index<0) {
break;
}
start = ++index;
}
// this time go through the directives, parse them and call defineAttribute()
start = startingPoint;
for (;;) {
offset = start;
index = AuthenticationManager.SplitNoQuotes(challenge, ref offset);
GlobalLog.Print("HttpDigest::Interpret() SplitNoQuotes() returning index:" + index.ToString() + " offset:" + offset.ToString());
if (offset<0) {
break;
}
name = challenge.Substring(start, offset-start);
if (index<0) {
value = unquote(challenge.Substring(offset+1));
}
else {
value = unquote(challenge.Substring(offset+1, index-offset-1));
}
if (digestChallenge.UTF8Charset) {
bool isAscii = true;
for (int i=0; i<value.Length; i++) {
if (value[i]>(char)0x7F) {
isAscii = false;
break;
}
}
if (!isAscii) {
GlobalLog.Print("HttpDigest::Interpret() UTF8 decoding required value:[" + value + "]");
byte[] bytes = new byte[value.Length];
for (int i=0; i<value.Length; i++) {
bytes[i] = (byte)value[i];
}
value = Encoding.UTF8.GetString(bytes);
GlobalLog.Print("HttpDigest::Interpret() UTF8 decoded value:[" + value + "]");
}
else {
GlobalLog.Print("HttpDigest::Interpret() no need for special encoding");
}
}
valid = digestChallenge.defineAttribute(name, value);
GlobalLog.Print("HttpDigest::Interpret() defineAttribute(" + name + ", " + value + ") returns " + valid.ToString());
if (index<0 || !valid) {
break;
}
start = ++index;
}
// We must absolutely have a nonce for Digest to work.
if (digestChallenge.Nonce == null) {
if (Logging.On)
Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_digest_requires_nonce));
return null;
}
return digestChallenge;
}
private enum Charset {
ASCII,
ANSI,
UTF8
}
private static string CharsetEncode(string rawString, Charset charset) {
#if TRAVE
GlobalLog.Print("HttpDigest::CharsetEncode() encoding rawString:[" + rawString + "] Chars(rawString):[" + Chars(rawString) + "] charset:[" + charset + "]");
#endif // #if TRAVE
if (charset==Charset.UTF8 || charset==Charset.ANSI) {
byte[] bytes = charset==Charset.UTF8 ? Encoding.UTF8.GetBytes(rawString) : Encoding.Default.GetBytes(rawString);
// the following code is the same as:
// rawString = Encoding.Default.GetString(bytes);
// but it's faster.
char[] chars = new char[bytes.Length];
bytes.CopyTo(chars, 0);
rawString = new string(chars);
}
#if TRAVE
GlobalLog.Print("HttpDigest::CharsetEncode() encoded rawString:[" + rawString + "] Chars(rawString):[" + Chars(rawString) + "] charset:[" + charset + "]");
#endif // #if TRAVE
return rawString;
}
private static Charset DetectCharset(string rawString) {
Charset charset = Charset.ASCII;
for (int i=0; i<rawString.Length; i++) {
if (rawString[i]>(char)0x7F) {
GlobalLog.Print("HttpDigest::DetectCharset() found non ASCII character:[" + ((int)rawString[i]).ToString() + "] at offset i:[" + i.ToString() + "] charset:[" + charset.ToString() + "]");
// ----, but the only way we can tell if we can use default ANSI encoding is see
// in the encode/decode process there is no loss of information.
byte[] bytes = Encoding.Default.GetBytes(rawString);
string rawCopy = Encoding.Default.GetString(bytes);
charset = string.Compare(rawString, rawCopy, StringComparison.Ordinal)==0 ? Charset.ANSI : Charset.UTF8;
break;
}
}
GlobalLog.Print("HttpDigest::DetectCharset() rawString:[" + rawString + "] has charset:[" + charset.ToString() + "]");
return charset;
}
#if TRAVE
private static string Chars(string rawString) {
string returnString = "[";
for (int i=0; i<rawString.Length; i++) {
if (i>0) {
returnString += ",";
}
returnString += ((int)rawString[i]).ToString();
}
return returnString + "]";
}
#endif // #if TRAVE
//
// CONSIDER V.NEXT
// creating a static hashtable for server nonces and keep track of nonce count
//
internal static Authorization Authenticate(HttpDigestChallenge digestChallenge, NetworkCredential NC, string spn, ChannelBinding binding) {
string username = NC.InternalGetUserName();
if (ValidationHelper.IsBlankString(username)) {
return null;
}
string password = NC.InternalGetPassword();
bool upgraded = IsUpgraded(digestChallenge.Nonce, binding);
if (upgraded)
{
digestChallenge.ServiceName = spn;
digestChallenge.ChannelBinding = hashChannelBinding(binding, digestChallenge.MD5provider);
}
if (digestChallenge.QopPresent) {
if (digestChallenge.ClientNonce==null || digestChallenge.Stale) {
GlobalLog.Print("HttpDigest::Authenticate() QopPresent:True, need new nonce. digestChallenge.ClientNonce:" + ValidationHelper.ToString(digestChallenge.ClientNonce) + " digestChallenge.Stale:" + digestChallenge.Stale.ToString());
if (upgraded)
{
digestChallenge.ClientNonce = createUpgradedNonce(digestChallenge);
}
else
{
digestChallenge.ClientNonce = createNonce(32);
}
digestChallenge.NonceCount = 1;
}
else {
GlobalLog.Print("HttpDigest::Authenticate() QopPresent:True, reusing nonce. digestChallenge.NonceCount:" + digestChallenge.NonceCount.ToString());
digestChallenge.NonceCount++;
}
}
StringBuilder authorization = new StringBuilder();
//
// look at username & password, if it's not ASCII we need to attempt some
// kind of encoding because we need to calculate the hash on byte[]
//
Charset usernameCharset = DetectCharset(username);
if (!digestChallenge.UTF8Charset && usernameCharset==Charset.UTF8) {
GlobalLog.Print("HttpDigest::Authenticate() can't authenticate with UNICODE username. failing auth.");
return null;
}
Charset passwordCharset = DetectCharset(password);
if (!digestChallenge.UTF8Charset && passwordCharset==Charset.UTF8) {
GlobalLog.Print("HttpDigest::Authenticate() can't authenticate with UNICODE password. failing auth.");
return null;
}
if (digestChallenge.UTF8Charset) {
// on the wire always use UTF8 when the server supports it
authorization.Append(pair(DA_charset, "utf-8", false));
authorization.Append(",");
if (usernameCharset==Charset.UTF8) {
username = CharsetEncode(username, Charset.UTF8);
authorization.Append(pair(DA_username, username, true));
authorization.Append(",");
}