File: HttpsChannelFactory.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (559 lines) | stat: -rw-r--r-- 23,244 bytes parent folder | download
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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
    using System.Collections.ObjectModel;
    using System.IdentityModel.Claims;
    using System.IdentityModel.Policy;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.Net;
    using System.Net.Security;
    using System.Runtime;
    using System.Runtime.CompilerServices;
    using System.Security.Cryptography.X509Certificates;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using System.ServiceModel.Security;
    using System.ServiceModel.Security.Tokens;

    class HttpsChannelFactory<TChannel> : HttpChannelFactory<TChannel>
    {
        bool requireClientCertificate;
        IChannelBindingProvider channelBindingProvider;
        RemoteCertificateValidationCallback remoteCertificateValidationCallback;
        X509CertificateValidator sslCertificateValidator;

        internal HttpsChannelFactory(HttpsTransportBindingElement httpsBindingElement, BindingContext context)
            : base(httpsBindingElement, context)
        {
            this.requireClientCertificate = httpsBindingElement.RequireClientCertificate;
            this.channelBindingProvider = new ChannelBindingProviderHelper();
            ClientCredentials credentials = context.BindingParameters.Find<ClientCredentials>();
            if (credentials != null && credentials.ServiceCertificate.SslCertificateAuthentication != null)
            {
                this.sslCertificateValidator = credentials.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator();
                this.remoteCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);
            }
        }

        public override string Scheme
        {
            get
            {
                return Uri.UriSchemeHttps;
            }
        }

        public bool RequireClientCertificate
        {
            get
            {
                return this.requireClientCertificate;
            }
        }

        public override bool IsChannelBindingSupportEnabled
        {
            get
            {
                return this.channelBindingProvider.IsChannelBindingSupportEnabled;
            }
        }

        public override T GetProperty<T>()
        {
            if (typeof(T) == typeof(IChannelBindingProvider))
            {
                return (T)(object)this.channelBindingProvider;
            }

            return base.GetProperty<T>();
        }

        internal override SecurityMessageProperty CreateReplySecurityProperty(HttpWebRequest request,
            HttpWebResponse response)
        {
            SecurityMessageProperty result = null;
            X509Certificate certificate = request.ServicePoint.Certificate;
            if (certificate != null)
            {
                X509Certificate2 certificateEx = new X509Certificate2(certificate);
                SecurityToken token = new X509SecurityToken(certificateEx, false);
                ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = SecurityUtils.NonValidatingX509Authenticator.ValidateToken(token);
                result = new SecurityMessageProperty();
                result.TransportToken = new SecurityTokenSpecification(token, authorizationPolicies);
                result.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies);
            }
            else
            {
                result = base.CreateReplySecurityProperty(request, response);
            }
            return result;
        }

        protected override void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
        {
            if (remoteAddress.Identity != null)
            {
                X509CertificateEndpointIdentity certificateIdentity =
                    remoteAddress.Identity as X509CertificateEndpointIdentity;
                if (certificateIdentity != null)
                {
                    if (certificateIdentity.Certificates.Count > 1)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
                            SR.HttpsIdentityMultipleCerts, remoteAddress.Uri));
                    }
                }

                EndpointIdentity identity = remoteAddress.Identity;
                bool validIdentity = (certificateIdentity != null)
                    || ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType)
                    || ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType)
                    || ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType);

                if (!HttpChannelFactory<TChannel>.IsWindowsAuth(this.AuthenticationScheme)
                    && !validIdentity)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
                        SR.HttpsExplicitIdentity));
                }
            }
            base.ValidateCreateChannelParameters(remoteAddress, via);
        }

        protected override TChannel OnCreateChannelCore(EndpointAddress address, Uri via)
        {
            ValidateCreateChannelParameters(address, via);
            this.ValidateWebSocketTransportUsage();

            if (typeof(TChannel) == typeof(IRequestChannel))
            {
                return (TChannel)(object)new HttpsRequestChannel((HttpsChannelFactory<IRequestChannel>)(object)this, address, via, ManualAddressing);
            }
            else
            {
                return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, this.ClientWebSocketFactory, address, via, this.WebSocketBufferPool);
            }
        }

        protected override bool IsSecurityTokenManagerRequired()
        {
            return this.requireClientCertificate || base.IsSecurityTokenManagerRequired();
        }

        protected override string OnGetConnectionGroupPrefix(HttpWebRequest httpWebRequest, SecurityTokenContainer clientCertificateToken)
        {
            System.Text.StringBuilder inputStringBuilder = new System.Text.StringBuilder();
            string delimiter = "\0"; // nonprintable characters are invalid for SSPI Domain/UserName/Password

            if (this.RequireClientCertificate)
            {
                HttpsChannelFactory<TChannel>.SetCertificate(httpWebRequest, clientCertificateToken);
                X509CertificateCollection certificateCollection = httpWebRequest.ClientCertificates;
                for (int i = 0; i < certificateCollection.Count; i++)
                {
                    inputStringBuilder.AppendFormat("{0}{1}", certificateCollection[i].GetCertHashString(), delimiter);
                }
            }

            return inputStringBuilder.ToString();
        }

        void OnOpenCore()
        {
            if (this.requireClientCertificate && this.SecurityTokenManager == null)
            {
                throw Fx.AssertAndThrow("HttpsChannelFactory: SecurityTokenManager is null on open.");
            }
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
            base.OnEndOpen(result);
            OnOpenCore();
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            base.OnOpen(timeout);
            OnOpenCore();
        }

        internal SecurityTokenProvider CreateAndOpenCertificateTokenProvider(EndpointAddress target, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout)
        {
            if (!this.RequireClientCertificate)
            {
                return null;
            }
            SecurityTokenProvider certificateProvider = TransportSecurityHelpers.GetCertificateTokenProvider(
                this.SecurityTokenManager, target, via, this.Scheme, channelParameters);
            SecurityUtils.OpenTokenProviderIfRequired(certificateProvider, timeout);
            return certificateProvider;
        }

        static void SetCertificate(HttpWebRequest request, SecurityTokenContainer clientCertificateToken)
        {
            if (clientCertificateToken != null)
            {
                X509SecurityToken x509Token = (X509SecurityToken)clientCertificateToken.Token;
                request.ClientCertificates.Add(x509Token.Certificate);
            }
        }

        internal SecurityTokenContainer GetCertificateSecurityToken(SecurityTokenProvider certificateProvider,
            EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, ref TimeoutHelper timeoutHelper)
        {
            SecurityToken token = null;
            SecurityTokenContainer tokenContainer = null;
            SecurityTokenProvider webRequestCertificateProvider;
            if (ManualAddressing && this.RequireClientCertificate)
            {
                webRequestCertificateProvider = CreateAndOpenCertificateTokenProvider(to, via, channelParameters, timeoutHelper.RemainingTime());
            }
            else
            {
                webRequestCertificateProvider = certificateProvider;
            }

            if (webRequestCertificateProvider != null)
            {
                token = webRequestCertificateProvider.GetToken(timeoutHelper.RemainingTime());
            }

            if (ManualAddressing && this.RequireClientCertificate)
            {
                SecurityUtils.AbortTokenProviderIfRequired(webRequestCertificateProvider);
            }

            if (token != null)
            {
                tokenContainer = new SecurityTokenContainer(token);
            }

            return tokenContainer;
        }

        void AddServerCertMappingOrSetRemoteCertificateValidationCallback(HttpWebRequest request, EndpointAddress to)
        {
            Fx.Assert(request != null, "request should not be null.");
            if (this.sslCertificateValidator != null)
            {
                request.ServerCertificateValidationCallback = this.remoteCertificateValidationCallback;
            }
            else
            {
                HttpTransportSecurityHelpers.AddServerCertMapping(request, to);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic,
            "Reliability104:CaughtAndHandledExceptionsRule",
            Justification = "The exception being thrown out comes from user code. Any non-fatal exception should be handled and translated into validation failure(return false).")]
        bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            Fx.Assert(sender is HttpWebRequest, "sender should be HttpWebRequest");
            Fx.Assert(this.sslCertificateValidator != null, "sslCertificateAuthentidation should not be null.");

            try
            {
                this.sslCertificateValidator.Validate(new X509Certificate2(certificate));
                return true;
            }
            catch (SecurityTokenValidationException ex)
            {
                FxTrace.Exception.AsInformation(ex);
                return false;
            }
            catch (Exception ex)
            {
                if (Fx.IsFatal(ex))
                {
                    throw;
                }

                FxTrace.Exception.AsWarning(ex);
                return false;
            }
        }

        class HttpsRequestChannel : HttpRequestChannel
        {
            SecurityTokenProvider certificateProvider;
            HttpsChannelFactory<IRequestChannel> factory;

            public HttpsRequestChannel(HttpsChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
                : base(factory, to, via, manualAddressing)
            {
                this.factory = factory;
            }

            public new HttpsChannelFactory<IRequestChannel> Factory
            {
                get { return this.factory; }
            }

            void CreateAndOpenTokenProvider(TimeSpan timeout)
            {
                if (!ManualAddressing && this.Factory.RequireClientCertificate)
                {
                    this.certificateProvider = Factory.CreateAndOpenCertificateTokenProvider(this.RemoteAddress, this.Via, this.ChannelParameters, timeout);
                }
            }

            void CloseTokenProvider(TimeSpan timeout)
            {
                if (this.certificateProvider != null)
                {
                    SecurityUtils.CloseTokenProviderIfRequired(this.certificateProvider, timeout);
                }
            }

            void AbortTokenProvider()
            {
                if (this.certificateProvider != null)
                {
                    SecurityUtils.AbortTokenProviderIfRequired(this.certificateProvider);
                }
            }

            protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                CreateAndOpenTokenProvider(timeoutHelper.RemainingTime());
                return base.OnBeginOpen(timeoutHelper.RemainingTime(), callback, state);
            }

            protected override void OnOpen(TimeSpan timeout)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                CreateAndOpenTokenProvider(timeoutHelper.RemainingTime());
                base.OnOpen(timeoutHelper.RemainingTime());
            }

            protected override void OnAbort()
            {
                AbortTokenProvider();
                base.OnAbort();
            }

            protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                CloseTokenProvider(timeoutHelper.RemainingTime());
                return base.OnBeginClose(timeoutHelper.RemainingTime(), callback, state);
            }

            protected override void OnClose(TimeSpan timeout)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                CloseTokenProvider(timeoutHelper.RemainingTime());
                base.OnClose(timeoutHelper.RemainingTime());
            }

            public IAsyncResult BeginBaseGetWebRequest(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
            {
                return base.BeginGetWebRequest(to, via, clientCertificateToken, ref timeoutHelper, callback, state);
            }

            public HttpWebRequest EndBaseGetWebRequest(IAsyncResult result)
            {
                return base.EndGetWebRequest(result);
            }

            public override HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper)
            {
                SecurityTokenContainer clientCertificateToken = Factory.GetCertificateSecurityToken(this.certificateProvider, to, via, this.ChannelParameters, ref timeoutHelper);
                HttpWebRequest request = base.GetWebRequest(to, via, clientCertificateToken, ref timeoutHelper);
                this.factory.AddServerCertMappingOrSetRemoteCertificateValidationCallback(request, to);
                return request;
            }

            public override IAsyncResult BeginGetWebRequest(EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
            {
                return new GetWebRequestAsyncResult(this, to, via, ref timeoutHelper, callback, state);
            }

            public override HttpWebRequest EndGetWebRequest(IAsyncResult result)
            {
                return GetWebRequestAsyncResult.End(result);
            }

            public override bool WillGetWebRequestCompleteSynchronously()
            {
                if (!base.WillGetWebRequestCompleteSynchronously())
                {
                    return false;
                }

                return (this.certificateProvider == null && !Factory.ManualAddressing);
            }

            internal override void OnWebRequestCompleted(HttpWebRequest request)
            {
                HttpTransportSecurityHelpers.RemoveServerCertMapping(request);
            }

            class GetWebRequestAsyncResult : AsyncResult
            {
                SecurityTokenProvider certificateProvider;
                HttpsChannelFactory<IRequestChannel> factory;
                HttpsRequestChannel httpsChannel;
                HttpWebRequest request;
                EndpointAddress to;
                Uri via;
                TimeoutHelper timeoutHelper;
                SecurityTokenContainer tokenContainer;
                static AsyncCallback onGetBaseWebRequestCallback = Fx.ThunkCallback(new AsyncCallback(OnGetBaseWebRequestCallback));
                static AsyncCallback onGetTokenCallback;

                public GetWebRequestAsyncResult(HttpsRequestChannel httpsChannel, EndpointAddress to, Uri via,
                    ref TimeoutHelper timeoutHelper,
                    AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.httpsChannel = httpsChannel;
                    this.to = to;
                    this.via = via;
                    this.timeoutHelper = timeoutHelper;
                    this.factory = httpsChannel.Factory;
                    this.certificateProvider = httpsChannel.certificateProvider;
                    if (this.factory.ManualAddressing && this.factory.RequireClientCertificate)
                    {
                        this.certificateProvider =
                            this.factory.CreateAndOpenCertificateTokenProvider(to, via, httpsChannel.ChannelParameters, timeoutHelper.RemainingTime());
                    }

                    if (!GetToken())
                    {
                        return;
                    }

                    if (!GetWebRequest())
                    {
                        return;
                    }

                    base.Complete(true);
                }

                bool GetWebRequest()
                {
                    IAsyncResult result = this.httpsChannel.BeginBaseGetWebRequest(to, via, tokenContainer, ref timeoutHelper, onGetBaseWebRequestCallback, this);

                    if (!result.CompletedSynchronously)
                    {
                        return false;
                    }

                    this.request = this.httpsChannel.EndBaseGetWebRequest(result);
                    this.factory.AddServerCertMappingOrSetRemoteCertificateValidationCallback(this.request, this.to);
                    return true;
                }

                bool GetToken()
                {
                    if (this.certificateProvider != null)
                    {
                        if (onGetTokenCallback == null)
                        {
                            onGetTokenCallback = Fx.ThunkCallback(new AsyncCallback(OnGetTokenCallback));
                        }

                        IAsyncResult result = this.certificateProvider.BeginGetToken(
                            timeoutHelper.RemainingTime(), onGetTokenCallback, this);

                        if (!result.CompletedSynchronously)
                        {
                            return false;
                        }
                        OnGetToken(result);
                    }

                    return true;
                }

                static void OnGetBaseWebRequestCallback(IAsyncResult result)
                {
                    if (result.CompletedSynchronously)
                        return;

                    GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState;

                    Exception completionException = null;
                    try
                    {
                        thisPtr.request = thisPtr.httpsChannel.EndBaseGetWebRequest(result);
                        thisPtr.factory.AddServerCertMappingOrSetRemoteCertificateValidationCallback(thisPtr.request, thisPtr.to);
                    }
#pragma warning suppress 56500 // [....], transferring exception to another thread
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        completionException = e;
                    }
                    thisPtr.Complete(false, completionException);
                }

                static void OnGetTokenCallback(IAsyncResult result)
                {
                    if (result.CompletedSynchronously)
                        return;

                    GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState;

                    Exception completionException = null;
                    bool completeSelf;
                    try
                    {
                        thisPtr.OnGetToken(result);
                        completeSelf = thisPtr.GetWebRequest();
                    }
#pragma warning suppress 56500 // [....], transferring exception to another thread
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        completeSelf = true;
                        completionException = e;
                    }
                    if (completeSelf)
                    {
                        thisPtr.Complete(false, completionException);
                    }
                }

                void OnGetToken(IAsyncResult result)
                {
                    SecurityToken token = this.certificateProvider.EndGetToken(result);
                    if (token != null)
                    {
                        this.tokenContainer = new SecurityTokenContainer(token);
                    }
                    CloseCertificateProviderIfRequired();
                }

                void CloseCertificateProviderIfRequired()
                {
                    if (this.factory.ManualAddressing && this.certificateProvider != null)
                    {
                        SecurityUtils.AbortTokenProviderIfRequired(this.certificateProvider);
                    }
                }

                public static HttpWebRequest End(IAsyncResult result)
                {
                    GetWebRequestAsyncResult thisPtr = AsyncResult.End<GetWebRequestAsyncResult>(result);
                    return thisPtr.request;
                }
            }
        }
    }
}