[xbuild] Add 14.0 toolchain
[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                         SubjectAltNameExtension alt = null;
115                         string p12file = null;
116                         string p12pwd = null;
117                         X509Certificate issuerCertificate = null;
118
119                         Header();
120                         try {
121                                 int i=0;
122                                 while (i < args.Length) {
123                                         switch (args [i++]) {
124                                                 // Basic options
125                                                 case "-#":
126                                                         // Serial Number
127                                                         sn = BitConverter.GetBytes (Convert.ToInt32 (args [i++]));
128                                                         break;
129                                                 case "-n":
130                                                         // Subject Distinguish Name
131                                                         subject = args [i++];
132                                                         break;
133                                                 case "-$":
134                                                         // (authenticode) commercial or individual
135                                                         // CRITICAL KeyUsageRestriction extension
136                                                         // hash algorithm
137                                                         string usageRestriction = args [i++].ToLower ();
138                                                         switch (usageRestriction) {
139                                                                 case "commercial":
140                                                                 case "individual":
141                                                                         Console.WriteLine ("WARNING: Unsupported deprecated certification extension KeyUsageRestriction not included");
142 //                                                                      Console.WriteLine ("WARNING: ExtendedKeyUsage for codesigning has been included.");
143                                                                         break;
144                                                                 default:
145                                                                         Console.WriteLine ("Unsupported restriction " + usageRestriction);
146                                                                         return -1;
147                                                         }
148                                                         break;
149                                                 // Extended Options
150                                                 case "-a":
151                                                         // hash algorithm
152                                                         switch (args [i++].ToLower ()) {
153                                                                 case "sha1":
154                                                                         hashName = "SHA1";
155                                                                         break;
156                                                                 case "md5":
157                                                                         Console.WriteLine ("WARNING: MD5 is no more safe for this usage.");
158                                                                         hashName = "MD5";
159                                                                         break;
160                                                                 default:
161                                                                         Console.WriteLine ("Unsupported hash algorithm");
162                                                                         break;
163                                                         }
164                                                         break;
165                                                 case "-b":
166                                                         // Validity / notBefore
167                                                         notBefore = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
168                                                         break;
169                                                 case "-cy":
170                                                         // basic constraints - autority or end-entity
171                                                         switch (args [i++].ToLower ()) {
172                                                                 case "authority":
173                                                                         if (bce == null)
174                                                                                 bce = new BasicConstraintsExtension ();
175                                                                         bce.CertificateAuthority = true;
176                                                                         break;
177                                                                 case "end":
178                                                                         // do not include extension
179                                                                         bce = null;
180                                                                         break;
181                                                                 case "both":
182                                                                         Console.WriteLine ("ERROR: No more supported in X.509");
183                                                                         return -1;
184                                                                 default:
185                                                                         Console.WriteLine ("Unsupported certificate type");
186                                                                         return -1;
187                                                         }
188                                                         break;
189                                                 case "-d":
190                                                         // CN private extension ?
191                                                         Console.WriteLine ("Unsupported option");
192                                                         break;
193                                                 case "-e":
194                                                         // Validity / notAfter
195                                                         notAfter = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
196                                                         break;
197                                                 case "-eku":
198                                                         // extendedKeyUsage extension
199                                                         char[] sep = { ',' };
200                                                         string[] purposes = args [i++].Split (sep);
201                                                         if (eku == null)
202                                                                 eku = new ExtendedKeyUsageExtension ();
203                                                         foreach (string purpose in purposes) {
204                                                                 eku.KeyPurpose.Add (purpose);
205                                                         }
206                                                         break;
207                                                 case "-h":
208                                                         // pathLength (basicConstraints)
209                                                         // MS use an old basicConstrains (2.5.29.10) which 
210                                                         // allows both CA and End-Entity. This is no
211                                                         // more supported with 2.5.29.19.
212                                                         if (bce == null) {
213                                                                 bce = new BasicConstraintsExtension ();
214                                                                 bce.CertificateAuthority = true;
215                                                         }
216                                                         bce.PathLenConstraint = Convert.ToInt32 (args [i++]);
217                                                         break;
218                                                 case "-alt":
219                                                         if (alt == null) {
220                                                                 string [] dnsNames = File.ReadAllLines (args [i++]);
221                                                                 alt = new SubjectAltNameExtension (null, dnsNames, null, null);
222                                                         }
223                                                         break;
224                                                 case "-ic":
225                                                         issuerCertificate = LoadCertificate (args [i++]);
226                                                         issuer = issuerCertificate.SubjectName;
227                                                         break;
228                                                 case "-in":
229                                                         issuer = args [i++];
230                                                         break;
231                                                 case "-iv":
232                                                         // TODO password
233                                                         PrivateKey pvk = PrivateKey.CreateFromFile (args [i++]);
234                                                         issuerKey = pvk.RSA;
235                                                         break;
236                                                 case "-l":
237                                                         // link (URL)
238                                                         // spcSpAgencyInfo private extension
239                                                         Console.WriteLine ("Unsupported option");
240                                                         break;
241                                                 case "-m":
242                                                         // validity period (in months)
243                                                         notAfter = notBefore.AddMonths (Convert.ToInt32 (args [i++]));
244                                                         break;
245                                                 case "-nscp":
246                                                         // Netscape's private extensions - NetscapeCertType
247                                                         // BasicContraints - End Entity
248                                                         Console.WriteLine ("Unsupported option");
249                                                         break;
250                                                 case "-r":
251                                                         selfSigned = true;
252                                                         break;
253                                                 case "-sc":
254                                                         // subject certificate ? renew ?
255                                                         Console.WriteLine ("Unsupported option");
256                                                         break;
257                                                 // Issuer CspParameters options
258                                                 case "-ik":
259                                                         issuerParams.KeyContainerName = args [i++];
260                                                         break;
261                                                 case "-iky":
262                                                         // select a key in the provider
263                                                         string ikn = args [i++].ToLower ();
264                                                         switch (ikn) {
265                                                                 case "signature":
266                                                                         issuerParams.KeyNumber = 0;
267                                                                         break;
268                                                                 case "exchange":
269                                                                         issuerParams.KeyNumber = 1;
270                                                                         break;
271                                                                 default:
272                                                                         issuerParams.KeyNumber = Convert.ToInt32 (ikn);
273                                                                         break;
274                                                         }
275                                                         break;
276                                                 case "-ip":
277                                                         issuerParams.ProviderName = args [i++];
278                                                         break;
279                                                 case "-ir":
280                                                         switch (args [i++].ToLower ()) {
281                                                                 case "localmachine":
282                                                                         issuerParams.Flags = CspProviderFlags.UseMachineKeyStore;
283                                                                         break;
284                                                                 case "currentuser":
285                                                                         issuerParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
286                                                                         break;
287                                                                 default:
288                                                                         Console.WriteLine ("Unknown key store for issuer");
289                                                                         return -1;
290                                                         }
291                                                         break;
292                                                 case "-is":
293                                                         Console.WriteLine ("Unsupported option");
294                                                         return -1;
295                                                 case "-iy":
296                                                         issuerParams.ProviderType = Convert.ToInt32 (args [i++]);
297                                                         break;
298                                                 // Subject CspParameters Options
299                                                 case "-sk":
300                                                         subjectParams.KeyContainerName = args [i++];
301                                                         break;
302                                                 case "-sky":
303                                                         // select a key in the provider
304                                                         string skn = args [i++].ToLower ();
305                                                         switch (skn) {
306                                                                 case "signature":
307                                                                         subjectParams.KeyNumber = 0;
308                                                                         break;
309                                                                 case "exchange":
310                                                                         subjectParams.KeyNumber = 1;
311                                                                         break;
312                                                                 default:
313                                                                         subjectParams.KeyNumber = Convert.ToInt32 (skn);
314                                                                         break;
315                                                         }
316                                                         break;
317                                                 case "-sp":
318                                                         subjectParams.ProviderName = args [i++];
319                                                         break;
320                                                 case "-sr":
321                                                         switch (args [i++].ToLower ()) {
322                                                                 case "localmachine":
323                                                                         subjectParams.Flags = CspProviderFlags.UseMachineKeyStore;
324                                                                         break;
325                                                                 case "currentuser":
326                                                                         subjectParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
327                                                                         break;
328                                                                 default:
329                                                                         Console.WriteLine ("Unknown key store for subject");
330                                                                         return -1;
331                                                         }
332                                                         break;
333                                                 case "-ss":
334                                                         Console.WriteLine ("Unsupported option");
335                                                         return -1;
336                                                 case "-sv":
337                                                         string pvkFile = args [i++];
338                                                         if (File.Exists (pvkFile)) {
339                                                                 PrivateKey key = PrivateKey.CreateFromFile (pvkFile);
340                                                                 subjectKey = key.RSA;
341                                                         }
342                                                         else {
343                                                                 PrivateKey key = new PrivateKey ();
344                                                                 key.RSA = subjectKey;
345                                                                 key.Save (pvkFile);
346                                                         }
347                                                         break;
348                                                 case "-sy":
349                                                         subjectParams.ProviderType = Convert.ToInt32 (args [i++]);
350                                                         break;
351                                                 // Mono Specific Options
352                                                 case "-p12":
353                                                         p12file = args [i++];
354                                                         p12pwd = args [i++];
355                                                         break;
356                                                 // Other options
357                                                 case "-?":
358                                                         Help ();
359                                                         return 0;
360                                                 case "-!":
361                                                         ExtendedHelp ();
362                                                         return 0;
363                                                 default:
364                                                         if (i != args.Length) {
365                                                                 Console.WriteLine ("ERROR: Unknown parameter");
366                                                                 Help ();
367                                                                 return -1;
368                                                         }
369                                                         break;
370                                         }
371                                 }
372
373                                 // serial number MUST be positive
374                                 if ((sn [0] & 0x80) == 0x80)
375                                         sn [0] -= 0x80;
376
377                                 if (selfSigned) {
378                                         if (subject != defaultSubject) {
379                                                 issuer = subject;
380                                                 issuerKey = subjectKey;
381                                         }
382                                         else {
383                                                 subject = issuer;
384                                                 subjectKey = issuerKey;
385                                         }
386                                 }
387
388                                 if (subject == null)
389                                         throw new Exception ("Missing Subject Name");
390
391                                 X509CertificateBuilder cb = new X509CertificateBuilder (3);
392                                 cb.SerialNumber = sn;
393                                 cb.IssuerName = issuer;
394                                 cb.NotBefore = notBefore;
395                                 cb.NotAfter = notAfter;
396                                 cb.SubjectName = subject;
397                                 cb.SubjectPublicKey = subjectKey;
398                                 // extensions
399                                 if (bce != null)
400                                         cb.Extensions.Add (bce);
401                                 if (eku != null)
402                                         cb.Extensions.Add (eku);
403                                 if (alt != null)
404                                         cb.Extensions.Add (alt);
405                                 // signature
406                                 cb.Hash = hashName;
407                                 byte[] rawcert = cb.Sign (issuerKey);
408
409                                 if (p12file == null) {
410                                         WriteCertificate (fileName, rawcert);
411                                 } else {
412                                         PKCS12 p12 = new PKCS12 ();
413                                         p12.Password = p12pwd;
414
415                                         ArrayList list = new ArrayList ();
416                                         // we use a fixed array to avoid endianess issues 
417                                         // (in case some tools requires the ID to be 1).
418                                         list.Add (new byte [4] { 1, 0, 0, 0 });
419                                         Hashtable attributes = new Hashtable (1);
420                                         attributes.Add (PKCS9.localKeyId, list);
421
422                                         p12.AddCertificate (new X509Certificate (rawcert), attributes);
423                                         if (issuerCertificate != null)
424                                                 p12.AddCertificate (issuerCertificate);
425                                         p12.AddPkcs8ShroudedKeyBag (subjectKey, attributes);
426                                         p12.SaveToFile (p12file);
427                                 }
428                                 Console.WriteLine ("Success");
429                                 return 0;
430                         }
431                         catch (Exception e) {
432                                 Console.WriteLine ("ERROR: " + e.ToString ());
433                                 Help ();
434                         }
435                         return 1;
436                 }
437         }
438 }