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