File: SamlSecurityTokenRequirement.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (418 lines) | stat: -rw-r--r-- 18,569 bytes parent folder | download | duplicates (7)
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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel.Tokens
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IdentityModel.Configuration;
    using System.IdentityModel.Diagnostics;
    using System.IdentityModel.Selectors;
    using System.Security.Claims;
    using System.Security.Cryptography.X509Certificates;
    using System.ServiceModel.Security;
    using System.Text;
    using System.Xml;

    /// <summary>
    /// Extends SecurityTokenRequirement by adding new properties which are
    /// useful for issued tokens.
    /// </summary>
    public class SamlSecurityTokenRequirement
    {

        //
        // The below defaults will only be used if some verification properties are set in config and others are not
        //
        static X509RevocationMode DefaultRevocationMode = X509RevocationMode.Online;
        static X509CertificateValidationMode DefaultValidationMode = X509CertificateValidationMode.PeerOrChainTrust;
        static StoreLocation DefaultStoreLocation = StoreLocation.LocalMachine;

        string _nameClaimType = ClaimsIdentity.DefaultNameClaimType;
        string _roleClaimType = ClaimTypes.Role;

        bool _mapToWindows;
        
        X509CertificateValidator _certificateValidator;

        /// <summary>
        /// Creates an instance of <see cref="SamlSecurityTokenRequirement"/>
        /// </summary>
        public SamlSecurityTokenRequirement()
        {
        }

        /// <summary>
        /// Creates an instance of <see cref="SamlSecurityTokenRequirement"/>
        /// <param name="element">The XmlElement from which the instance is to be loaded.</param>
        /// </summary>
        public SamlSecurityTokenRequirement(XmlElement element)
        {
            if (element == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
            }

            if (element.LocalName != ConfigurationStrings.SamlSecurityTokenRequirement)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7000, ConfigurationStrings.SamlSecurityTokenRequirement, element.LocalName));
            }

            bool foundCustomX509Validator = false;
            X509RevocationMode revocationMode = DefaultRevocationMode;
            X509CertificateValidationMode certificateValidationMode = DefaultValidationMode;
            StoreLocation trustedStoreLocation = DefaultStoreLocation;
            string customValidator = null;

            foreach (XmlAttribute attribute in element.Attributes)
            {
                if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, ConfigurationStrings.MapToWindows))
                {
                    bool outMapToWindows = false;
                    if (!bool.TryParse(attribute.Value, out outMapToWindows))
                    {
                        throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7022, attribute.Value));
                    }
                    this.MapToWindows = outMapToWindows;
                }                
                else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, ConfigurationStrings.IssuerCertificateValidator))
                {
                    customValidator = attribute.Value.ToString();
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, ConfigurationStrings.IssuerCertificateRevocationMode))
                {
                    foundCustomX509Validator = true;

                    string revocationModeString = attribute.Value.ToString();

                    if (StringComparer.OrdinalIgnoreCase.Equals(revocationModeString, ConfigurationStrings.X509RevocationModeNoCheck))
                    {
                        revocationMode = X509RevocationMode.NoCheck;
                    }

                    else if (StringComparer.OrdinalIgnoreCase.Equals(revocationModeString, ConfigurationStrings.X509RevocationModeOffline))
                    {
                        revocationMode = X509RevocationMode.Offline;
                    }

                    else if (StringComparer.OrdinalIgnoreCase.Equals(revocationModeString, ConfigurationStrings.X509RevocationModeOnline))
                    {
                        revocationMode = X509RevocationMode.Online;
                    }

                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID7011, attribute.LocalName, element.LocalName)));
                    }
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, ConfigurationStrings.IssuerCertificateValidationMode))
                {
                    foundCustomX509Validator = true;

                    string validationModeString = attribute.Value.ToString();

                    if (StringComparer.OrdinalIgnoreCase.Equals(validationModeString, ConfigurationStrings.X509CertificateValidationModeChainTrust))
                    {
                        certificateValidationMode = X509CertificateValidationMode.ChainTrust;
                    }

                    else if (StringComparer.OrdinalIgnoreCase.Equals(validationModeString, ConfigurationStrings.X509CertificateValidationModePeerOrChainTrust))
                    {
                        certificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;
                    }

                    else if (StringComparer.OrdinalIgnoreCase.Equals(validationModeString, ConfigurationStrings.X509CertificateValidationModePeerTrust))
                    {
                        certificateValidationMode = X509CertificateValidationMode.PeerTrust;
                    }

                    else if (StringComparer.OrdinalIgnoreCase.Equals(validationModeString, ConfigurationStrings.X509CertificateValidationModeNone))
                    {
                        certificateValidationMode = X509CertificateValidationMode.None;
                    }

                    else if (StringComparer.OrdinalIgnoreCase.Equals(validationModeString, ConfigurationStrings.X509CertificateValidationModeCustom))
                    {
                        certificateValidationMode = X509CertificateValidationMode.Custom;
                    }

                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID7011, attribute.LocalName, element.LocalName)));
                    }
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, ConfigurationStrings.IssuerCertificateTrustedStoreLocation))
                {
                    foundCustomX509Validator = true;

                    string trustedStoreLocationString = attribute.Value.ToString();

                    if (StringComparer.OrdinalIgnoreCase.Equals(trustedStoreLocationString, ConfigurationStrings.X509TrustedStoreLocationCurrentUser))
                    {
                        trustedStoreLocation = StoreLocation.CurrentUser;
                    }

                    else if (StringComparer.OrdinalIgnoreCase.Equals(trustedStoreLocationString, ConfigurationStrings.X509TrustedStoreLocationLocalMachine))
                    {
                        trustedStoreLocation = StoreLocation.LocalMachine;
                    }

                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID7011, attribute.LocalName, element.LocalName)));
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID7004, attribute.LocalName, element.LocalName)));
                }
            }

            List<XmlElement> configElements = XmlUtil.GetXmlElements(element.ChildNodes);

            foreach (XmlElement childElement in configElements)
            {
                if (StringComparer.Ordinal.Equals(childElement.LocalName, ConfigurationStrings.NameClaimType))
                {
                    if (childElement.Attributes.Count != 1 || !StringComparer.Ordinal.Equals(childElement.Attributes[0].LocalName, ConfigurationStrings.Value))
                    {
                        throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7001, String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}", element.LocalName, childElement.LocalName), ConfigurationStrings.Value));
                    }
                    this.NameClaimType = childElement.Attributes[0].Value;
                }
                else if (StringComparer.Ordinal.Equals(childElement.LocalName, ConfigurationStrings.RoleClaimType))
                {
                    if (childElement.Attributes.Count != 1 || !StringComparer.Ordinal.Equals(childElement.Attributes[0].LocalName, ConfigurationStrings.Value))
                    {
                        throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7001, String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}", element.LocalName, childElement.LocalName), ConfigurationStrings.Value));
                    }
                    this.RoleClaimType = childElement.Attributes[0].Value;
                }
                else
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7002, childElement.LocalName, ConfigurationStrings.SamlSecurityTokenRequirement));
                }
            }

            if (certificateValidationMode == X509CertificateValidationMode.Custom)
            {
                if (string.IsNullOrEmpty(customValidator))
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7028));
                }

                Type customValidatorType = Type.GetType(customValidator, true);

                if (customValidatorType == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID7007, customValidatorType));
                }

                _certificateValidator = CustomTypeElement.Resolve<X509CertificateValidator>(new CustomTypeElement(customValidatorType));
            }
            else if (foundCustomX509Validator)
            {
                _certificateValidator = X509Util.CreateCertificateValidator(certificateValidationMode, revocationMode, trustedStoreLocation);
            }
        }

        /// <summary>
        /// Gets/sets the X509CertificateValidator associated with this token requirement
        /// </summary>
        public X509CertificateValidator CertificateValidator
        {
            get
            {
                return _certificateValidator;
            }
            set
            {
                if (value == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
                }
                _certificateValidator = value;
            }
        }

        /// <summary>
        /// Gets or sets the Claim Type that will be used to generate the 
        /// FederatedIdentity.Name property.
        /// </summary>
        public string NameClaimType
        {
            get
            {
                return _nameClaimType;
            }
            set
            {
                _nameClaimType = value;
            }
        }

        /// <summary>
        /// Gets the Claim Types that are used to generate the
        /// FederatedIdentity.Roles property.
        /// </summary>
        public string RoleClaimType
        {
            get
            {
                return _roleClaimType;
            }
            set
            {
                _roleClaimType = value;
            }
        }

        /// <summary>
        /// Determines if the token handler will attempt to map the SAML identity to a
        /// Windows identity via the unique principal name (UPN) claim.
        /// </summary>
        public bool MapToWindows
        {
            get { return _mapToWindows; }
            set { _mapToWindows = value; }
        }

        /// <summary>
        /// Checks if Audience Enforcement checks are required for the given token 
        /// based on this SamlSecurityTokenRequirement settings.
        /// </summary>
        /// <param name="audienceUriMode">
        /// The <see cref="AudienceUriMode"/> defining the audience requirement.
        /// </param>
        /// <param name="token">The Security token to be tested for Audience 
        /// Enforcement.</param>
        /// <returns>True if Audience Enforcement should be applied.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        public virtual bool ShouldEnforceAudienceRestriction(AudienceUriMode audienceUriMode, SecurityToken token)
        {
            if (null == token)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            //
            // Use AudienceUriMode to determine whether the audience 
            // should be enforced
            //
            switch (audienceUriMode)
            {
                case AudienceUriMode.Always:
                    return true;

                case AudienceUriMode.Never:
                    return false;

                case AudienceUriMode.BearerKeyOnly:
#pragma warning suppress 56506
                    return (null == token.SecurityKeys || 0 == token.SecurityKeys.Count);

                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4025, audienceUriMode)));
            }
        }

        /// <summary>
        /// Checks the given list of Audience URIs with the AllowedAudienceUri list.
        /// </summary>
        /// <param name="allowedAudienceUris">Collection of AudienceUris.</param>
        /// <param name="tokenAudiences">Collection of audience URIs the token applies to.</param>
        /// <exception cref="ArgumentNullException">The input argument 'allowedAudienceUris' is null.</exception>
        /// <exception cref="ArgumentNullException">The input argument 'tokenAudiences' is null.</exception>
        /// <exception cref="AudienceUriValidationFailedException">Either the input argument 'tokenAudiences' or the configured
        /// 'AudienceUris' collection is empty.</exception>
        public virtual void ValidateAudienceRestriction(IList<Uri> allowedAudienceUris, IList<Uri> tokenAudiences)
        {
            if (null == allowedAudienceUris)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("allowedAudienceUris");
            }

            if (null == tokenAudiences)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenAudiences");
            }

            if (0 == tokenAudiences.Count)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(
                    SR.GetString(SR.ID1036)));
            }

            if (0 == allowedAudienceUris.Count)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(
                    SR.GetString(SR.ID1043)));
            }

            bool found = false;
            foreach (Uri audience in tokenAudiences)
            {
                if (audience != null)
                {
                    // Strip off any query string or fragment. This is necessary because the 
                    // CardSpace uses the raw Request-URI to form the audience when issuing 
                    // tokens for personal cards, but we clearly don't want things like the 
                    // ReturnUrl parameter affecting the audience matching.
                    Uri audienceLeftPart;
                    if (audience.IsAbsoluteUri)
                    {
                        audienceLeftPart = new Uri(audience.GetLeftPart(UriPartial.Path));
                    }
                    else
                    {
                        Uri baseUri = new Uri("http://www.example.com");
                        Uri resolved = new Uri(baseUri, audience);
                        audienceLeftPart = baseUri.MakeRelativeUri(new Uri(resolved.GetLeftPart(UriPartial.Path)));
                    }

                    if (allowedAudienceUris.Contains(audienceLeftPart))
                    {
                        found = true;
                        break;
                    }
                }
            }

            if (!found)
            {
#pragma warning suppress 56506
                if (1 == tokenAudiences.Count || null != tokenAudiences[0])
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(
                        SR.GetString(SR.ID1038, tokenAudiences[0].OriginalString)));
                }
                else
                {
                    StringBuilder sb = new StringBuilder(SR.GetString(SR.ID8007));
                    bool first = true;

                    foreach (Uri a in tokenAudiences)
                    {
                        if (a != null)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                sb.Append(", ");
                            }

                            sb.Append(a.OriginalString);
                        }
                    }

                    TraceUtility.TraceString(TraceEventType.Error, sb.ToString());

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(SR.GetString(SR.ID1037)));
                }
            }
        }
    }
}