2005-10-20 Miguel de Icaza <miguel@novell.com>
[mono.git] / mcs / tools / security / makecert.cs
1 //
2 // makecert.cs: makecert clone tool
3 //
4 // Author:
5 //      Sebastien Pouliot <sebastien@ximian.com>
6 //
7 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
9 //
10
11 using System;
12 using System.Collections;
13 using System.Globalization;
14 using System.IO;
15 using System.Reflection;
16 using System.Security.Cryptography;
17
18 using Mono.Security.Authenticode;
19 using Mono.Security.X509;
20 using Mono.Security.X509.Extensions;
21
22 [assembly: AssemblyTitle("Mono MakeCert")]
23 [assembly: AssemblyDescription("X.509 Certificate Builder")]
24
25 namespace Mono.Tools {
26
27         class MakeCert {
28
29                 static private void Header () 
30                 {
31                         Console.WriteLine (new AssemblyInfo ().ToString ());
32                 }
33
34                 static private void Help () 
35                 {
36                         Console.WriteLine ("Usage: makecert [options] certificate{0}", Environment.NewLine);
37                         Console.WriteLine (" -# num{0}\tCertificate serial number", Environment.NewLine);
38                         Console.WriteLine (" -n dn{0}\tSubject Distinguished Name", Environment.NewLine);
39                         Console.WriteLine (" -in dn{0}\tIssuer Distinguished Name", Environment.NewLine);
40                         Console.WriteLine (" -r{0}\tCreate a self-signed (root) certificate", Environment.NewLine);
41                         Console.WriteLine (" -sv pkvfile{0}\tPrivate key file (.PVK) for the subject (created if missing)", Environment.NewLine);
42                         Console.WriteLine (" -iv pvkfile{0}\tPrivate key file (.PVK) for the issuer", Environment.NewLine);
43                         Console.WriteLine (" -ic certfile{0}\tExtract the issuer's name from the specified certificate", Environment.NewLine);
44                         Console.WriteLine (" -?{0}\thelp (display this help message)", Environment.NewLine);
45                         Console.WriteLine (" -!{0}\textended help (for advanced options)", Environment.NewLine);
46                 }
47
48                 static private void ExtendedHelp () 
49                 {
50                         Console.WriteLine ("Usage: makecert [options] certificate{0}", Environment.NewLine);
51                         Console.WriteLine (" -a hash\tSelect hash algorithm. Only MD5 and SHA1 (default) are supported.");
52                         Console.WriteLine (" -b date\tThe date since when the certificate is valid (notBefore).");
53                         Console.WriteLine (" -cy [authority|end]\tBasic constraints. Select Authority or End-Entity certificate.");
54                         Console.WriteLine (" -e date\tThe date until when the certificate is valid (notAfter).");
55                         Console.WriteLine (" -eku oid[,oid]\tAdd some extended key usage OID to the certificate.");
56                         Console.WriteLine (" -h number\tAdd a path length restriction to the certificate chain.");
57                         Console.WriteLine (" -in name\tTake the issuer's name from the specified parameter.");
58                         Console.WriteLine (" -m number\tCertificate validity period (in months).");
59                         Console.WriteLine (" -p12 pkcs12file password\tCreate a new PKCS#12 file with the specified password.");
60                         Console.WriteLine (" -?\thelp (display basic message)");
61                 }
62
63                 static X509Certificate LoadCertificate (string filename) 
64                 {
65                         FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);
66                         byte[] rawcert = new byte [fs.Length];
67                         fs.Read (rawcert, 0, rawcert.Length);
68                         fs.Close ();
69                         return new X509Certificate (rawcert);
70                 }
71
72                 static void WriteCertificate (string filename, byte[] rawcert) 
73                 {
74                         FileStream fs = File.Open (filename, FileMode.Create, FileAccess.Write);
75                         fs.Write (rawcert, 0, rawcert.Length);
76                         fs.Close ();
77                 }
78
79                 static string MonoTestRootAgency = "<RSAKeyValue><Modulus>v/4nALBxCE+9JgEC0LnDUvKh6e96PwTpN4Rj+vWnqKT7IAp1iK/JjuqvAg6DQ2vTfv0dTlqffmHH51OyioprcT5nzxcSTsZb/9jcHScG0s3/FRIWnXeLk/fgm7mSYhjUaHNI0m1/NTTktipicjKxo71hGIg9qucCWnDum+Krh/k=</Modulus><Exponent>AQAB</Exponent><P>9jbKxMXEruW2CfZrzhxtull4O8P47+mNsEL+9gf9QsRO1jJ77C+jmzfU6zbzjf8+ViK+q62tCMdC1ZzulwdpXQ==</P><Q>x5+p198l1PkK0Ga2mRh0SIYSykENpY2aLXoyZD/iUpKYAvATm0/wvKNrE4dKJyPCA+y3hfTdgVag+SP9avvDTQ==</Q><DP>ISSjCvXsUfbOGG05eddN1gXxL2pj+jegQRfjpk7RAsnWKvNExzhqd5x+ZuNQyc6QH5wxun54inP4RTUI0P/IaQ==</DP><DQ>R815VQmR3RIbPqzDXzv5j6CSH6fYlcTiQRtkBsUnzhWmkd/y3XmamO+a8zJFjOCCx9CcjpVuGziivBqi65lVPQ==</DQ><InverseQ>iYiu0KwMWI/dyqN3RJYUzuuLj02/oTD1pYpwo2rvNCXU1Q5VscOeu2DpNg1gWqI+1RrRCsEoaTNzXB1xtKNlSw==</InverseQ><D>nIfh1LYF8fjRBgMdAH/zt9UKHWiaCnc+jXzq5tkR8HVSKTVdzitD8bl1JgAfFQD8VjSXiCJqluexy/B5SGrCXQ49c78NIQj0hD+J13Y8/E0fUbW1QYbhj6Ff7oHyhaYe1WOQfkp2t/h+llHOdt1HRf7bt7dUknYp7m8bQKGxoYE=</D></RSAKeyValue>";
80
81                 static string defaultIssuer = "CN=Mono Test Root Agency";
82                 static string defaultSubject = "CN=Poupou's-Software-Factory";
83
84                 [STAThread]
85                 static int Main (string[] args)
86                 {
87                         if (args.Length < 1) {
88                                 Header ();
89                                 Console.WriteLine ("ERROR: Missing output filename {0}", Environment.NewLine);
90                                 Help ();
91                                 return -1;
92                         }
93
94                         string fileName = args [args.Length - 1];
95
96                         // default values
97                         byte[] sn = Guid.NewGuid ().ToByteArray ();
98                         string subject = defaultSubject;
99                         string issuer = defaultIssuer;
100                         DateTime notBefore = DateTime.Now;
101                         DateTime notAfter = new DateTime (643445675990000000); // 12/31/2039 23:59:59Z
102
103                         RSA issuerKey = (RSA)RSA.Create ();
104                         issuerKey.FromXmlString (MonoTestRootAgency);
105                         RSA subjectKey = (RSA)RSA.Create ();
106
107                         bool selfSigned = false;
108                         string hashName = "SHA1";
109
110                         CspParameters subjectParams = new CspParameters ();
111                         CspParameters issuerParams = new CspParameters ();
112                         BasicConstraintsExtension bce = null;
113                         ExtendedKeyUsageExtension eku = null;
114                         string p12file = null;
115                         string p12pwd = null;
116                         X509Certificate issuerCertificate = null;
117
118                         Header();
119                         try {
120                                 int i=0;
121                                 while (i < args.Length) {
122                                         switch (args [i++]) {
123                                                 // Basic options
124                                                 case "-#":
125                                                         // Serial Number
126                                                         sn = BitConverter.GetBytes (Convert.ToInt32 (args [i++]));
127                                                         break;
128                                                 case "-n":
129                                                         // Subject Distinguish Name
130                                                         subject = args [i++];
131                                                         break;
132                                                 case "-$":
133                                                         // (authenticode) commercial or individual
134                                                         // CRITICAL KeyUsageRestriction extension
135                                                         // hash algorithm
136                                                         string usageRestriction = args [i++].ToLower ();
137                                                         switch (usageRestriction) {
138                                                                 case "commercial":
139                                                                 case "individual":
140                                                                         Console.WriteLine ("WARNING: Unsupported deprecated certification extension KeyUsageRestriction not included");
141 //                                                                      Console.WriteLine ("WARNING: ExtendedKeyUsage for codesigning has been included.");
142                                                                         break;
143                                                                 default:
144                                                                         Console.WriteLine ("Unsupported restriction " + usageRestriction);
145                                                                         return -1;
146                                                         }
147                                                         break;
148                                                 // Extended Options
149                                                 case "-a":
150                                                         // hash algorithm
151                                                         switch (args [i++].ToLower ()) {
152                                                                 case "sha1":
153                                                                         hashName = "SHA1";
154                                                                         break;
155                                                                 case "md5":
156                                                                         Console.WriteLine ("WARNING: MD5 is no more safe for this usage.");
157                                                                         hashName = "MD5";
158                                                                         break;
159                                                                 default:
160                                                                         Console.WriteLine ("Unsupported hash algorithm");
161                                                                         break;
162                                                         }
163                                                         break;
164                                                 case "-b":
165                                                         // Validity / notBefore
166                                                         notBefore = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
167                                                         break;
168                                                 case "-cy":
169                                                         // basic constraints - autority or end-entity
170                                                         switch (args [i++].ToLower ()) {
171                                                                 case "authority":
172                                                                         if (bce == null)
173                                                                                 bce = new BasicConstraintsExtension ();
174                                                                         bce.CertificateAuthority = true;
175                                                                         break;
176                                                                 case "end":
177                                                                         // do not include extension
178                                                                         bce = null;
179                                                                         break;
180                                                                 case "both":
181                                                                         Console.WriteLine ("ERROR: No more supported in X.509");
182                                                                         return -1;
183                                                                 default:
184                                                                         Console.WriteLine ("Unsupported certificate type");
185                                                                         return -1;
186                                                         }
187                                                         break;
188                                                 case "-d":
189                                                         // CN private extension ?
190                                                         Console.WriteLine ("Unsupported option");
191                                                         break;
192                                                 case "-e":
193                                                         // Validity / notAfter
194                                                         notAfter = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
195                                                         break;
196                                                 case "-eku":
197                                                         // extendedKeyUsage extension
198                                                         char[] sep = { ',' };
199                                                         string[] purposes = args [i++].Split (sep);
200                                                         if (eku == null)
201                                                                 eku = new ExtendedKeyUsageExtension ();
202                                                         foreach (string purpose in purposes) {
203                                                                 eku.KeyPurpose.Add (purpose);
204                                                         }
205                                                         break;
206                                                 case "-h":
207                                                         // pathLength (basicConstraints)
208                                                         // MS use an old basicConstrains (2.5.29.10) which 
209                                                         // allows both CA and End-Entity. This is no
210                                                         // more supported with 2.5.29.19.
211                                                         if (bce == null) {
212                                                                 bce = new BasicConstraintsExtension ();
213                                                                 bce.CertificateAuthority = true;
214                                                         }
215                                                         bce.PathLenConstraint = Convert.ToInt32 (args [i++]);
216                                                         break;
217                                                 case "-ic":
218                                                         issuerCertificate = LoadCertificate (args [i++]);
219                                                         issuer = issuerCertificate.SubjectName;
220                                                         break;
221                                                 case "-in":
222                                                         issuer = args [i++];
223                                                         break;
224                                                 case "-iv":
225                                                         // TODO password
226                                                         PrivateKey pvk = PrivateKey.CreateFromFile (args [i++]);
227                                                         issuerKey = pvk.RSA;
228                                                         break;
229                                                 case "-l":
230                                                         // link (URL)
231                                                         // spcSpAgencyInfo private extension
232                                                         Console.WriteLine ("Unsupported option");
233                                                         break;
234                                                 case "-m":
235                                                         // validity period (in months)
236                                                         notAfter = notBefore.AddMonths (Convert.ToInt32 (args [i++]));
237                                                         break;
238                                                 case "-nscp":
239                                                         // Netscape's private extensions - NetscapeCertType
240                                                         // BasicContraints - End Entity
241                                                         Console.WriteLine ("Unsupported option");
242                                                         break;
243                                                 case "-r":
244                                                         selfSigned = true;
245                                                         break;
246                                                 case "-sc":
247                                                         // subject certificate ? renew ?
248                                                         Console.WriteLine ("Unsupported option");
249                                                         break;
250                                                 // Issuer CspParameters options
251                                                 case "-ik":
252                                                         issuerParams.KeyContainerName = args [i++];
253                                                         break;
254                                                 case "-iky":
255                                                         // select a key in the provider
256                                                         string ikn = args [i++].ToLower ();
257                                                         switch (ikn) {
258                                                                 case "signature":
259                                                                         issuerParams.KeyNumber = 0;
260                                                                         break;
261                                                                 case "exchange":
262                                                                         issuerParams.KeyNumber = 1;
263                                                                         break;
264                                                                 default:
265                                                                         issuerParams.KeyNumber = Convert.ToInt32 (ikn);
266                                                                         break;
267                                                         }
268                                                         break;
269                                                 case "-ip":
270                                                         issuerParams.ProviderName = args [i++];
271                                                         break;
272                                                 case "-ir":
273                                                         switch (args [i++].ToLower ()) {
274                                                                 case "localmachine":
275                                                                         issuerParams.Flags = CspProviderFlags.UseMachineKeyStore;
276                                                                         break;
277                                                                 case "currentuser":
278                                                                         issuerParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
279                                                                         break;
280                                                                 default:
281                                                                         Console.WriteLine ("Unknown key store for issuer");
282                                                                         return -1;
283                                                         }
284                                                         break;
285                                                 case "-is":
286                                                         Console.WriteLine ("Unsupported option");
287                                                         return -1;
288                                                 case "-iy":
289                                                         issuerParams.ProviderType = Convert.ToInt32 (args [i++]);
290                                                         break;
291                                                 // Subject CspParameters Options
292                                                 case "-sk":
293                                                         subjectParams.KeyContainerName = args [i++];
294                                                         break;
295                                                 case "-sky":
296                                                         // select a key in the provider
297                                                         string skn = args [i++].ToLower ();
298                                                         switch (skn) {
299                                                                 case "signature":
300                                                                         subjectParams.KeyNumber = 0;
301                                                                         break;
302                                                                 case "exchange":
303                                                                         subjectParams.KeyNumber = 1;
304                                                                         break;
305                                                                 default:
306                                                                         subjectParams.KeyNumber = Convert.ToInt32 (skn);
307                                                                         break;
308                                                         }
309                                                         break;
310                                                 case "-sp":
311                                                         subjectParams.ProviderName = args [i++];
312                                                         break;
313                                                 case "-sr":
314                                                         switch (args [i++].ToLower ()) {
315                                                                 case "localmachine":
316                                                                         subjectParams.Flags = CspProviderFlags.UseMachineKeyStore;
317                                                                         break;
318                                                                 case "currentuser":
319                                                                         subjectParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
320                                                                         break;
321                                                                 default:
322                                                                         Console.WriteLine ("Unknown key store for subject");
323                                                                         return -1;
324                                                         }
325                                                         break;
326                                                 case "-ss":
327                                                         Console.WriteLine ("Unsupported option");
328                                                         return -1;
329                                                 case "-sv":
330                                                         string pvkFile = args [i++];
331                                                         if (File.Exists (pvkFile)) {
332                                                                 PrivateKey key = PrivateKey.CreateFromFile (pvkFile);
333                                                                 subjectKey = key.RSA;
334                                                         }
335                                                         else {
336                                                                 PrivateKey key = new PrivateKey ();
337                                                                 key.RSA = subjectKey;
338                                                                 key.Save (pvkFile);
339                                                         }
340                                                         break;
341                                                 case "-sy":
342                                                         subjectParams.ProviderType = Convert.ToInt32 (args [i++]);
343                                                         break;
344                                                 // Mono Specific Options
345                                                 case "-p12":
346                                                         p12file = args [i++];
347                                                         p12pwd = args [i++];
348                                                         break;
349                                                 // Other options
350                                                 case "-?":
351                                                         Help ();
352                                                         return 0;
353                                                 case "-!":
354                                                         ExtendedHelp ();
355                                                         return 0;
356                                                 default:
357                                                         if (i != args.Length) {
358                                                                 Console.WriteLine ("ERROR: Unknown parameter");
359                                                                 Help ();
360                                                                 return -1;
361                                                         }
362                                                         break;
363                                         }
364                                 }
365
366                                 // serial number MUST be positive
367                                 if ((sn [0] & 0x80) == 0x80)
368                                         sn [0] -= 0x80;
369
370                                 if (selfSigned) {
371                                         if (subject != defaultSubject) {
372                                                 issuer = subject;
373                                                 issuerKey = subjectKey;
374                                         }
375                                         else {
376                                                 subject = issuer;
377                                                 subjectKey = issuerKey;
378                                         }
379                                 }
380
381                                 if (subject == null)
382                                         throw new Exception ("Missing Subject Name");
383
384                                 X509CertificateBuilder cb = new X509CertificateBuilder (3);
385                                 cb.SerialNumber = sn;
386                                 cb.IssuerName = issuer;
387                                 cb.NotBefore = notBefore;
388                                 cb.NotAfter = notAfter;
389                                 cb.SubjectName = subject;
390                                 cb.SubjectPublicKey = subjectKey;
391                                 // extensions
392                                 if (bce != null)
393                                         cb.Extensions.Add (bce);
394                                 if (eku != null)
395                                         cb.Extensions.Add (eku);
396                                 // signature
397                                 cb.Hash = hashName;
398                                 byte[] rawcert = cb.Sign (issuerKey);
399
400                                 if (p12file == null) {
401                                         WriteCertificate (fileName, rawcert);
402                                 } else {
403                                         PKCS12 p12 = new PKCS12 ();
404                                         p12.Password = p12pwd;
405
406                                         ArrayList list = new ArrayList ();
407                                         // we use a fixed array to avoid endianess issues 
408                                         // (in case some tools requires the ID to be 1).
409                                         list.Add (new byte [4] { 1, 0, 0, 0 });
410                                         Hashtable attributes = new Hashtable (1);
411                                         attributes.Add (PKCS9.localKeyId, list);
412
413                                         p12.AddCertificate (new X509Certificate (rawcert), attributes);
414                                         if (issuerCertificate != null)
415                                                 p12.AddCertificate (issuerCertificate);
416                                         p12.AddPkcs8ShroudedKeyBag (subjectKey, attributes);
417                                         p12.SaveToFile (p12file);
418                                 }
419                                 Console.WriteLine ("Success");
420                                 return 0;
421                         }
422                         catch (Exception e) {
423                                 Console.WriteLine ("ERROR: " + e.ToString ());
424                                 Help ();
425                         }
426                         return 1;
427                 }
428         }
429 }