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