Debian Codegraph @

ssl-proxies/src/main/java/org/globus/tools/GridCertRequest.java

raw
1 /**
2 * Copyright (c) 2003, National Research Council of Canada
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to
7 * deal in the Software without restriction, including without limitation the
8 * rights to use, copy, modify, merge, publish, distribute, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to
10 * do so, subject to the following conditions:
11 *
12 * The above copyright notice(s) and this licence appear in all copies of the
13 * Software or substantial portions of the Software, and that both the above
14 * copyright notice(s) and this license appear in supporting documentation.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 * NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE
20 * COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE
21 * FOR ANY CLAIM, OR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL
22 * DAMAGES, OR ANY DAMAGES WHATSOEVER (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWSOEVER
25 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN AN ACTION OF
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27 * OTHERWISE) ARISING IN ANY WAY OUT OF OR IN CONNECTION WITH THE
28 * SOFTWARE OR THE USE OF THE SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 *
31 * Except as contained in this notice, the name of a copyright holder shall NOT
32 * be used in advertising or otherwise to promote the sale, use or other
33 * dealings in this Software without specific prior written authorization.
34 * Title to copyright in this software and any associated documentation will at
35 * all times remain with copyright holders.
36 */
37 package org.globus.tools;
38
39 import java.io.File;
40 import java.io.FileOutputStream;
41 import java.io.PrintStream;
42 import java.security.KeyPair;
43 import java.security.KeyPairGenerator;
44 import java.security.PrivateKey;
45 import java.security.PublicKey;
46
47 import org.bouncycastle.asn1.DERSet;
48 import org.bouncycastle.asn1.x509.X509Name;
49 import org.bouncycastle.jce.PKCS10CertificationRequest;
50 import org.bouncycastle.util.encoders.Base64;
51
52 import org.globus.common.Version;
53 import org.globus.common.CoGProperties;
54 import org.globus.gsi.CertUtil;
55 import org.globus.gsi.OpenSSLKey;
56 import org.globus.gsi.bc.BouncyCastleOpenSSLKey;
57 import org.globus.gsi.bc.X509NameHelper;
58 import org.globus.util.PEMUtils;
59 import org.globus.util.Util;
60 import org.globus.util.ConfigUtil;
61
62 /**
63 * GridCertRequest Command Line Client.
64 *
65 * @author <a href="mailto:[email protected]">Jean-Claude Cote</a>
66 */
67 public final class GridCertRequest {
68
69 public static final String USAGE =
70 "\n"
71 + "\ngrid-cert-request [-help] [ options ...]"
72 + "\n"
73 + "\n Example Usage:"
74 + "\n"
75 + "\n Creating a user certifcate:"
76 + "\n grid-cert-request"
77 + "\n"
78 + "\n Creating a host or gatekeeper certifcate:"
79 + "\n grid-cert-request -host [my.host.fqdn]"
80 + "\n"
81 + "\n Creating a LDAP server certificate:"
82 + "\n grid-cert-request -service ldap -host [my.host.fqdn]"
83 + "\n"
84 + "\n Options:"
85 + "\n"
86 + "\n -version : Display version"
87 + "\n -?, -h, -help, : Display usage"
88 + "\n -usage"
89 + "\n -cn <name>, : Common name of the user"
90 + "\n -commonname <name>"
91 + "\n -service <service> : Create certificate for a service. Requires"
92 + "\n the -host option and implies that the generated"
93 + "\n key will not be password protected (ie implies -nopw)."
94 + "\n -host <FQDN> : Create certificate for a host named <FQDN>"
95 + "\n -dir <directory> : Changes the directory the private key and certificate"
96 + "\n request will be placed in. By default user certificates"
97 + "\n are placed in " + System.getProperty("user.home") + File.separator + ".globus"
98 + "\n directory. On Unix machines, host certificates are"
99 + "\n placed in /etc/grid-security directory and service"
100 + "\n certificates are placed in /etc/grid-security/<service>."
101 + "\n On Windows machines they are placed in the same"
102 + "\n location as the user certificates."
103 + "\n -prefix <prefix> : Causes the generated files to be named"
104 + "\n <prefix>cert.pem, <prefix>key.pem and"
105 + "\n <prefix>cert_request.pem"
106 + "\n -nopw, : Create certificate without a password"
107 + "\n -nodes,"
108 + "\n -nopassphrase,"
109 + "\n -verbose : Don't clear the screen <<Not used>>"
110 + "\n -int[eractive] : Prompt user for each component of the DN"
111 + "\n -force : Overwrites preexisting certifictes"
112 + "\n -caEmail <address> : CA email address, if request is to be mailed to CA"
113 + "\n -orgBaseDN <dn> : The base DN of this organization (in LDAP format)";
114
115 private static final String MESSAGE =
116 "A certificate request and private key will be created."
117 + "\nYou will be asked to enter a PEM pass phrase."
118 + "\nThis pass phrase is akin to your account password,"
119 + "\nand is used to protect your key file."
120 + "\nIf you forget your pass phrase, you will need to"
121 + "\nobtain a new certificate.\n";
122
123 private static String caEmail = null;
124
125 private static String cn = null;
126
127 private static boolean interactive = false;
128 private static boolean verbose = false;
129
130 private static boolean noPswd = false;
131 private static String dir = null;
132 private static boolean force = false;
133 private static String prefix = null;
134 private static boolean debug = false;
135
136 public static void main(String[] args) {
137
138 parseCmdLine(args);
139
140 File certDir = new File(dir);
141
142 // Create dir if does not exists.
143 if (!certDir.exists()) {
144 // if fails exit
145 if (!certDir.mkdirs()) {
146 exit("Unable to create " + certDir + " directory.", 1);
147 }
148 }
149
150 // Make sure it's a directory.
151 if (!certDir.isDirectory()) {
152 exit("The directory " + certDir + " specified is not a directory.", 2);
153 }
154
155 // Make sure we can write to it.
156 if (!certDir.canWrite()) {
157 exit("Can't write to " + certDir, 3);
158 }
159
160 File certFile = new File(certDir, prefix + "cert.pem");
161 File keyFile = new File(certDir, prefix + "key.pem");
162 File certRequestFile = new File(certDir, prefix + "cert_request.pem");
163
164 // Check not to overwrite any of these files.
165 if (!force) {
166 boolean fileExists = false;
167 if (keyFile.exists()) {
168 System.err.println(keyFile + " exists");
169 fileExists = true;
170 }
171 if (certFile.exists()) {
172 System.err.println(certFile + " exists");
173 fileExists = true;
174 }
175 if (certRequestFile.exists()) {
176 System.err.println(certRequestFile + " exists");
177 fileExists = true;
178 }
179
180 if (fileExists) {
181 exit("If you wish to overwrite, run the script again with -force.", 4);
182 }
183 }
184
185 String password = null;
186
187 if (!noPswd) {
188 // Get password from user.
189 int attempts = 0;
190 boolean passOK = false;
191
192 System.out.println(MESSAGE);
193
194 while (attempts < 3) {
195
196 password = Util.getPrivateInput("Enter PEM pass phrase: ");
197 if (password.length() < 4) {
198 System.out.println("Phrase is too short, needs to be at least 4 chars");
199 attempts++;
200 continue;
201 }
202
203 String password2 =
204 Util.getPrivateInput("Verifying password - Enter PEM pass phrase: ");
205
206 if (password.compareTo(password2) == 0) {
207 passOK = true;
208 break;
209 } else {
210 System.out.println("Verify failure");
211 attempts++;
212 }
213 }
214
215 if (!passOK) {
216 exit("Too many attempts", 5);
217 }
218 }
219
220 // Generate cert request.
221 try {
222 genCertificateRequest(cn,
223 caEmail,
224 password,
225 keyFile,
226 certFile,
227 certRequestFile);
228 } catch (Exception e) {
229 System.err.println("Error generating cert request: " +
230 e.getMessage());
231 if (debug) {
232 e.printStackTrace();
233 }
234 System.exit(6);
235 }
236 }
237
238 private static void exit(String msg, int errorCode) {
239 System.err.println("Error: " + msg);
240 System.exit(errorCode);
241 }
242
243 private static void exit(String msg) {
244 exit(msg, 1);
245 }
246
247 protected static void parseCmdLine(String[] args) {
248
249 String hostName = null;
250 String service = null;
251 String orgBaseDN = null;
252 String name = System.getProperty("user.name");
253
254 for (int i = 0; i < args.length; i++) {
255 if (args[i].equalsIgnoreCase("-version")) {
256 System.err.println(Version.getVersion());
257 System.exit(1);
258 } else if (args[i].equalsIgnoreCase("-help")
259 || args[i].equalsIgnoreCase("-h")
260 || args[i].equalsIgnoreCase("-?")) {
261 exit(USAGE, 0);
262 } else if (args[i].equalsIgnoreCase("-cn")
263 || args[i].equalsIgnoreCase("-commonname")) {
264 i++;
265 if (i == args.length) {
266 exit("-cn requires an argument");
267 } else {
268 // common name specified
269 name = args[i];
270 }
271 } else if (args[i].equalsIgnoreCase("-service")) {
272 i++;
273 if (i == args.length) {
274 exit("-service requires an argument");
275 } else {
276 // user certificate directory specified
277 service = args[i];
278 }
279 } else if (args[i].equalsIgnoreCase("-host")) {
280 i++;
281 if (i == args.length) {
282 exit("-host requires an argument");
283 } else {
284 // host name specified
285 hostName = args[i];
286 }
287 } else if (args[i].equalsIgnoreCase("-dir")) {
288 i++;
289 if (i == args.length) {
290 exit("-dir requires an argument");
291 } else {
292 // user certificate directory specified
293 dir = args[i];
294 }
295 } else if (args[i].equalsIgnoreCase("-prefix")) {
296 i++;
297 if (i == args.length) {
298 exit("-prefix requires an argument");
299 } else {
300 prefix = args[i];
301 }
302 } else if (args[i].equalsIgnoreCase("-nopw")
303 || args[i].equalsIgnoreCase("-nodes")
304 || args[i].equalsIgnoreCase("-nopassphrase")) {
305 // no password
306 noPswd = true;
307 } else if (args[i].equalsIgnoreCase("-verbose")) {
308 verbose = true;
309 } else if (args[i].equalsIgnoreCase("-int") ||
310 args[i].equalsIgnoreCase("-interactive")) {
311 // interactive mode
312 interactive = true;
313 } else if (args[i].equalsIgnoreCase("-force")) {
314 // overwrite existing credentials
315 force = true;
316 } else if (args[i].equalsIgnoreCase("-debug")) {
317 // overwrite existing credentials
318 debug = true;
319 } else if (args[i].equalsIgnoreCase("-caEmail")) {
320 i++;
321 if (i == args.length) {
322 exit("-caEmail requires an argument");
323 } else {
324 caEmail = args[i];
325 }
326 } else if (args[i].equalsIgnoreCase("-orgBaseDN")) {
327 i++;
328 if (i == args.length) {
329 exit("-orgBaseDN requires an argument");
330 } else {
331 orgBaseDN = args[i];
332 }
333 } else {
334 exit("argument #"
335 + (i+1)
336 + "("
337 + args[i]
338 + ") : unknown");
339 }
340 }
341
342 if (orgBaseDN == null) {
343 CoGProperties props = CoGProperties.getDefault();
344 orgBaseDN = props.getProperty("orgBaseDN");
345 if (orgBaseDN == null) {
346 if (interactive) {
347 orgBaseDN = getOrgName();
348 } else {
349 // just a default
350 orgBaseDN = "O=Grid";
351 }
352 }
353 }
354
355 if (service != null) {
356 if (hostName == null) {
357 exit("-host required");
358 } else {
359 cn = orgBaseDN + ", CN=" + service + "/" + hostName;
360 noPswd = true;
361 if (prefix == null) {
362 prefix = service;
363 }
364 if (dir == null && ConfigUtil.getOS() == ConfigUtil.UNIX_OS) {
365 dir = "/etc/grid-security/" + service;
366 }
367 }
368 } else if (hostName != null) {
369 cn = orgBaseDN + ", CN=host/" + hostName;
370 noPswd = true;
371 if (prefix == null) {
372 prefix = "host";
373 }
374 if (dir == null && ConfigUtil.getOS() == ConfigUtil.UNIX_OS) {
375 dir = "/etc/grid-security";
376 }
377 } else {
378 cn = orgBaseDN + ", CN=" + name;
379 if (prefix == null) {
380 prefix = "user";
381 }
382 }
383
384 if (dir == null) {
385 dir = System.getProperty("user.home") +
386 File.separator +
387 ".globus";
388 }
389 }
390
391 /**
392 * Generates a encrypted private key and certificate request.
393 */
394 static public void genCertificateRequest(String dname,
395 String emailAddressOfCA,
396 String password,
397 File keyFile,
398 File certFile,
399 File certReqFile)
400 throws Exception {
401
402 String sigAlgName = "MD5WithRSA";
403 String keyAlgName = "RSA";
404
405 CertUtil.init();
406
407 X509Name name = new X509Name(dname);
408
409 String certSubject = X509NameHelper.toString(name);
410
411 System.out.println("Generating a 1024 bit RSA private key");
412
413 // Generate a new key pair.
414 KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName);
415 keygen.initialize(1024);
416 KeyPair keyPair = keygen.genKeyPair();
417 PrivateKey privKey = keyPair.getPrivate();
418 PublicKey pubKey = keyPair.getPublic();
419
420 // Generate the certificate request.
421 DERSet derSet = new DERSet();
422 PKCS10CertificationRequest request =
423 new PKCS10CertificationRequest(
424 sigAlgName,
425 name,
426 pubKey,
427 derSet,
428 privKey);
429
430 // Save the certificate request to a .pem file.
431 byte[] data = request.getEncoded();
432 byte[] encodedData = Base64.encode(data);
433
434 PrintStream ps = null;
435
436 try {
437 ps = new PrintStream(new FileOutputStream(certReqFile));
438
439 boolean caEmail = false;
440
441 if ((emailAddressOfCA != null) &&
442 (emailAddressOfCA.length() > 0)) {
443 caEmail = true;
444 ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA);
445 } else {
446 ps.print("\n\n" + "Please send the following certificate request to the Certificate Authority (CA). Refer to CA instructions for details on to send the request.");
447 }
448 ps.print("\n\n"
449 + "==================================================================\n"
450 + "\n"
451 + "Certificate Subject:\n"
452 + "\n"
453 + certSubject
454 + "\n"
455 + "\n"
456 + "The above string is known as your user certificate subject, and it \n"
457 + "uniquely identifies this user.\n"
458 + "\n"
459 + "To install this user certificate, please save this e-mail message\n"
460 + "into the following file.\n"
461 + "\n"
462 + "\n"
463 + certReqFile.getAbsolutePath()
464 + "\n"
465 + "\n"
466 + "\n"
467 + " You need not edit this message in any way. Simply \n"
468 + " save this e-mail message to the file.\n"
469 + "\n"
470 + "\n"
471 + "If you have any questions about the certificate contact\n"
472 + "the Certificate Authority");
473 if (caEmail) {
474 ps.print("at " + emailAddressOfCA);
475 }
476 ps.print("\n\n");
477 PEMUtils.writeBase64(ps,
478 "-----BEGIN CERTIFICATE REQUEST-----",
479 encodedData,
480 "-----END CERTIFICATE REQUEST-----");
481 } finally {
482 if (ps != null) {
483 ps.close();
484 }
485 }
486
487 // Save private key to a .pem file.
488 OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey);
489 if (password != null) {
490 key.encrypt(password);
491 }
492 // this will set the permissions correctly already
493 key.writeTo(keyFile.getAbsolutePath());
494
495 // Create an empty cert file.
496 certFile.createNewFile();
497
498 System.out.println("A private key and a certificate request has been generated with the subject:");
499 System.out.println();
500 System.out.println(certSubject);
501 System.out.println();
502
503 System.out.println("The private key is stored in " +
504 keyFile.getAbsolutePath());
505 System.out.println("The request is stored in " +
506 certReqFile.getAbsolutePath());
507
508 }
509
510 private static String getOrgName() {
511
512 System.out.println("-----");
513 System.out.println("You are about to be asked to enter information that will be incorporated");
514 System.out.println("into your certificate request.");
515 System.out.println("What you are about to enter is what is called a Distinguished Name or a DN.");
516 System.out.println("Enter organization DN by entering individual component names and their values.");
517 System.out.println("The component name can be one of: " + X509Name.DefaultLookUp.keySet());
518 System.out.println("-----");
519
520 StringBuffer orgName = new StringBuffer();
521 String component = null;
522 while ( (component = getComponent()) != null ) {
523 if (orgName.length() != 0) {
524 orgName.append(", ");
525 }
526 orgName.append(component);
527 }
528
529 if (orgName.length() == 0) {
530 exit("Invalid organization DN");
531 }
532
533 return orgName.toString();
534 }
535
536 private static String getComponent() {
537 String component = null;
538
539 while (true) {
540 component = Util.getInput("Enter name component: ");
541 if (component == null || component.trim().length() == 0) {
542 return null;
543 }
544 component = component.trim();
545 if (X509Name.DefaultLookUp.get(component.toLowerCase()) == null) {
546 System.out.println("Invalid component name");
547 } else {
548 break;
549 }
550 }
551
552 component = component.toUpperCase();
553
554 String value = Util.getInput("Enter '" + component + "' value: ");
555 if (value == null || value.trim().length() == 0) {
556 return null;
557 }
558 return component + "=" + value.trim();
559 }
560
561
562
563 }