Use the right socket for the data stream
[mono.git] / mcs / class / System / System.Security.Cryptography.X509Certificates / X509Certificate2Collection.cs
1 //
2 // System.Security.Cryptography.X509Certificates.X509Certificate2Collection class
3 //
4 // Authors:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //      Tim Coleman (tim@timcoleman.com)
7 //
8 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) Tim Coleman, 2004
10 // Copyright (C) 2005, 2006 Novell Inc. (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 #if SECURITY_DEP || MOONLIGHT
33
34 using System.Collections;
35 using System.Globalization;
36
37 namespace System.Security.Cryptography.X509Certificates {
38
39         public class X509Certificate2Collection : X509CertificateCollection {
40
41                 // constructors
42
43                 public X509Certificate2Collection ()
44                 {
45                 }
46
47                 public X509Certificate2Collection (X509Certificate2Collection certificates)
48                 {
49                         AddRange (certificates);
50                 }
51
52                 public X509Certificate2Collection (X509Certificate2 certificate) 
53                 {
54                         Add (certificate);
55                 }
56
57                 public X509Certificate2Collection (X509Certificate2[] certificates) 
58                 {
59                         AddRange (certificates);
60                 }
61
62                 // properties
63
64                 public new X509Certificate2 this [int index] {
65                         get {
66                                 if (index < 0)
67                                         throw new ArgumentOutOfRangeException ("negative index");
68                                 if (index >= InnerList.Count)
69                                         throw new ArgumentOutOfRangeException ("index >= Count");
70                                 return (X509Certificate2) InnerList [index];
71                         }
72                         set { InnerList [index] = value; }
73                 }
74
75                 // methods
76
77                 public int Add (X509Certificate2 certificate)
78                 {
79                         if (certificate == null)
80                                 throw new ArgumentNullException ("certificate");
81
82                         return InnerList.Add (certificate);
83                 }
84
85                 [MonoTODO ("Method isn't transactional (like documented)")]
86                 public void AddRange (X509Certificate2[] certificates) 
87                 {
88                         if (certificates == null)
89                                 throw new ArgumentNullException ("certificates");
90
91                         for (int i=0; i < certificates.Length; i++)
92                                 InnerList.Add (certificates [i]);
93                 }
94
95                 [MonoTODO ("Method isn't transactional (like documented)")]
96                 public void AddRange (X509Certificate2Collection certificates) 
97                 {
98                         if (certificates == null)
99                                 throw new ArgumentNullException ("certificates");
100
101                         InnerList.AddRange (certificates);
102                 }
103
104                 public bool Contains (X509Certificate2 certificate) 
105                 {
106                         if (certificate == null)
107                                 throw new ArgumentNullException ("certificate");
108
109                         foreach (X509Certificate2 c in InnerList) {
110                                 if (c.Equals (certificate))
111                                         return true;
112                         }
113                         return false;
114                 }
115
116                 [MonoTODO ("only support X509ContentType.Cert")]
117                 public byte[] Export (X509ContentType contentType) 
118                 {
119                         return Export (contentType, null);
120                 }
121
122                 [MonoTODO ("only support X509ContentType.Cert")]
123                 public byte[] Export (X509ContentType contentType, string password) 
124                 {
125                         switch (contentType) {
126                         case X509ContentType.Cert:
127 #if !MOONLIGHT
128                         case X509ContentType.Pfx: // this includes Pkcs12
129                         case X509ContentType.SerializedCert:
130 #endif
131                                 // if multiple certificates are present we only export the last one
132                                 if (Count > 0)
133                                         return this [Count - 1].Export (contentType, password);
134                                 break;
135 #if !MOONLIGHT
136                         case X509ContentType.Pkcs7:
137                                 // TODO
138                                 break;
139                         case X509ContentType.SerializedStore:
140                                 // TODO
141                                 break;
142 #endif
143                         default:
144                                 // this includes Authenticode, Unknown and bad values
145                                 string msg = Locale.GetText ("Cannot export certificate(s) to the '{0}' format", contentType);
146                                 throw new CryptographicException (msg);
147                         }
148                         return null;
149                 }
150
151                 [MonoTODO ("Does not support X509FindType.FindByTemplateName, FindByApplicationPolicy and FindByCertificatePolicy")]
152                 public X509Certificate2Collection Find (X509FindType findType, object findValue, bool validOnly) 
153                 {
154                         if (findValue == null)
155                                 throw new ArgumentNullException ("findValue");
156
157                         string str = String.Empty;
158                         string oid = String.Empty;
159                         X509KeyUsageFlags ku = X509KeyUsageFlags.None;
160                         DateTime dt = DateTime.MinValue;
161
162                         switch (findType) {
163                         case X509FindType.FindByThumbprint:
164                         case X509FindType.FindBySubjectName:
165                         case X509FindType.FindBySubjectDistinguishedName:
166                         case X509FindType.FindByIssuerName:
167                         case X509FindType.FindByIssuerDistinguishedName:
168                         case X509FindType.FindBySerialNumber:
169                         case X509FindType.FindByTemplateName:
170                         case X509FindType.FindBySubjectKeyIdentifier:
171                                 try {
172                                         str = (string) findValue;
173                                 }
174                                 catch (Exception e) {
175                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
176                                                 findValue.GetType (), "string");
177                                         throw new CryptographicException (msg, e);
178                                 }
179                                 break;
180                         case X509FindType.FindByApplicationPolicy:
181                         case X509FindType.FindByCertificatePolicy:
182                         case X509FindType.FindByExtension:
183                                 try {
184                                         oid = (string) findValue;
185                                 }
186                                 catch (Exception e) {
187                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
188                                                 findValue.GetType (), "X509KeyUsageFlags");
189                                         throw new CryptographicException (msg, e);
190                                 }
191                                 // OID validation
192                                 try {
193                                         CryptoConfig.EncodeOID (oid);
194                                 }
195                                 catch (CryptographicUnexpectedOperationException) {
196                                         string msg = Locale.GetText ("Invalid OID value '{0}'.", oid);
197                                         throw new ArgumentException ("findValue", msg);
198                                 }
199                                 break;
200                         case X509FindType.FindByKeyUsage:
201                                 try {
202                                         ku = (X509KeyUsageFlags) findValue;
203                                 }
204                                 catch (Exception e) {
205                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
206                                                 findValue.GetType (), "X509KeyUsageFlags");
207                                         throw new CryptographicException (msg, e);
208                                 }
209                                 break;
210                         case X509FindType.FindByTimeValid:
211                         case X509FindType.FindByTimeNotYetValid:
212                         case X509FindType.FindByTimeExpired:
213                                 try {
214                                         dt = (DateTime) findValue;
215                                 }
216                                 catch (Exception e) {
217                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
218                                                 findValue.GetType (), "X509DateTime");
219                                         throw new CryptographicException (msg,e );
220                                 }
221                                 break;
222                         default:
223                                 {
224                                         string msg = Locale.GetText ("Invalid find type '{0}'.", findType);
225                                         throw new CryptographicException (msg);
226                                 }
227                         }
228
229                         CultureInfo cinv = CultureInfo.InvariantCulture;
230                         X509Certificate2Collection results = new  X509Certificate2Collection ();
231                         foreach (X509Certificate2 x in InnerList) {
232                                 bool value_match = false;
233
234                                 switch (findType) {
235                                 case X509FindType.FindByThumbprint:
236                                         // works with Thumbprint, GetCertHashString in both normal (upper) and lower case
237                                         value_match = ((String.Compare (str, x.Thumbprint, true, cinv) == 0) ||
238                                                 (String.Compare (str, x.GetCertHashString (), true, cinv) == 0));
239                                         break;
240                                 case X509FindType.FindBySubjectName:
241                                         string sname = x.GetNameInfo (X509NameType.SimpleName, false);
242                                         value_match = (sname.IndexOf (str, StringComparison.InvariantCultureIgnoreCase) >= 0);
243                                         break;
244                                 case X509FindType.FindBySubjectDistinguishedName:
245                                         value_match = (String.Compare (str, x.Subject, true, cinv) == 0);
246                                         break;
247                                 case X509FindType.FindByIssuerName:
248                                         string iname = x.GetNameInfo (X509NameType.SimpleName, true);
249                                         value_match = (iname.IndexOf (str, StringComparison.InvariantCultureIgnoreCase) >= 0);
250                                         break;
251                                 case X509FindType.FindByIssuerDistinguishedName:
252                                         value_match = (String.Compare (str, x.Issuer, true, cinv) == 0);
253                                         break;
254                                 case X509FindType.FindBySerialNumber:
255                                         value_match = (String.Compare (str, x.SerialNumber, true, cinv) == 0);
256                                         break;
257                                 case X509FindType.FindByTemplateName:
258                                         // TODO - find a valid test case
259                                         break;
260                                 case X509FindType.FindBySubjectKeyIdentifier:
261                                         X509SubjectKeyIdentifierExtension ski = (x.Extensions ["2.5.29.14"] as X509SubjectKeyIdentifierExtension);
262                                         if (ski != null) {
263                                                 value_match = (String.Compare (str, ski.SubjectKeyIdentifier, true, cinv) == 0);
264                                         }
265                                         break;
266                                 case X509FindType.FindByApplicationPolicy:
267                                         // note: include when no extensions are present (even if v3)
268                                         value_match = (x.Extensions.Count == 0);
269                                         // TODO - find test case with extension
270                                         break;
271                                 case X509FindType.FindByCertificatePolicy:
272                                         // TODO - find test case with extension
273                                         break;
274                                 case X509FindType.FindByExtension:
275                                         value_match = (x.Extensions [oid] != null);
276                                         break;
277                                 case X509FindType.FindByKeyUsage:
278                                         X509KeyUsageExtension kue = (x.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
279                                         if (kue == null) {
280                                                 // key doesn't have any hard coded limitations
281                                                 // note: MS doesn't check for ExtendedKeyUsage
282                                                 value_match = true; 
283                                         } else {
284                                                 value_match = ((kue.KeyUsages & ku) == ku);
285                                         }
286                                         break;
287                                 case X509FindType.FindByTimeValid:
288                                         value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter));
289                                         break;
290                                 case X509FindType.FindByTimeNotYetValid:
291                                         value_match = (dt < x.NotBefore);
292                                         break;
293                                 case X509FindType.FindByTimeExpired:
294                                         value_match = (dt > x.NotAfter);
295                                         break;
296                                 }
297
298                                 if (!value_match)
299                                         continue;
300
301                                 if (validOnly) {
302                                         try {
303                                                 if (x.Verify ())
304                                                         results.Add (x);
305                                         }
306                                         catch {
307                                         }
308                                 } else {
309                                         results.Add (x);
310                                 }
311                         }
312                         return results;
313                 }
314
315                 public new X509Certificate2Enumerator GetEnumerator () 
316                 {
317                         return new X509Certificate2Enumerator (this);
318                 }
319
320                 [MonoTODO ("same limitations as X509Certificate2.Import")]
321                 public void Import (byte[] rawData) 
322                 {
323                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
324                         X509Certificate2 cert = new X509Certificate2 ();
325                         cert.Import (rawData);
326                         Add (cert);
327                 }
328
329                 [MonoTODO ("same limitations as X509Certificate2.Import")]
330                 public void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
331                 {
332                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
333                         X509Certificate2 cert = new X509Certificate2 ();
334                         cert.Import (rawData, password, keyStorageFlags);
335                         Add (cert);
336                 }
337
338                 [MonoTODO ("same limitations as X509Certificate2.Import")]
339                 public void Import (string fileName) 
340                 {
341                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
342                         X509Certificate2 cert = new X509Certificate2 ();
343                         cert.Import (fileName);
344                         Add (cert);
345                 }
346
347                 [MonoTODO ("same limitations as X509Certificate2.Import")]
348                 public void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) 
349                 {
350                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
351                         X509Certificate2 cert = new X509Certificate2 ();
352                         cert.Import (fileName, password, keyStorageFlags);
353                         Add (cert);
354                 }
355
356                 public void Insert (int index, X509Certificate2 certificate) 
357                 {
358                         if (certificate == null)
359                                 throw new ArgumentNullException ("certificate");
360                         if (index < 0)
361                                 throw new ArgumentOutOfRangeException ("negative index");
362                         if (index >= InnerList.Count)
363                                 throw new ArgumentOutOfRangeException ("index >= Count");
364
365                         InnerList.Insert (index, certificate);
366                 }
367
368                 public void Remove (X509Certificate2 certificate) 
369                 {
370                         if (certificate == null)
371                                 throw new ArgumentNullException ("certificate");
372
373                         for (int i=0; i < InnerList.Count; i++) {
374                                 X509Certificate c = (X509Certificate) InnerList [i];
375                                 if (c.Equals (certificate)) {
376                                         InnerList.RemoveAt (i);
377                                         // only first instance is removed
378                                         return;
379                                 }
380                         }
381                 }
382
383                 [MonoTODO ("Method isn't transactional (like documented)")]
384                 public void RemoveRange (X509Certificate2[] certificates)
385                 {
386                         if (certificates == null)
387                                 throw new ArgumentNullException ("certificate");
388
389                         foreach (X509Certificate2 x in certificates)
390                                 Remove (x);
391                 }
392
393                 [MonoTODO ("Method isn't transactional (like documented)")]
394                 public void RemoveRange (X509Certificate2Collection certificates) 
395                 {
396                         if (certificates == null)
397                                 throw new ArgumentNullException ("certificate");
398
399                         foreach (X509Certificate2 x in certificates)
400                                 Remove (x);
401                 }
402         }
403 }
404
405 #endif