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

X509Store.cs « Mono.Security.X509 « Mono.Security « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1821075635ddbc343dfd2fe42944ddc46b11cd20 (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
//
// X509Store.cs: Handles a X.509 certificates/CRLs store
//
// Author:
//	Sebastien Pouliot  <sebastien@ximian.com>
//	Pablo Ruiz <pruiz@netway.org>
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// (C) 2010 Pablo Ruiz.
//
// 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.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;

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

using SSCX = System.Security.Cryptography.X509Certificates;

namespace Mono.Security.X509 {

#if INSIDE_CORLIB
	internal
#else
	public 
#endif
	class X509Store {

		private string _storePath;
		private X509CertificateCollection _certificates;
		private ArrayList _crls;
		private bool _crl;
		private bool _newFormat;
		private string _name;

		internal X509Store (string path, bool crl, bool newFormat)
		{
			_storePath = path;
			_crl = crl;
			_newFormat = newFormat;
		}

		// properties

		public X509CertificateCollection Certificates {
			get { 
				if (_certificates == null) {
					_certificates = BuildCertificatesCollection (_storePath);
				}
				return _certificates; 
			}
		}

		public ArrayList Crls {
			get {
				// CRL aren't applicable to all stores
				// but returning null is a little rude
				if (!_crl) {
					_crls = new ArrayList ();
				}
				if (_crls == null) {
					_crls = BuildCrlsCollection (_storePath);
				}
				return _crls; 
			}
		}

		public string Name {
			get {
				if (_name == null) {
					int n = _storePath.LastIndexOf (Path.DirectorySeparatorChar);
					_name = _storePath.Substring (n+1);
				}
				return _name;
			}
		}

		// methods

		public void Clear () 
		{
			/* 
			 * Both _certificates and _crls extend CollectionBase, whose Clear() method calls OnClear() and 
			 * OnClearComplete(), which should be overridden in derivative classes. So we should not worry about
			 * other threads that might be holding references to _certificates or _crls. They should be smart enough
			 * to handle this gracefully.  And if not, it's their own fault.
			 */
			ClearCertificates ();
			ClearCrls ();
		}

		void ClearCertificates()
		{
			if (_certificates != null)
				_certificates.Clear ();
			_certificates = null;
		}

		void ClearCrls ()
		{
			if (_crls != null)
				_crls.Clear ();
			_crls = null;
		}

		public void Import (X509Certificate certificate) 
		{
			CheckStore (_storePath, true);

			if (_newFormat) {
				ImportNewFormat (certificate);
				return;
			}

			string filename = Path.Combine (_storePath, GetUniqueName (certificate));
			if (!File.Exists (filename)) {
				filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
				if (!File.Exists (filename)) {
					using (FileStream fs = File.Create (filename)) {
						byte[] data = certificate.RawData;
						fs.Write (data, 0, data.Length);
						fs.Close ();
					}
					ClearCertificates ();	// We have modified the store on disk.  So forget the old state.
				}
			} else {
				string newfilename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
				if (GetUniqueNameWithSerial (LoadCertificate (filename)) != GetUniqueNameWithSerial (certificate)) {
					using (FileStream fs = File.Create (newfilename)) {
						byte[] data = certificate.RawData;
						fs.Write (data, 0, data.Length);
						fs.Close ();
					}
					ClearCertificates ();	// We have modified the store on disk.  So forget the old state.
				}
			}
#if !MOBILE
			// Try to save privateKey if available..
			CspParameters cspParams = new CspParameters ();
			cspParams.KeyContainerName = CryptoConvert.ToHex (certificate.Hash);

			// Right now this seems to be the best way to know if we should use LM store.. ;)
			if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
				cspParams.Flags = CspProviderFlags.UseMachineKeyStore;

			ImportPrivateKey (certificate, cspParams);
#endif
		}

		public void Import (X509Crl crl) 
		{
			CheckStore (_storePath, true);

			if (_newFormat)
				throw new NotSupportedException ();

			string filename = Path.Combine (_storePath, GetUniqueName (crl));
			if (!File.Exists (filename)) {
				using (FileStream fs = File.Create (filename)) {
					byte[] data = crl.RawData;
					fs.Write (data, 0, data.Length);
				}
				ClearCrls ();	// We have modified the store on disk.  So forget the old state.
			}
		}

		public void Remove (X509Certificate certificate) 
		{
			if (_newFormat) {
				RemoveNewFormat (certificate);
				return;
			}

			string filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
			if (File.Exists (filename)) {
				File.Delete (filename);
				ClearCertificates ();	// We have modified the store on disk.  So forget the old state.
			} else {
				filename = Path.Combine (_storePath, GetUniqueName (certificate));
				if (File.Exists (filename)) {
					File.Delete (filename);
					ClearCertificates ();	// We have modified the store on disk.  So forget the old state.
				}
			}
		}

		public void Remove (X509Crl crl) 
		{
			if (_newFormat)
				throw new NotSupportedException ();

			string filename = Path.Combine (_storePath, GetUniqueName (crl));
			if (File.Exists (filename)) {
				File.Delete (filename);
				ClearCrls ();	// We have modified the store on disk.  So forget the old state.
			}
		}

		// new format

		void ImportNewFormat (X509Certificate certificate)
		{
#if INSIDE_CORLIB
			throw new NotSupportedException ();
#else
			using (var sscxCert = new SSCX.X509Certificate (certificate.RawData)) {
				var hash = SSCX.X509Helper2.GetSubjectNameHash (sscxCert);
				var filename = Path.Combine (_storePath, string.Format ("{0:x8}.0", hash));
				if (!File.Exists (filename)) {
					using (FileStream fs = File.Create (filename))
						SSCX.X509Helper2.ExportAsPEM (sscxCert, fs, true);
					ClearCertificates ();
				}
			}
#endif
		}

		void RemoveNewFormat (X509Certificate certificate)
		{
#if INSIDE_CORLIB
			throw new NotSupportedException ();
#else
			using (var sscxCert = new SSCX.X509Certificate (certificate.RawData)) {
				var hash = SSCX.X509Helper2.GetSubjectNameHash (sscxCert);
				var filename = Path.Combine (_storePath, string.Format ("{0:x8}.0", hash));
				if (File.Exists (filename)) {
					File.Delete (filename);
					ClearCertificates ();
				}
			}
#endif
		}

		// private stuff

		private string GetUniqueNameWithSerial (X509Certificate certificate)
		{
			return GetUniqueName (certificate, certificate.SerialNumber);
		}

		private string GetUniqueName (X509Certificate certificate, byte[] serial = null) 
		{
			string method;
			byte[] name = GetUniqueName (certificate.Extensions, serial);
			if (name == null) {
				method = "tbp"; // thumbprint
				name = certificate.Hash;
			} else {
				method = "ski";
			}
			return GetUniqueName (method, name, ".cer");
		}

		private string GetUniqueName (X509Crl crl) 
		{
			string method;
			byte[] name = GetUniqueName (crl.Extensions);
			if (name == null) {
				method = "tbp"; // thumbprint
				name = crl.Hash;
			} else {
				method = "ski";
			}
			return GetUniqueName (method, name, ".crl");
		}

		private byte[] GetUniqueName (X509ExtensionCollection extensions, byte[] serial = null) 
		{
			// We prefer Subject Key Identifier as the unique name
			// as it will provide faster lookups
			X509Extension ext = extensions ["2.5.29.14"];
			if (ext == null)
				return null;

			SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension (ext);
			if (serial == null) {
				return ski.Identifier;
			} else {
				byte[] uniqueWithSerial = new byte[ski.Identifier.Length + serial.Length];
				System.Buffer.BlockCopy (ski.Identifier, 0, uniqueWithSerial, 0, ski.Identifier.Length );
				System.Buffer.BlockCopy (serial, 0, uniqueWithSerial, ski.Identifier.Length, serial.Length );
				return uniqueWithSerial;
			}
		}

		private string GetUniqueName (string method, byte[] name, string fileExtension) 
		{
			StringBuilder sb = new StringBuilder (method);
			
			sb.Append ("-");
			foreach (byte b in name) {
				sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
			}
			sb.Append (fileExtension);

			return sb.ToString ();
		}

		private byte[] Load (string filename) 
		{
			byte[] data = null;
			using (FileStream fs = File.OpenRead (filename)) {
				data = new byte [fs.Length];
				fs.Read (data, 0, data.Length);
				fs.Close ();
			}
			return data;
		}

		private X509Certificate LoadCertificate (string filename) 
		{
			byte[] data = Load (filename);
			X509Certificate cert = new X509Certificate (data);
#if !MOBILE
			// If privateKey it's available, load it too..
			CspParameters cspParams = new CspParameters ();
			cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
			if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
				cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
			KeyPairPersistence kpp = new KeyPairPersistence (cspParams);

			try {
				if (!kpp.Load ())
					return cert;
			}
			catch {
				return cert;
			}

			if (cert.RSA != null)
				cert.RSA = new RSACryptoServiceProvider (cspParams);
			else if (cert.DSA != null)
				cert.DSA = new DSACryptoServiceProvider (cspParams);
#endif
			return cert;
		}

		private X509Crl LoadCrl (string filename) 
		{
			byte[] data = Load (filename);
			X509Crl crl = new X509Crl (data);
			return crl;
		}

		private bool CheckStore (string path, bool throwException)
		{
			try {
				if (Directory.Exists (path))
					return true;
				Directory.CreateDirectory (path);
				return Directory.Exists (path);
			}
			catch {
				if (throwException)
					throw;
				return false;
			}
		}

		private X509CertificateCollection BuildCertificatesCollection (string storeName) 
		{
			X509CertificateCollection coll = new X509CertificateCollection ();
			string path = Path.Combine (_storePath, storeName);
			if (!CheckStore (path, false))
				return coll;	// empty collection

			string[] files = Directory.GetFiles (path, _newFormat ? "*.0" : "*.cer");
			if ((files != null) && (files.Length > 0)) {
				foreach (string file in files) {
					try {
						X509Certificate cert = LoadCertificate (file);
						coll.Add (cert);
					}
					catch {
						// in case someone is dumb enough
						// (like me) to include a base64
						// encoded certs (or other junk 
						// into the store).
					}
				}
			}
			return coll;
		}

		private ArrayList BuildCrlsCollection (string storeName) 
		{
			ArrayList list = new ArrayList ();
			string path = Path.Combine (_storePath, storeName);
			if (!CheckStore (path, false))
				return list;	// empty list

			string[] files = Directory.GetFiles (path, "*.crl");
			if ((files != null) && (files.Length > 0)) {
				foreach (string file in files) {
					try {
						X509Crl crl = LoadCrl (file);
						list.Add (crl);
					}
					catch {
						// junk catcher
					}
				}
			}
			return list;
		}
#if !MOBILE
		private void ImportPrivateKey (X509Certificate certificate, CspParameters cspParams)
		{
			RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider;
			if (rsaCsp != null) {
				if (rsaCsp.PublicOnly)
					return;

				RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
				csp.ImportParameters(rsaCsp.ExportParameters(true));
				csp.PersistKeyInCsp = true;
				return;
			}

			RSAManaged rsaMng = certificate.RSA as RSAManaged;
			if (rsaMng != null) {
				if (rsaMng.PublicOnly)
					return;

				RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
				csp.ImportParameters(rsaMng.ExportParameters(true));
				csp.PersistKeyInCsp = true;
				return;
			}

			DSACryptoServiceProvider dsaCsp = certificate.DSA as DSACryptoServiceProvider;
			if (dsaCsp != null) {
				if (dsaCsp.PublicOnly)
					return;

				DSACryptoServiceProvider csp = new DSACryptoServiceProvider(cspParams);
				csp.ImportParameters(dsaCsp.ExportParameters(true));
				csp.PersistKeyInCsp = true;
			}
		}
#endif
	}
}