File: AuthenticodeDeformatter.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 (522 lines) | stat: -rw-r--r-- 13,687 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
//
// AuthenticodeDeformatter.cs: Authenticode signature validator
//
// Author:
//	Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;

using Mono.Security.Cryptography;
using Mono.Security.X509;

namespace Mono.Security.Authenticode {

	// References:
	// a.	http://www.cs.auckland.ac.nz/~pgut001/pubs/authenticode.txt

#if INSIDE_CORLIB
	internal
#else
	public 
#endif
	class AuthenticodeDeformatter : AuthenticodeBase {

		private string filename;
		private byte[] rawdata;
		private byte[] hash;
		private X509CertificateCollection coll;
		private ASN1 signedHash;
		private DateTime timestamp;
		private X509Certificate signingCertificate;
		private int reason;
		private bool trustedRoot;
		private bool trustedTimestampRoot;
		private byte[] entry;

		private X509Chain signerChain;
		private X509Chain timestampChain;

		public AuthenticodeDeformatter () : base ()
		{
			reason = -1;
			signerChain = new X509Chain ();
			timestampChain = new X509Chain ();
		}

		public AuthenticodeDeformatter (string fileName) : this () 
		{
			FileName = fileName;
		}

		public AuthenticodeDeformatter (byte[] rawData) : this ()
		{
			RawData = rawData;
		}

		public string FileName {
			get { return filename; }
			set { 
				Reset ();
				filename = value;
				try {
					CheckSignature ();
				} catch (SecurityException) {
					throw;
				} catch {
					reason = 1;
				}
			}
		}

		public byte[] RawData {
			get { return rawdata; }
			set {
				Reset ();
				rawdata = value;
				try {
					CheckSignature ();
				} catch (SecurityException) {
					throw;
				} catch {
					reason = 1;
				}
			}
		}

		public byte[] Hash {
			get { 
				if (signedHash == null)
					return null;
				return (byte[]) signedHash.Value.Clone ();
			}
		}

		public int Reason {
			get { 
				if (reason == -1)
					IsTrusted ();
				return reason; 
			}
		}

		public bool IsTrusted ()
		{
			if (entry == null) {
				reason = 1;
				return false;
			}

			if (signingCertificate == null) {
				reason = 7;
				return false;
			}

			if ((signerChain.Root == null) || !trustedRoot) {
				reason = 6;
				return false;
			}

			if (timestamp != DateTime.MinValue) {
				if ((timestampChain.Root == null) || !trustedTimestampRoot) {
					reason = 6;
					return false;
				}

				// check that file was timestamped when certificates were valid
				if (!signingCertificate.WasCurrent (Timestamp)) {
					reason = 4;
					return false;
				}
			}
			else if (!signingCertificate.IsCurrent) {
				// signature only valid if the certificate is valid
				reason = 8;
				return false;
			}

			if (reason == -1)
				reason = 0;
			return true;
		}

		public byte[] Signature {
			get {
				if (entry == null)
					return null;
				return (byte[]) entry.Clone (); 
			}
		}

		public DateTime Timestamp {
			get { return timestamp; }
		}

		public X509CertificateCollection Certificates {
			get { return coll; }
		}

		public X509Certificate SigningCertificate {
			get { return signingCertificate; }
		}

		private bool CheckSignature ()
		{
			if (filename != null) {
				Open (filename);
			} else {
				Open (rawdata);
			}
			entry = GetSecurityEntry ();
			if (entry == null) {
				// no signature is present
				reason = 1;
				Close ();
				return false;
			}

			PKCS7.ContentInfo ci = new PKCS7.ContentInfo (entry);
			if (ci.ContentType != PKCS7.Oid.signedData) {
				Close ();
				return false;
			}

			PKCS7.SignedData sd = new PKCS7.SignedData (ci.Content);
			if (sd.ContentInfo.ContentType != spcIndirectDataContext) {
				Close ();
				return false;
			}

			coll = sd.Certificates;

			ASN1 spc = sd.ContentInfo.Content;
			signedHash = spc [0][1][1];

			HashAlgorithm ha = null; 
			switch (signedHash.Length) {
				case 16:
					ha = MD5.Create (); 
					hash = GetHash (ha);
					break;
				case 20:
					ha = SHA1.Create ();
					hash = GetHash (ha);
					break;
				case 32:
					ha = SHA256.Create ();
					hash = GetHash (ha);
					break;
				case 48:
					ha = SHA384.Create ();
					hash = GetHash (ha);
					break;
				case 64:
					ha = SHA512.Create ();
					hash = GetHash (ha);
					break;
				default:
					reason = 5;
					Close ();
					return false;
			}
			Close ();

			if (!signedHash.CompareValue (hash)) {
				reason = 2;
			}

			// messageDigest is a hash of spcIndirectDataContext (which includes the file hash)
			byte[] spcIDC = spc [0].Value;
			ha.Initialize (); // re-using hash instance
			byte[] messageDigest = ha.ComputeHash (spcIDC);

			bool sign = VerifySignature (sd, messageDigest, ha);
			return (sign && (reason == 0));
		}

		private bool CompareIssuerSerial (string issuer, byte[] serial, X509Certificate x509) 
		{
			if (issuer != x509.IssuerName)
				return false;
			if (serial.Length != x509.SerialNumber.Length)
				return false;
			// MS shows the serial number inversed (so is Mono.Security.X509.X509Certificate)
			int n = serial.Length;
			for (int i=0; i < serial.Length; i++) {
				if (serial [i] != x509.SerialNumber [--n])
					return false;
			}
			// must be true
			return true;
		}

		//private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName) 
		private bool VerifySignature (PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha) 
		{
			string contentType = null;
			ASN1 messageDigest = null;
//			string spcStatementType = null;
//			string spcSpOpusInfo = null;

			for (int i=0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++) {
				ASN1 attr = (ASN1) sd.SignerInfo.AuthenticatedAttributes [i];
				string oid = ASN1Convert.ToOid (attr[0]);
				switch (oid) {
					case "1.2.840.113549.1.9.3":
						// contentType
						contentType = ASN1Convert.ToOid (attr[1][0]);
						break;
					case "1.2.840.113549.1.9.4":
						// messageDigest
						messageDigest = attr[1][0];
						break;
					case "1.3.6.1.4.1.311.2.1.11":
						// spcStatementType (Microsoft code signing)
						// possible values
						// - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
						// - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
//						spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
						break;
					case "1.3.6.1.4.1.311.2.1.12":
						// spcSpOpusInfo (Microsoft code signing)
/*						try {
							spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
						}
						catch (NullReferenceException) {
							spcSpOpusInfo = null;
						}*/
						break;
					default:
						break;
				}
			}
			if (contentType != spcIndirectDataContext)
				return false;

			// verify message digest
			if (messageDigest == null)
				return false;
			if (!messageDigest.CompareValue (calculatedMessageDigest))
				return false;

			// verify signature
			string hashOID = CryptoConfig.MapNameToOID (ha.ToString ());
			
			// change to SET OF (not [0]) as per PKCS #7 1.5
			ASN1 aa = new ASN1 (0x31);
			foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
				aa.Add (a);
			ha.Initialize ();
			byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

			byte[] signature = sd.SignerInfo.Signature;
			// we need to find the specified certificate
			string issuer = sd.SignerInfo.IssuerName;
			byte[] serial = sd.SignerInfo.SerialNumber;
			foreach (X509Certificate x509 in coll) {
				if (CompareIssuerSerial (issuer, serial, x509)) {
					// don't verify is key size don't match
					if (x509.PublicKey.Length > (signature.Length >> 3)) {
						// return the signing certificate even if the signature isn't correct
						// (required behaviour for 2.0 support)
						signingCertificate = x509;
						RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
						if (rsa.VerifyHash (p7hash, hashOID, signature)) {
							signerChain.LoadCertificates (coll);
							trustedRoot = signerChain.Build (x509);
							break; 
						}
					}
				}
			}

			// validate Extended Key Usage extension contains OID for code signing
			bool hasCodeSigningEKU = false;
			X509Extension ekuExtension = coll.Count > 0 ? coll[0].Extensions["2.5.29.37"] : null;
			if (ekuExtension == null)
				return false;

			ASN1 extensionValue = new ASN1(ekuExtension.Value.Value);
			if (extensionValue.Tag != 0x30)
				return false;

			for (int i = 0; i < extensionValue.Count; i++) {
				string oid = ASN1Convert.ToOid (extensionValue[i]);
				if (oid == "1.3.6.1.5.5.7.3.3") {
					hasCodeSigningEKU = true;
					break;
				}
			}

			if (!hasCodeSigningEKU)
				return false;

			// timestamp signature is optional
			if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0) {
				trustedTimestampRoot = true;
			}  else {
				for (int i = 0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++) {
					ASN1 attr = (ASN1) sd.SignerInfo.UnauthenticatedAttributes[i];
					string oid = ASN1Convert.ToOid (attr[0]);
					switch (oid) {
					case PKCS7.Oid.countersignature:
						// SEQUENCE {
						//   OBJECT IDENTIFIER
						//     countersignature (1 2 840 113549 1 9 6)
						//   SET {
						PKCS7.SignerInfo cs = new PKCS7.SignerInfo (attr[1]);
						trustedTimestampRoot = VerifyCounterSignature (cs, signature);
						break;
					default:
						// we don't support other unauthenticated attributes
						break;
					}
				}
			}

			return (trustedRoot && trustedTimestampRoot);
		}

		private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature) 
		{
			// SEQUENCE {
			//   INTEGER 1
			if (cs.Version > 1)
				return false;
			//   SEQUENCE {
			//      SEQUENCE {

			string contentType = null;
			ASN1 messageDigest = null;
			for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) {
				// SEQUENCE {
				//   OBJECT IDENTIFIER
				ASN1 attr = (ASN1) cs.AuthenticatedAttributes [i];
				string oid = ASN1Convert.ToOid (attr[0]);
				switch (oid) {
					case "1.2.840.113549.1.9.3":
						// contentType
						contentType = ASN1Convert.ToOid (attr[1][0]);
						break;
					case "1.2.840.113549.1.9.4":
						// messageDigest
						messageDigest = attr[1][0];
						break;
					case "1.2.840.113549.1.9.5":
						// SEQUENCE {
						//   OBJECT IDENTIFIER
						//     signingTime (1 2 840 113549 1 9 5)
						//   SET {
						//     UTCTime '030124013651Z'
						//   }
						// }
						timestamp = ASN1Convert.ToDateTime (attr[1][0]);
						break;
					default:
						break;
				}
			}

			if (contentType != PKCS7.Oid.data) 
				return false;

			// verify message digest
			if (messageDigest == null)
				return false;
			// TODO: must be read from the ASN.1 structure
			string hashName = null;
			switch (messageDigest.Length) {
				case 16:
					hashName = "MD5";
					break;
				case 20:
					hashName = "SHA1";
					break;
				case 32:
					hashName = "SHA256";
					break;
				case 48:
					hashName = "SHA384";
					break;
				case 64:
					hashName = "SHA512";
					break;
			}
			HashAlgorithm ha = HashAlgorithm.Create (hashName);
			if (!messageDigest.CompareValue (ha.ComputeHash (signature)))
				return false;

			// verify signature
			byte[] counterSignature = cs.Signature;

			// change to SET OF (not [0]) as per PKCS #7 1.5
			ASN1 aa = new ASN1 (0x31);
			foreach (ASN1 a in cs.AuthenticatedAttributes)
				aa.Add (a);
			byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

			// we need to try all certificates
			string issuer = cs.IssuerName;
			byte[] serial = cs.SerialNumber;
			foreach (X509Certificate x509 in coll) {
				if (CompareIssuerSerial (issuer, serial, x509)) {
					if (x509.PublicKey.Length > counterSignature.Length) {
						RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
						// we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service
						// and this means copying stuff into our own RSAManaged to get the required flexibility
						RSAManaged rsam = new RSAManaged ();
						rsam.ImportParameters (rsa.ExportParameters (false));
						if (PKCS1.Verify_v15 (rsam, ha, p7hash, counterSignature, true)) {
							timestampChain.LoadCertificates (coll);
							return (timestampChain.Build (x509));
						}
					}
				}
			}
			// no certificate can verify this signature!
			return false;
		}

		private void Reset ()
		{
			filename = null;
			rawdata = null;
			entry = null;
			hash = null;
			signedHash = null;
			signingCertificate = null;
			reason = -1;
			trustedRoot = false;
			trustedTimestampRoot = false;
			signerChain.Reset ();
			timestampChain.Reset ();
			timestamp = DateTime.MinValue;
		}
	}
}