File: RsaSecurityToken.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 (208 lines) | stat: -rw-r--r-- 7,331 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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.IdentityModel.Tokens
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    using System.Runtime.CompilerServices;

    public class RsaSecurityToken : SecurityToken
    {
        string id;
        DateTime effectiveTime;
        ReadOnlyCollection<SecurityKey> rsaKey;
        RSA rsa;
        CspKeyContainerInfo keyContainerInfo;
        GCHandle rsaHandle;

        public RsaSecurityToken(RSA rsa)
            : this(rsa, SecurityUniqueId.Create().Value)
        {
        }

        public RsaSecurityToken(RSA rsa, string id)
        {
            if (rsa == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");
            if (id == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");
            this.rsa = rsa;
            this.id = id;
            this.effectiveTime = DateTime.UtcNow;
            GC.SuppressFinalize(this);
        }

        // This is defense-in-depth.
        // Rsa finalizer can throw and bring down the process if in finalizer context.
        // This internal ctor is used by SM's IssuedSecurityTokenProvider.
        // If ownsRsa=true, this class will take ownership of the Rsa object and provides
        // a reliable finalizing/disposing of Rsa object.  The GCHandle is used to ensure 
        // order in finalizer sequence.
        RsaSecurityToken(RSACryptoServiceProvider rsa, bool ownsRsa)
        {
            if (rsa == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");
            this.rsa = rsa;
            this.id = SecurityUniqueId.Create().Value;
            this.effectiveTime = DateTime.UtcNow;
            if (ownsRsa)
            {
                // This also key pair generation.  
                // This must be called before PersistKeyInCsp to avoid a handle to go out of scope.
                this.keyContainerInfo = rsa.CspKeyContainerInfo;
                // We will handle key file deletion
                rsa.PersistKeyInCsp = true;
                this.rsaHandle = GCHandle.Alloc(rsa);
            }
            else
            {
                GC.SuppressFinalize(this);
            }
        }

        ~RsaSecurityToken()
        {
            Dispose(false);
        }

        internal void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        void Dispose(bool disposing)
        {
            if (this.rsaHandle.IsAllocated)
            {
                try
                {
                    // keyContainerInfo is a wrapper over a member of Rsa.
                    // this is to be safe that rsa.Dispose won't clean up that member.
                    string keyContainerName = this.keyContainerInfo.KeyContainerName;
                    string providerName = this.keyContainerInfo.ProviderName;
                    uint providerType = (uint)this.keyContainerInfo.ProviderType;

                    ((IDisposable)this.rsa).Dispose();

                    // Best effort delete key file in user context
                    SafeProvHandle provHandle;
                    if (!NativeMethods.CryptAcquireContextW(out provHandle,
                                                            keyContainerName,
                                                            providerName,
                                                            providerType,
                                                            NativeMethods.CRYPT_DELETEKEYSET))
                    {
                        int error = Marshal.GetLastWin32Error();
                        try
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                new InvalidOperationException(SR.GetString(SR.FailedToDeleteKeyContainerFile), new Win32Exception(error)));
                        }
                        catch (InvalidOperationException ex)
                        {
                            DiagnosticUtility.TraceHandledException(ex, TraceEventType.Warning);
                        }
                    }
                    System.ServiceModel.Diagnostics.Utility.CloseInvalidOutSafeHandle(provHandle);
                }
                finally
                {
                    this.rsaHandle.Free();
                }
            }
        }

        internal static RsaSecurityToken CreateSafeRsaSecurityToken(int keySize)
        {
            RsaSecurityToken token;
            RSACryptoServiceProvider rsa = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                try
                {
                }
                finally
                {
                    rsa = new RSACryptoServiceProvider(keySize);
                }
                token = new RsaSecurityToken(rsa, true);
                rsa = null;
            }
            finally
            {
                if (rsa != null)
                {
                    ((IDisposable)rsa).Dispose();
                }
            }
            return token;
        }

        public override string Id
        {
            get { return this.id; }
        }

        public override DateTime ValidFrom
        {
            get { return this.effectiveTime; }
        }

        public override DateTime ValidTo
        {
            // Never expire
            get { return SecurityUtils.MaxUtcDateTime; }
        }

        public override ReadOnlyCollection<SecurityKey> SecurityKeys
        {
            get
            {
                if (this.rsaKey == null)
                {
                    List<SecurityKey> keys = new List<SecurityKey>(1);
                    keys.Add(new RsaSecurityKey(this.rsa));
                    this.rsaKey = keys.AsReadOnly();
                }
                return this.rsaKey;
            }
        }

        public RSA Rsa
        {
            get { return this.rsa; }
        }

        public override bool CanCreateKeyIdentifierClause<T>()
        {
            return typeof(T) == typeof(RsaKeyIdentifierClause);
        }

        public override T CreateKeyIdentifierClause<T>()
        {
            if (typeof(T) == typeof(RsaKeyIdentifierClause))
                return (T)((object)new RsaKeyIdentifierClause(this.rsa));

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
                SR.GetString(SR.TokenDoesNotSupportKeyIdentifierClauseCreation, GetType().Name, typeof(T).Name)));
        }

        public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
        {
            RsaKeyIdentifierClause rsaKeyIdentifierClause = keyIdentifierClause as RsaKeyIdentifierClause;
            if (rsaKeyIdentifierClause != null)
                return rsaKeyIdentifierClause.Matches(this.rsa);

            return false;
        }
    }
}