Welcome to mirror list, hosted at ThFree Co, Russian Federation.

hash.cs « policy « security « system « mscorlib « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 184faec0ee70988bed502ad7f7d87c0530f7587e (plain)
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
// ==++==
// 
//   Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// ==--==
// <OWNER>Microsoft</OWNER>
// 

//
// Hash
//
// Evidence corresponding to a hash of the assembly bits.
//

using System;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Util;
using Microsoft.Win32.SafeHandles;

namespace System.Security.Policy
{
    [Serializable]
    [ComVisible(true)]
    public sealed class Hash : EvidenceBase, ISerializable
    {
        private RuntimeAssembly m_assembly;
        private Dictionary<Type, byte[]> m_hashes;
        private WeakReference m_rawData;

        /// <summary>
        ///     Deserialize a serialized hash evidence object
        /// </summary>
        [SecurityCritical]
        internal Hash(SerializationInfo info, StreamingContext context)
        {
            //
            // We have three serialization formats that we might be deserializing, the Whidbey format which
            // contains hash values directly, the Whidbey format which contains a pointer to a PEImage, and
            // the v4 format which contains a dictionary of calculated hashes.
            // 
            // If we have the Whidbey version that has built in hash values, we can convert that, but we
            // cannot do anything with the PEImage format since that is a serialized pointer into another
            // runtime's VM.
            // 

            Dictionary<Type, byte[]> hashes = info.GetValueNoThrow("Hashes", typeof(Dictionary<Type, byte[]>)) as Dictionary<Type, byte[]>;
            if (hashes != null)
            {
                m_hashes = hashes;
            }
            else
            {
                // If there is no hash value dictionary, then check to see if we have the Whidbey multiple
                // hashes version of the evidence.
                m_hashes = new Dictionary<Type, byte[]>();

                byte[] md5 = info.GetValueNoThrow("Md5", typeof(byte[])) as byte[];
                if (md5 != null)
                {
                    m_hashes[typeof(MD5)] = md5;
                }

                byte[] sha1 = info.GetValueNoThrow("Sha1", typeof(byte[])) as byte[];
                if (sha1 != null)
                {
                    m_hashes[typeof(SHA1)] = sha1;
                }

                byte[] rawData = info.GetValueNoThrow("RawData", typeof(byte[])) as byte[];
                if (rawData != null)
                {
                    GenerateDefaultHashes(rawData);
                }
            }
        }

        /// <summary>
        ///     Create hash evidence for the specified assembly
        /// </summary>
        public Hash(Assembly assembly)
        {
            if (assembly == null)
                throw new ArgumentNullException("assembly");
            Contract.EndContractBlock();
            if (assembly.IsDynamic)
                throw new ArgumentException(Environment.GetResourceString("Security_CannotGenerateHash"), "assembly");

            m_hashes = new Dictionary<Type, byte[]>();
            m_assembly = assembly as RuntimeAssembly;

            if (m_assembly == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly");
        }

        /// <summary>
        ///     Create a copy of some hash evidence
        /// </summary>
        private Hash(Hash hash)
        {
            Contract.Assert(hash != null);

            m_assembly = hash.m_assembly;
            m_rawData = hash.m_rawData;
            m_hashes = new Dictionary<Type, byte[]>(hash.m_hashes);
        }

        /// <summary>
        ///     Create a hash evidence prepopulated with a specific hash value
        /// </summary>
        private Hash(Type hashType, byte[] hashValue)
        {
            Contract.Assert(hashType != null);
            Contract.Assert(hashValue != null);

            m_hashes = new Dictionary<Type, byte[]>();

            byte[] hashClone = new byte[hashValue.Length];
            Array.Copy(hashValue, hashClone, hashClone.Length);

            m_hashes[hashType] = hashValue;
        }

        /// <summary>
        ///     Build a Hash evidence that contains the specific SHA-1 hash.  The input hash is not validated,
        ///     and the resulting Hash object cannot calculate additional hash values.
        /// </summary>
        public static Hash CreateSHA1(byte[] sha1)
        {
            if (sha1 == null)
                throw new ArgumentNullException("sha1");
            Contract.EndContractBlock();

            return new Hash(typeof(SHA1), sha1);
        }

        /// <summary>
        ///     Build a Hash evidence that contains the specific SHA-256 hash.  The input hash is not
        ///     validated, and the resulting Hash object cannot calculate additional hash values.
        /// </summary>
        public static Hash CreateSHA256(byte[] sha256)
        {
            if (sha256 == null)
                throw new ArgumentNullException("sha256");
            Contract.EndContractBlock();

            return new Hash(typeof(SHA256), sha256);
        }

        /// <summary>
        ///     Build a Hash evidence that contains the specific MD5 hash.  The input hash is not validated,
        ///     and the resulting Hash object cannot calculate additional hash values.
        /// </summary>
        public static Hash CreateMD5(byte[] md5)
        {
            if (md5 == null)
                throw new ArgumentNullException("md5");
            Contract.EndContractBlock();

            return new Hash(typeof(MD5), md5);
        }

        /// <summary>
        ///     Make a copy of this evidence object
        /// </summary>
        public override EvidenceBase Clone()
        {
            return new Hash(this);
        }

        /// <summary>
        ///     Prepare the hash evidence for serialization
        /// </summary>
        [OnSerializing]
        private void OnSerializing(StreamingContext ctx)
        {
            GenerateDefaultHashes();
        }

        /// <summary>
        ///     Serialize the hash evidence
        /// </summary>
        [SecurityCritical]
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            GenerateDefaultHashes();

            //
            // Backwards compatibility with Whidbey
            //

            byte[] sha1Hash;
            byte[] md5Hash;

            // Whidbey expects the MD5 and SHA1 hashes stored separately.
            if (m_hashes.TryGetValue(typeof(MD5), out md5Hash))
            {
                info.AddValue("Md5", md5Hash);
            }
            if (m_hashes.TryGetValue(typeof(SHA1), out sha1Hash))
            {
                info.AddValue("Sha1", sha1Hash);
            }
            
            // For perf, don't serialize the assembly binary content.
            // This has the side-effect that the Whidbey runtime will not be able to compute any 
            // hashes besides the provided MD5 and SHA1.
            info.AddValue("RawData", null);
            // It doesn't make sense to serialize a memory pointer cross-runtime.
            info.AddValue("PEFile", IntPtr.Zero);

            //
            // Current implementation
            //

            // Add all the computed hashes. While this can duplicate the MD5 and SHA1 hashes, 
            // it allows for a clean separation between legacy support and the current implementation.
            info.AddValue("Hashes", m_hashes);
        }

        /// <summary>
        ///     Get the SHA-1 hash value of the assembly
        /// </summary>
        public byte[] SHA1
        {
            get
            {
                byte[] sha1 = null;
                if (!m_hashes.TryGetValue(typeof(SHA1), out sha1))
                {
                    sha1 = GenerateHash(GetDefaultHashImplementationOrFallback(typeof(SHA1), typeof(SHA1)));
                }

                byte[] returnHash = new byte[sha1.Length];
                Array.Copy(sha1, returnHash, returnHash.Length);
                return returnHash;
            }
        }

        /// <summary>
        ///     Get the SHA-256 hash value of the assembly
        /// </summary>
        public byte[] SHA256
        {
            get
            {
                byte[] sha256 = null;
                if (!m_hashes.TryGetValue(typeof(SHA256), out sha256))
                {
                    sha256 = GenerateHash(GetDefaultHashImplementationOrFallback(typeof(SHA256), typeof(SHA256)));
                }

                byte[] returnHash = new byte[sha256.Length];
                Array.Copy(sha256, returnHash, returnHash.Length);
                return returnHash;
            }
        }

        /// <summary>
        ///     Get the MD5 hash value of the assembly
        /// </summary>
        public byte[] MD5
        {
            get
            {
                byte[] md5 = null;
                if (!m_hashes.TryGetValue(typeof(MD5), out md5))
                {
                    md5 = GenerateHash(GetDefaultHashImplementationOrFallback(typeof(MD5), typeof(MD5)));
                }

                byte[] returnHash = new byte[md5.Length];
                Array.Copy(md5, returnHash, returnHash.Length);
                return returnHash;
            }
        }

        /// <summary>
        ///     Get the hash value of the assembly when hashed with a specific algorithm.  The actual hash
        ///     algorithm object is not used, however the same type of object will be used.
        /// </summary>
        public byte[] GenerateHash(HashAlgorithm hashAlg)
        {
            if (hashAlg == null)
                throw new ArgumentNullException("hashAlg");
            Contract.EndContractBlock();

            byte[] hashValue = GenerateHash(hashAlg.GetType());

            byte[] returnHash = new byte[hashValue.Length];
            Array.Copy(hashValue, returnHash, returnHash.Length);
            return returnHash;
        }

        /// <summary>
        ///     Generate the hash value of an assembly when hashed with the specified algorithm. The result
        ///     may be a direct reference to our internal table of hashes, so it should be copied before
        ///     returning it to user code.
        /// </summary>
        private byte[] GenerateHash(Type hashType)
        {
            Contract.Assert(hashType != null && typeof(HashAlgorithm).IsAssignableFrom(hashType), "Expected a hash algorithm");

            Type indexType = GetHashIndexType(hashType);
            byte[] hashValue = null;
            if (!m_hashes.TryGetValue(indexType, out hashValue))
            {
                // If we're not attached to an assembly, then we cannot generate hashes on demand
                if (m_assembly == null)
                {
                    throw new InvalidOperationException(Environment.GetResourceString("Security_CannotGenerateHash"));
                }

                hashValue = GenerateHash(hashType, GetRawData());
                m_hashes[indexType] = hashValue;
            }

            return hashValue;
        }

        /// <summary>
        ///     Generate a hash of the given type for the assembly data
        /// </summary>
        private static byte[] GenerateHash(Type hashType, byte[] assemblyBytes)
        {
            Contract.Assert(hashType != null && typeof(HashAlgorithm).IsAssignableFrom(hashType), "Expected a hash algorithm");
            Contract.Assert(assemblyBytes != null);

            using (HashAlgorithm hash = HashAlgorithm.Create(hashType.FullName))
            {
                return hash.ComputeHash(assemblyBytes);
            }
        }


        /// <summary>
        ///     Build the default set of hash values that will be available for all assemblies
        /// </summary>
        private void GenerateDefaultHashes()
        {
            // We can't generate any hash values that we don't already have if there isn't an attached
            // assembly to get the hash value of.
            if (m_assembly != null)
            {
                GenerateDefaultHashes(GetRawData());
            }
        }

        /// <summary>
        ///     Build the default set of hash values that will be available for all assemblies given the raw
        ///     assembly data to hash.
        /// </summary>
        private void GenerateDefaultHashes(byte[] assemblyBytes)
        {
            Contract.Assert(assemblyBytes != null);

            Type[] defaultHashTypes = new Type[]
            {
                GetHashIndexType(typeof(SHA1)),
                GetHashIndexType(typeof(SHA256)),
                GetHashIndexType(typeof(MD5))
            };

            foreach (Type defaultHashType in defaultHashTypes)
            {
                Type hashImplementationType = GetDefaultHashImplementation(defaultHashType);
                if (hashImplementationType != null)
                {
                    if (!m_hashes.ContainsKey(defaultHashType))
                    {
                        m_hashes[defaultHashType] = GenerateHash(hashImplementationType, assemblyBytes);
                    }
                }
            }
        }

        /// <summary>
        ///     Map a hash algorithm to the default implementation of that algorithm, falling back to a given
        ///     implementation if no suitable default can be found.  This option may be used for situations
        ///     where it is better to throw an informative exception when trying to use an unsuitable hash
        ///     algorithm than to just return null.  (For instance, throwing a FIPS not supported exception
        ///     when trying to get the MD5 hash evidence).
        /// </summary>
        private static Type GetDefaultHashImplementationOrFallback(Type hashAlgorithm,
                                                                   Type fallbackImplementation)
        {
            Contract.Assert(hashAlgorithm != null && typeof(HashAlgorithm).IsAssignableFrom(hashAlgorithm));
            Contract.Assert(fallbackImplementation != null && GetHashIndexType(hashAlgorithm).IsAssignableFrom(fallbackImplementation));

            Type defaultImplementation = GetDefaultHashImplementation(hashAlgorithm);
            return defaultImplementation != null ? defaultImplementation : fallbackImplementation;
        }

        /// <summary>
        ///     Map a hash algorithm to the default implementation of that algorithm to use for Hash
        ///     evidence, taking into account things such as FIPS support.  If there is no suitable
        ///     implementation for the algorithm, GetDefaultHashImplementation returns null.
        /// </summary>
        private static Type GetDefaultHashImplementation(Type hashAlgorithm)
        {
            Contract.Assert(hashAlgorithm != null && typeof(HashAlgorithm).IsAssignableFrom(hashAlgorithm));

            if (hashAlgorithm.IsAssignableFrom(typeof(MD5)))
            {
                // MD5 is not a FIPS compliant algorithm, so if we need to allow only FIPS implementations,
                // we have no way to create an MD5 hash.  Otherwise, we can just use the standard CAPI
                // implementation since that is available on all operating systems we support.
                if (!CryptoConfig.AllowOnlyFipsAlgorithms)
                {
                    return typeof(MD5CryptoServiceProvider);
                }
                else
                {
                    return null;
                }
            }
            else if (hashAlgorithm.IsAssignableFrom(typeof(SHA256)))
            {
                // The managed SHA256 implementation is not a FIPS certified implementation, however on
                // we have a FIPS alternative.
                return Type.GetType("System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyRef.SystemCore);
            }
            else
            {
                // Otherwise we don't have a better suggestion for the algorithm, so we can just fallback to
                // the input algorithm.
                return hashAlgorithm;
            }
        }

        /// <summary>
        ///     Get the type used to index into the saved hash value dictionary.  We want this to be the
        ///     class which immediately derives from HashAlgorithm so that we can reuse the same hash value
        ///     if we're asked for (e.g.) SHA256Managed and SHA256CryptoServiceProvider
        /// </summary>
        private static Type GetHashIndexType(Type hashType)
        {
            Contract.Assert(hashType != null && typeof(HashAlgorithm).IsAssignableFrom(hashType));

            Type currentType = hashType;

            // Walk up the inheritence hierarchy looking for the first class that derives from HashAlgorithm
            while (currentType != null && currentType.BaseType != typeof(HashAlgorithm))
            {
                currentType = currentType.BaseType;
            }

            // If this is the degenerate case where we started out with HashAlgorithm, we won't find it
            // further up our inheritence tree.
            if (currentType == null)
            {
                BCLDebug.Assert(hashType == typeof(HashAlgorithm), "hashType == typeof(HashAlgorithm)");
                currentType = typeof(HashAlgorithm);
            }

            return currentType;
        }

        /// <summary>
        ///     Raw bytes of the assembly being hashed
        /// </summary>
        private byte[] GetRawData()
        {
            byte[] rawData = null;

            // We can only generate hashes on demand if we're associated with an assembly
            if (m_assembly != null)
            {
                // See if we still hold a reference to the assembly data
                if (m_rawData != null)
                {
                    rawData = m_rawData.Target as byte[];
                }

                // If not, load the raw bytes up
                if (rawData == null)
                {
                    rawData = m_assembly.GetRawBytes();
                    m_rawData = new WeakReference(rawData);
                }
            }

            return rawData;
        }

        private SecurityElement ToXml()
        {
            GenerateDefaultHashes();

            SecurityElement root = new SecurityElement("System.Security.Policy.Hash");
            // If you hit this assert then most likely you are trying to change the name of this class. 
            // This is ok as long as you change the hard coded string above and change the assert below.
            BCLDebug.Assert(this.GetType().FullName.Equals("System.Security.Policy.Hash"), "Class name changed!");

            root.AddAttribute("version", "2");
            foreach (KeyValuePair<Type, byte[]> hashValue in m_hashes)
            {
                SecurityElement hashElement = new SecurityElement("hash");
                hashElement.AddAttribute("algorithm", hashValue.Key.Name);
                hashElement.AddAttribute("value", Hex.EncodeHexString(hashValue.Value));

                root.AddChild(hashElement);
            }

            return root;
        }

        public override String ToString()
        {
            return ToXml().ToString();
        }
    }
}